// app/screens-settings.jsx — sync, notifications, read-aloud, plan, widgets.
const { useState: useStateS, useMemo: useMemoS } = React;

// Deepgram Aura voices served by the Cloudflare TTS Worker (/api/tts).
const AURA_VOICES = [
  { id: 'asteria', label: 'Asteria — warm (F)' },
  { id: 'luna', label: 'Luna — gentle (F)' },
  { id: 'stella', label: 'Stella — clear (F)' },
  { id: 'athena', label: 'Athena — mature (F)' },
  { id: 'orion', label: 'Orion — reverent (M)' },
  { id: 'arcas', label: 'Arcas — natural (M)' },
  { id: 'angus', label: 'Angus — Irish (M)' },
  { id: 'perseus', label: 'Perseus — deep (M)' },
];

function Section({ t, title, children, note }) {
  return (
    <div style={{ marginTop: 22 }}>
      <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: t.ink3, fontWeight: 700, padding: '0 6px 9px' }}>{title}</div>
      <div style={{ background: t.surface, borderRadius: 18, border: `1px solid ${t.line}`, overflow: 'hidden' }}>{children}</div>
      {note && <div style={{ fontSize: 11.5, color: t.ink3, padding: '8px 6px 0', lineHeight: 1.4 }}>{note}</div>}
    </div>
  );
}
function Row({ t, label, sub, right, onClick, first }) {
  return (
    <div onClick={onClick} className={onClick ? 'bom-press' : ''} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', cursor: onClick ? 'pointer' : 'default', borderTop: first ? 'none' : `1px solid ${t.hairline}` }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, color: t.ink, fontWeight: 600 }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: t.ink3, fontWeight: 500, marginTop: 1 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}
function Toggle({ t, accent, on, onChange }) {
  return (
    <div onClick={(e) => { e.stopPropagation(); onChange(!on); }} className="bom-press" style={{ width: 46, height: 28, borderRadius: 999, background: on ? accent.base : t.sunken, position: 'relative', cursor: 'pointer', flexShrink: 0 }}>
      <div style={{ position: 'absolute', top: 3, left: on ? 21 : 3, width: 22, height: 22, borderRadius: 999, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.3)', transition: 'left 0.2s' }} />
    </div>
  );
}

// faux lock screen showing the three lock widgets
function LockScreenMock({ accent, font, day, dayNum, pct }) {
  return (
    <div style={{ borderRadius: 22, overflow: 'hidden', height: 290, position: 'relative', background: 'linear-gradient(165deg,#2a3a5c 0%,#16243f 55%,#0a1322 100%)' }}>
      <div style={{ position: 'absolute', inset: 0, padding: '20px 22px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        {/* inline above clock */}
        <div style={{ marginTop: 6 }}><WidgetLockInline day={day} dayNum={dayNum} /></div>
        {/* clock */}
        <div style={{ fontSize: 70, color: '#fff', fontWeight: 300, letterSpacing: '-0.02em', lineHeight: 1, marginTop: 2, fontFamily: '-apple-system, system-ui' }}>9:41</div>
        <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.85)', fontWeight: 500, marginTop: 2 }}>Sunday, June 7</div>
        {/* widget row */}
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginTop: 22 }}>
          <WidgetLockCircular day={day} dayNum={dayNum} pct={pct} />
          <WidgetLockRect day={day} dayNum={dayNum} pct={pct} font={font} />
        </div>
      </div>
    </div>
  );
}

function SettingsScreen({ t, accent, font, state, patch, plan, stats, themeKey, accentKey, onNotify, onSyncNow }) {
  const [copied, setCopied] = useStateS(false);
  const [syncMsg, setSyncMsg] = useStateS('');
  function copyText(v) { try { navigator.clipboard && navigator.clipboard.writeText(v); } catch (e) {} }
  async function doSyncNow() {
    if (!onSyncNow) return;
    setSyncMsg('Syncing…');
    try { await onSyncNow(); setSyncMsg('Synced just now'); }
    catch (e) { setSyncMsg('Offline — will retry'); }
    setTimeout(() => setSyncMsg(''), 4000);
  }
  const engineLabel = (window.BomAudio && window.BomAudio.engine()) || 'device';
  const widgetURL = ((window.BOM_CONFIG && window.BOM_CONFIG.siteURL) || 'https://byyearsend.pages.dev') + '/api/today';
  const todayDate = window.ymd(window.today());
  const dInfo = useMemoS(() => {
    let i = plan.days.findIndex(d => d.date === todayDate);
    if (i < 0) i = Math.min(stats.done, plan.days.length - 1);
    const day = plan.days[i] || plan.days[0];
    const verse = window.VERSES_OF_DAY[i % window.VERSES_OF_DAY.length];
    return { day, dayNum: i + 1, verse };
  }, [plan, stats]);

  function copyCode() { copyText(state.syncCode); setCopied('code'); setTimeout(() => setCopied(false), 1600); }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '52px 20px 6px' }}>
        <div style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: accent.base, fontWeight: 700 }}>Manage</div>
        <div style={{ fontFamily: font, fontSize: 26, color: t.ink, fontWeight: 600, marginTop: 2 }}>Settings</div>
      </div>

      <div className="bom-scroll" style={{ flex: 1, overflowY: 'auto', padding: '6px 18px 120px' }}>
        {/* WIDGETS */}
        <div style={{ marginTop: 16 }}>
          <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: t.ink3, fontWeight: 700, padding: '0 6px 9px' }}>Home Screen widgets</div>
          <div style={{ display: 'flex', gap: 14, overflowX: 'auto', padding: '4px 2px 8px' }} className="bom-scroll">
            <div style={{ flexShrink: 0 }}><WidgetHomeSmall accent={accent} font={font} day={dInfo.day} dayNum={dInfo.dayNum} total={plan.days.length} pct={stats.pct} streak={stats.streak} /></div>
            <div style={{ flexShrink: 0 }}><WidgetHomeMedium accent={accent} font={font} day={dInfo.day} dayNum={dInfo.dayNum} total={plan.days.length} pct={stats.pct} streak={stats.streak} verse={dInfo.verse} /></div>
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: t.ink3, fontWeight: 700, padding: '0 6px 9px' }}>Lock Screen</div>
          <LockScreenMock accent={accent} font={font} day={dInfo.day} dayNum={dInfo.dayNum} pct={stats.pct} />
          <div style={{ marginTop: 10, background: t.surface, borderRadius: 16, border: `1px solid ${t.line}`, overflow: 'hidden' }}>
            <Row t={t} first label="Hosted Scriptable widget" sub="Installs once · updates live from your site" right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: accent.base, fontSize: 12, fontWeight: 700 }}><span style={{ width: 7, height: 7, borderRadius: 999, background: accent.base }} />Live</span>} />
            <Row t={t} label="Widget feed" sub={widgetURL} onClick={() => { copyText(widgetURL); setCopied('url'); setTimeout(() => setCopied(false), 1600); }} right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: accent.base, fontSize: 12.5, fontWeight: 700 }}>{copied === 'url' ? 'Copied!' : 'Copy'}<Icon name={copied === 'url' ? 'check' : 'bookmark'} size={15} stroke={2} /></span>} />
            <Row t={t} label="Scriptable setup code" sub="Paste once into a new Scriptable script" onClick={() => { copyText(window.BOM_WIDGET_LOADER || ''); setCopied('loader'); setTimeout(() => setCopied(false), 1600); }} right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: accent.base, fontSize: 12.5, fontWeight: 700 }}>{copied === 'loader' ? 'Copied!' : 'Copy'}<Icon name={copied === 'loader' ? 'check' : 'bookmark'} size={15} stroke={2} /></span>} />
          </div>
          <div style={{ fontSize: 11.5, color: t.ink3, padding: '9px 6px 0', lineHeight: 1.45 }}>
            Install once: tap <b>Scriptable setup code</b> above to copy the loader, open the Scriptable app, make a new script and paste it, then add a Scriptable widget to your Home or Lock Screen and pick it. The loader pulls today’s reading from the hosted feed each refresh, so any later tweak goes live automatically — no reinstall.
          </div>
        </div>

        {/* DAILY READING */}
        <Section t={t} title="Daily reading plan" note="Changing dates rebuilds the plan and rebalances verses per day. Completed days are kept.">
          <Row t={t} first label="Start date" right={<span style={{ color: t.ink3, fontSize: 14, fontWeight: 600 }}>{window.parseYMD(state.startDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</span>} />
          <Row t={t} label="Finish by" right={<span style={{ color: accent.base, fontSize: 14, fontWeight: 700 }}>{window.parseYMD(state.endDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</span>} />
          <Row t={t} label="Rest on Sundays" sub="Spread reading across six days" right={<Toggle t={t} accent={accent} on={(state.skipWeekdays || []).includes(0)} onChange={(v) => patch({ skipWeekdays: v ? [0] : [] })} />} />
          <Row t={t} label="Verses per day" right={<span style={{ color: t.ink3, fontSize: 14, fontWeight: 600 }}>~{plan.target}</span>} />
        </Section>

        {/* NOTIFICATIONS */}
        <Section t={t} title="Reminders & notifications">
          <Row t={t} first label="Daily reading reminder" sub="Push notification each morning" right={<Toggle t={t} accent={accent} on={state.notifyOn} onChange={(v) => (onNotify ? onNotify(v) : patch({ notifyOn: v }))} />} />
          <Row t={t} label="Reminder time" right={
            <label style={{ position: 'relative' }}>
              <span style={{ color: accent.base, fontSize: 14, fontWeight: 700 }}>{fmtTime(state.notifyTime)}</span>
              <input type="time" value={state.notifyTime} onChange={(e) => e.target.value && patch({ notifyTime: e.target.value })} style={{ position: 'absolute', inset: 0, opacity: 0, width: '100%', cursor: 'pointer' }} />
            </label>
          } />
          <Row t={t} label="Streak reminders" sub="Nudge me if I’m about to break a streak" right={<Toggle t={t} accent={accent} on={state.streakReminders !== false} onChange={(v) => patch({ streakReminders: v })} />} />
          <Row t={t} label="Verse of the day" right={<Toggle t={t} accent={accent} on={state.votdOn !== false} onChange={(v) => patch({ votdOn: v })} />} />
        </Section>

        {/* READ ALOUD */}
        <Section t={t} title="Read aloud" note="Natural voices stream from your Cloudflare Worker (Deepgram Aura) and are cached per verse. With no connection, the app falls back to the best on-device voice automatically.">
          <Row t={t} first label="Narration engine" sub={engineLabel === 'cloud' ? 'Natural cloud voice' : 'On-device voice (offline)'} right={
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: engineLabel === 'cloud' ? accent.base : t.ink3, fontSize: 12.5, fontWeight: 700 }}>
              <Icon name={engineLabel === 'cloud' ? 'cloud' : 'phone'} size={16} stroke={1.9} />
              {engineLabel === 'cloud' ? 'Aura · Live' : 'Device'}
            </span>
          } />
          <Row t={t} label="Narration voice" right={
            <select value={state.voice} onChange={(e) => patch({ voice: e.target.value })} style={selStyle(t, accent)}>
              {AURA_VOICES.map(v => <option key={v.id} value={v.id}>{v.label}</option>)}
            </select>
          } />
          <Row t={t} label="Default speed" right={
            <div style={{ display: 'flex', gap: 4 }}>
              {[0.75, 1, 1.25, 1.5].map(r => (
                <button key={r} onClick={() => patch({ rate: r })} className="bom-press" style={{ border: 'none', cursor: 'pointer', borderRadius: 8, padding: '5px 9px', fontSize: 12.5, fontWeight: 700, fontFamily: 'inherit', background: state.rate === r ? accent.base : t.sunken, color: state.rate === r ? accent.ink : t.ink2 }}>{r}×</button>
              ))}
            </div>
          } />
          <Row t={t} label="Highlight verses while reading" right={<Toggle t={t} accent={accent} on={state.highlightOn !== false} onChange={(v) => patch({ highlightOn: v })} />} />
        </Section>

        {/* SYNC */}
        <Section t={t} title="Sync across devices" note="Your plan, progress, and streak stay in sync on every device signed in with the same code.">
          <Row t={t} first label="iCloud sync" sub="Automatic backup & restore" right={<Toggle t={t} accent={accent} on={state.icloudOn !== false} onChange={(v) => patch({ icloudOn: v })} />} />
          <Row t={t} label="Sync code" sub="Share to link another device" onClick={copyCode} right={
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: accent.base, fontSize: 13, fontWeight: 700, fontFamily: "'Inter', sans-serif", letterSpacing: '0.04em' }}>
              {copied === 'code' ? 'Copied!' : state.syncCode}<Icon name={copied === 'code' ? 'check' : 'bookmark'} size={15} stroke={2} />
            </span>
          } />
          <Row t={t} label="This device" sub={syncMsg || 'Reading on this device'} right={
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: accent.base, fontSize: 12, fontWeight: 700 }}><span style={{ width: 7, height: 7, borderRadius: 999, background: accent.base }} />Live</span>
          } />
          <Row t={t} label="Sync now" sub="Push & pull the latest" onClick={doSyncNow} right={<span style={{ color: accent.base, display: 'flex' }}><Icon name="sync" size={20} stroke={1.9} /></span>} />
        </Section>

        {/* APPEARANCE */}
        <Section t={t} title="Appearance" note="Tip: open Tweaks (top toolbar) to preview every theme, accent and reading face live.">
          <Row t={t} first label="Theme" right={<span style={{ color: t.ink3, fontSize: 14, fontWeight: 600 }}>{(window.THEMES[themeKey] || {}).label}</span>} />
          <Row t={t} label="Accent" right={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: t.ink3, fontSize: 14, fontWeight: 600 }}>{(window.ACCENTS[accentKey] || {}).label}<span style={{ width: 18, height: 18, borderRadius: 999, background: accent.base, border: `1px solid ${t.line}` }} /></span>} />
        </Section>

        {/* ABOUT */}
        <Section t={t} title="About">
          <Row t={t} first label="Reset progress" sub="Clear completed days (keeps your plan)" onClick={() => { if (confirm('Clear all completed days? Your plan and dates stay.')) patch({ completed: {} }); }} right={<span style={{ color: '#c0492f', fontSize: 13, fontWeight: 700 }}>Reset</span>} />
          <Row t={t} label="Start a new plan" sub="Re-enter start and finish dates" onClick={() => { if (confirm('Start over? This returns you to setup.')) patch({ onboarded: false }); }} right={<Icon name="chevron" size={18} stroke={2} style={{ color: t.ink3 }} />} />
          <Row t={t} label="Version" right={<span style={{ color: t.ink3, fontSize: 13, fontWeight: 600 }}>By Year’s End · 1.0</span>} />
        </Section>
      </div>
    </div>
  );
}

function fmtTime(hhmm) {
  if (!hhmm) return '7:00 AM';
  const [h, m] = hhmm.split(':').map(Number);
  const am = h < 12; const h12 = h % 12 === 0 ? 12 : h % 12;
  return `${h12}:${String(m).padStart(2, '0')} ${am ? 'AM' : 'PM'}`;
}
function selStyle(t, accent) {
  return { border: 'none', background: t.sunken, color: t.ink, fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit', borderRadius: 9, padding: '6px 8px', cursor: 'pointer' };
}

Object.assign(window, { SettingsScreen });
