// settings.jsx — Settings screen (dark-only, localized) (exported to window)

function Toggle({ on, onChange, accent }) {
  const { dir } = useI18n();
  const start = on ? 'flex-end' : 'flex-start';
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 50, height: 30, borderRadius: 99, border: 'none', cursor: 'pointer', padding: 2, flexShrink: 0,
      background: on ? `linear-gradient(135deg,${accent[0]},${accent[1]})` : 'rgba(140,140,160,.3)',
      boxShadow: on ? `0 0 12px ${accent[0]}77` : 'none', transition: 'background .25s',
      display: 'flex', justifyContent: start, alignItems: 'center',
    }}>
      <span style={{ width: 26, height: 26, borderRadius: '50%', background: '#fff', transition: 'all .25s', boxShadow: '0 1px 3px rgba(0,0,0,.35)' }} />
    </button>
  );
}

function Chevron({ th, dir }) {
  return <span style={{ display: 'flex', color: th.ghost, transform: dir === 'rtl' ? 'scaleX(-1)' : 'none' }}><IconChevron size={18} /></span>;
}

function Row({ icon, title, sub, right, accent, th, onClick, last }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '15px 16px', cursor: onClick ? 'pointer' : 'default',
      borderBottom: last ? 'none' : '1px solid ' + th.border,
    }}>
      <span style={{
        width: 34, height: 34, borderRadius: 10, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: `linear-gradient(140deg, ${accent[0]}33, ${accent[1]}22)`, color: accent[0],
      }}>{icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 300, color: th.text }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: th.faint, marginTop: 2 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

function Card({ children, th }) {
  return <div style={{ borderRadius: 22, background: th.surface, border: '1px solid ' + th.border, overflow: 'hidden' }}>{children}</div>;
}

// ── PairingSheet — cross-device sync without an account ────────────────────────────
// Two flows: SHOW a code (on the device that already holds the data) or ENTER a code
// (on the new device, which then adopts the same identity and merges its local progress).
function PairingSheet({ th, accent, onClose, createPairingCode, linkWithCode }) {
  const { t } = useI18n();
  const [mode, setMode] = React.useState('choose'); // choose | show | enter
  const [code, setCode] = React.useState('');
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState(null);       // { kind: 'error'|'ok', text }

  const genCode = async () => {
    setMode('show'); setMsg(null); setCode(''); setBusy(true);
    const r = await createPairingCode();
    setBusy(false);
    if (r && r.code) setCode(r.code);
    else setMsg({ kind: 'error', text: t('pair_err_gen') });
  };
  const submit = async () => {
    const v = input.trim().toUpperCase();
    if (v.length < 6) { setMsg({ kind: 'error', text: t('pair_err_code') }); return; }
    setBusy(true); setMsg(null);
    const r = await linkWithCode(v);
    setBusy(false);
    setMsg(r && r.ok ? { kind: 'ok', text: t('pair_linked') } : { kind: 'error', text: t('pair_err_invalid') });
  };

  const bigBtn = (title, sub, onClick, primary) => (
    <button onClick={onClick} data-haptic="medium" style={{
      width: '100%', textAlign: 'start', padding: '15px 16px', borderRadius: 16, cursor: 'pointer', marginBottom: 10,
      border: '1px solid ' + (primary ? accent[0] + '66' : th.border), fontFamily: 'inherit',
      background: primary ? `linear-gradient(135deg, ${accent[0]}26, ${th.surface})` : th.surface, color: th.text,
      display: 'flex', flexDirection: 'column', gap: 3,
    }}>
      <span style={{ fontSize: 15, fontWeight: 400 }}>{title}</span>
      <span style={{ fontSize: 12, color: th.faint }}>{sub}</span>
    </button>
  );

  return (
    <Sheet title={t('multi_sync')} onClose={onClose} th={th}>
      {mode === 'choose' && (
        <div>
          <div style={{ fontSize: 13, color: th.dim, lineHeight: 1.5, margin: '0 2px 16px', fontWeight: 300 }}>{t('pair_intro')}</div>
          {bigBtn(t('pair_show_btn'), t('pair_show_btn_sub'), genCode, true)}
          {bigBtn(t('pair_enter_btn'), t('pair_enter_btn_sub'), () => { setMode('enter'); setMsg(null); }, false)}
        </div>
      )}

      {mode === 'show' && (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 13, color: th.dim, lineHeight: 1.5, margin: '0 4px 18px', fontWeight: 300 }}>{t('pair_show_hint')}</div>
          <div style={{
            fontSize: 34, fontWeight: 500, letterSpacing: 6, color: th.text, padding: '18px 12px', borderRadius: 16,
            background: `linear-gradient(135deg, ${accent[0]}22, ${th.surface})`, border: '1px solid ' + accent[0] + '55',
            fontVariantNumeric: 'tabular-nums', minHeight: 40,
          }}>{busy ? '…' : (code || '—')}</div>
          {msg && <div style={{ fontSize: 12.5, marginTop: 12, color: msg.kind === 'ok' ? accent[0] : '#FF6B6B' }}>{msg.text}</div>}
          <div style={{ fontSize: 11.5, color: th.faint, marginTop: 12 }}>{t('pair_expires')}</div>
          <button onClick={() => { setMode('choose'); setMsg(null); }} style={{ marginTop: 18, padding: '12px 22px', borderRadius: 14, cursor: 'pointer',
            background: 'transparent', border: '1px solid ' + th.border2, color: th.text, fontFamily: 'inherit', fontSize: 14 }}>{t('pair_back')}</button>
        </div>
      )}

      {mode === 'enter' && (
        <div>
          <div style={{ fontSize: 13, color: th.dim, lineHeight: 1.5, margin: '0 2px 16px', fontWeight: 300 }}>{t('pair_enter_hint')}</div>
          <input value={input} onChange={(e) => setInput(e.target.value.toUpperCase())} placeholder={t('pair_input_ph')}
            autoCapitalize="characters" autoCorrect="off" spellCheck={false} maxLength={12}
            style={{ width: '100%', boxSizing: 'border-box', padding: '15px 16px', borderRadius: 14, fontFamily: 'inherit',
              fontSize: 20, letterSpacing: 4, textAlign: 'center', textTransform: 'uppercase',
              background: th.surface2, border: '1px solid ' + th.border2, color: th.text, outline: 'none' }} />
          {msg && <div style={{ fontSize: 12.5, marginTop: 12, textAlign: 'center', color: msg.kind === 'ok' ? accent[0] : '#FF6B6B' }}>{msg.text}</div>}
          <button onClick={submit} disabled={busy} data-haptic="success" style={{ width: '100%', marginTop: 16, padding: '15px', borderRadius: 14,
            cursor: busy ? 'default' : 'pointer', border: 'none', color: '#fff', fontFamily: 'inherit', fontSize: 15,
            background: `linear-gradient(135deg, ${accent[0]}, ${accent[1]})`, opacity: busy ? 0.6 : 1, boxShadow: `0 8px 22px ${accent[0]}44` }}>
            {busy ? t('pair_linking') : t('pair_link')}</button>
          <button onClick={() => { setMode('choose'); setMsg(null); setInput(''); }} style={{ width: '100%', marginTop: 10, padding: '12px', borderRadius: 14, cursor: 'pointer',
            background: 'transparent', border: '1px solid ' + th.border2, color: th.text, fontFamily: 'inherit', fontSize: 14 }}>{t('pair_back')}</button>
        </div>
      )}
    </Sheet>
  );
}

function SettingsScreen({ accent, th, settings, updateSettings, onReset, onToast, isPremium, onLocked, onOpenShare, onOpenQuotes, onOpenSync, onOpenHistory, focusShield, widgets, onOpenShield, onOpenWidgets }) {
  const { t, dir, lang } = useI18n();
  // Shared gold Premium pill on the right of locked premium rows (no extra padlock).
  const premiumTag = <PremiumPill />;
  return (
    <div className="scroll-area" style={{ height: '100%', padding: '64px 20px 96px' }}>
      <div style={{ fontSize: 30, fontWeight: 300, letterSpacing: .3, color: th.text }}>{t('settings_title')}</div>

      {/* premium banner */}
      {isPremium ? (
        <div style={{ marginTop: 18, padding: '14px 16px', borderRadius: 18, display: 'flex', alignItems: 'center', gap: 12,
          background: `linear-gradient(135deg, ${accent[0]}22, ${accent[1]}11)`, border: '1px solid ' + accent[0] + '55' }}>
          <span style={{ color: accent[0], display: 'flex' }}><IconCrown size={20} /></span>
          <span style={{ fontSize: 14.5, color: th.text, fontWeight: 400, flex: 1 }}>{t('premium_active')}</span>
          <span style={{ color: accent[0], display: 'flex' }}><IconCheck size={20} /></span>
        </div>
      ) : (
        <div onClick={() => onLocked('settings')} style={{ marginTop: 18, padding: '16px', borderRadius: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 13,
          background: `linear-gradient(135deg, ${accent[0]}1f, ${accent[1]}12)`, border: '1px solid ' + accent[0] + '44' }}>
          <span style={{ width: 38, height: 38, borderRadius: 12, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: `linear-gradient(140deg, ${accent[0]}44, ${accent[1]}33)`, color: '#fff' }}><IconCrown size={20} /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 400, color: th.text }}>{t('premium_cta')}</div>
            <div style={{ fontSize: 12.5, color: th.dim, marginTop: 2 }}>{t('premium_sub')}</div>
          </div>
          <span style={{ color: accent[0], display: 'flex', flexShrink: 0, transform: dir === 'rtl' ? 'scaleX(-1)' : 'none' }}><IconChevron size={18} /></span>
        </div>
      )}

      <SectionTitle th={th}>{t('preferences')}</SectionTitle>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconBell size={19} />} title={t('notifications')} sub={t('notifications_sub')}
             right={<Toggle on={settings.notifications} accent={accent} onChange={(v) => updateSettings({ notifications: v })} />} />
        <Row th={th} accent={accent} icon={<IconVolume size={19} />} title={t('sound_effects')} sub={t('sound_effects_sub')}
             right={<Toggle on={settings.sounds} accent={accent} onChange={(v) => updateSettings({ sounds: v })} />} />
        <Row th={th} accent={accent} icon={<IconSparkle size={19} />} title={t('quotes_label')} sub={t('quotes_sub')}
             right={<Toggle on={settings.quotes !== false} accent={accent} onChange={(v) => updateSettings({ quotes: v })} />} />
        <Row th={th} accent={accent} icon={<IconWave size={19} />} title={t('haptics')} sub={t('haptics_sub')}
             right={<Toggle on={settings.haptics} accent={accent} onChange={(v) => { updateSettings({ haptics: v }); if (v) haptic(18, true); }} />} />
        <Row th={th} accent={accent} icon={<IconChart size={19} />} title={t('show_progress')} sub={t('show_progress_sub')}
             right={<Toggle on={settings.showProgress === true} accent={accent} onChange={(v) => updateSettings({ showProgress: v })} />} last />
      </Card>

      <SectionTitle th={th}>{t('focus_blocking')}</SectionTitle>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconShield size={19} />} title={t('focus_shield')}
             sub={focusShield && focusShield.enabled ? t('shield_on') : t('focus_shield_sub')}
             onClick={onOpenShield} right={<Chevron th={th} dir={dir} />} />
        <Row th={th} accent={accent} icon={<IconDevices size={19} />} title={t('widgets_live')} sub={t('widgets_sub')}
             onClick={onOpenWidgets} last right={<Chevron th={th} dir={dir} />} />
      </Card>

      <SectionTitle th={th}>{t('session_history')}</SectionTitle>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconClock size={19} />} title={t('session_history')} sub={t('session_history_sub')}
             onClick={onOpenHistory} last right={<Chevron th={th} dir={dir} />} />
      </Card>

      <SectionTitle th={th}>{t('reminders')}</SectionTitle>
      <div style={{ fontSize: 12.5, color: th.faint, margin: '-6px 2px 12px', lineHeight: 1.5, fontWeight: 300 }}>{t('notif_strategy')}</div>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconBell size={19} />} title={t('notif_daily')} sub={t('notif_daily_sub')}
             right={<Toggle on={settings.notifDaily !== false} accent={accent} onChange={(v) => updateSettings({ notifDaily: v })} />} />
        <Row th={th} accent={accent} icon={<IconStreak size={19} />} title={t('notif_streak')} sub={t('notif_streak_sub')}
             right={<Toggle on={settings.notifStreak !== false} accent={accent} onChange={(v) => updateSettings({ notifStreak: v })} />} />
        <Row th={th} accent={accent} icon={<IconCalendar size={19} />} title={t('notif_weekly')} sub={t('notif_weekly_sub')}
             right={<Toggle on={settings.notifWeekly !== false} accent={accent} onChange={(v) => updateSettings({ notifWeekly: v })} />} last />
      </Card>

      {/* Premium features grouped together (locked behind the paywall when not subscribed) */}
      <SectionTitle th={th}>{t('premium')}</SectionTitle>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconQuote size={19} />} title={t('personalized_quotes')} sub={t('personalized_quotes_sub')}
             onClick={isPremium ? onOpenQuotes : () => onLocked('quotes')}
             right={isPremium ? <Chevron th={th} dir={dir} /> : premiumTag} />
        <Row th={th} accent={accent} icon={<IconDevices size={19} />} title={t('multi_sync')} sub={t('multi_sync_sub')}
             onClick={isPremium ? onOpenSync : () => onLocked('sync')} last
             right={isPremium ? <Chevron th={th} dir={dir} /> : premiumTag} />
      </Card>

      <SectionTitle th={th}>{t('language')}</SectionTitle>
      <Card th={th}>
        {LANGS.map((l, i) => (
          <Row key={l.code} th={th} accent={accent} icon={<IconGlobe size={19} />} title={l.native}
               onClick={() => updateSettings({ language: l.code })} last={i === LANGS.length - 1}
               right={lang === l.code ? <span style={{ color: accent[0], display: 'flex' }}><IconCheck size={20} /></span> : null} />
        ))}
      </Card>

      <SectionTitle th={th}>{t('share')}</SectionTitle>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconShare size={19} />} title={t('share_progress')} sub={t('share_progress_sub')}
             onClick={onOpenShare} last right={<Chevron th={th} dir={dir} />} />
      </Card>

      <SectionTitle th={th}>{t('data')}</SectionTitle>
      <Card th={th}>
        <Row th={th} accent={accent} icon={<IconReset size={19} />} title={t('reset_progress')} sub={t('reset_progress_sub')}
             onClick={onReset} last right={<Chevron th={th} dir={dir} />} />
      </Card>

      <div style={{ textAlign: 'center', marginTop: 30, color: th.ghost, fontSize: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'center' }}><Wordmark size={16} track={6} /></div>
        <div style={{ marginTop: 8 }}>{t('version_line')}</div>
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScreen, PairingSheet, Toggle, SettingsRow: Row, SettingsCard: Card });

  