// settings.jsx — full-screen, top-to-bottom Settings screen (replaces the
// floating Tweaks panel). Styled in the app's own glass/dark language and
// driven by the same useTweaks state. Exposes window.SettingsScreen.
(function () {
const { useEffect, useState } = React;
const Ico = window.Ico;
const fx = (t) => (t.effects && t.effects.blur && t.effects.blur !== 'none')
  ? { backdropFilter: t.effects.blur, WebkitBackdropFilter: t.effects.blur } : {};
const cardBorderOf = (t) => t.cardBorder !== undefined ? t.cardBorder : (t.mode === 'dark' ? `1px solid ${t.color.border}` : 'none');

// segmented control matching the app's pills
function Seg({ t, value, options, onChange, render }) {
  const lbl = render || ((o) => o);
  return (
    <div style={{ display: 'flex', gap: 3, background: t.color.surfaceAlt, borderRadius: t.radius.pill, padding: 3 }}>
      {options.map((o) => {
        const on = o === value;
        return (
          <button key={o} onClick={() => onChange(o)} style={{
            flex: '0 0 auto', padding: '7px 14px', borderRadius: t.radius.pill, border: 'none', cursor: 'pointer',
            fontFamily: t.font.head, fontSize: 13, fontWeight: 600,
            background: on ? t.color.accent : 'transparent', color: on ? t.color.accentText : t.color.textMuted,
            transition: 'background .15s, color .15s', minWidth: 56,
          }}>{lbl(o)}</button>
        );
      })}
    </div>
  );
}

function Toggle({ t, value, onChange }) {
  return (
    <button onClick={() => onChange(!value)} aria-pressed={value} style={{
      position: 'relative', width: 46, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer', padding: 0,
      background: value ? t.color.accent : t.color.checkRing, transition: 'background .2s',
    }}>
      <span style={{ position: 'absolute', top: 3, left: 3, width: 22, height: 22, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.3)', transform: value ? 'translateX(18px)' : 'none', transition: 'transform .2s cubic-bezier(.3,.8,.3,1)' }} />
    </button>
  );
}

function Swatches({ t, value, options, customColors, onChange, onAddCustom, onRemoveCustom }) {
  const inputRef = React.useRef(null);
  // Commit a custom color only when the native picker is confirmed/closed
  // ('change' event) — the input event fires on every drag tick and would
  // add dozens of near-identical swatches.
  React.useEffect(() => {
    const el = inputRef.current; if (!el) return;
    const commit = (e) => { onAddCustom && onAddCustom(e.target.value); };
    el.addEventListener('change', commit);
    return () => el.removeEventListener('change', commit);
  }, [onAddCustom]);
  const customs = (customColors || []).filter((c) => !options.some((o) => String(o).toLowerCase() === String(c).toLowerCase()));
  const wheel = 'conic-gradient(from 90deg, #ff3b30, #ff9500, #ffcc00, #34c759, #00c7be, #30b0c7, #007aff, #5856d6, #af52de, #ff2d55, #ff3b30)';
  const dot = (c, removable) => {
    const on = String(c).toLowerCase() === String(value).toLowerCase();
    return (
      <span key={c} style={{ position: 'relative', display: 'inline-flex' }}>
        <button onClick={() => onChange(c)} aria-label={c} style={{
          width: 30, height: 30, borderRadius: '50%', cursor: 'pointer', padding: 0, background: c,
          backgroundClip: 'padding-box',
          border: on ? `2px solid ${t.color.text}` : `2px solid ${t.color.border}`,
          transition: 'transform .12s', transform: on ? 'scale(1.06)' : 'none',
        }} />
        {removable && on && (
          <button onClick={(e) => { e.stopPropagation(); onRemoveCustom(c); }} aria-label="remove color" style={{
            position: 'absolute', top: -5, insetInlineEnd: -5, width: 16, height: 16, borderRadius: '50%', border: 'none', cursor: 'pointer',
            background: t.color.surface, color: t.color.textMuted, fontSize: 11, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: t.shadow.card,
          }}>×</button>
        )}
      </span>
    );
  };
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
      {options.map((c) => dot(c, false))}
      {customs.map((c) => dot(c, true))}
      {customs.length < 10 && (
        <button onClick={() => inputRef.current && inputRef.current.click()} title="Add a custom color" aria-label="Add a custom color" style={{
          width: 30, height: 30, borderRadius: '50%', cursor: 'pointer', padding: 0, background: wheel,
          backgroundClip: 'padding-box', overflow: 'hidden',
          border: `2px solid ${t.color.border}`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
        }}>
          <span style={{ width: 15, height: 15, borderRadius: '50%', background: t.color.surface, color: t.color.text, fontSize: 13, fontWeight: 700, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+</span>
        </button>
      )}
      <input ref={inputRef} type="color" defaultValue="#7b5bd6" aria-hidden="true" tabIndex={-1}
        onChange={(e) => { onChange(e.target.value); }}
        style={{ position: 'absolute', width: 1, height: 1, opacity: 0, pointerEvents: 'none', border: 0, padding: 0 }} />
    </div>
  );
}

function CompanionPick({ t, value, onChange }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
      {(window.COMPANIONS || []).map((c) => {
        const on = c.id === value;
        return (
          <button key={c.id} onClick={() => onChange(c.id)} title={c.name} aria-label={c.name} style={{
            padding: '5px 0 0', borderRadius: t.radius.chip, cursor: 'pointer',
            border: on ? `2px solid ${t.color.accent}` : `1px solid ${t.color.border}`,
            background: on ? t.color.accentSoft : t.color.surfaceAlt, display: 'flex', justifyContent: 'center', alignItems: 'flex-end', overflow: 'hidden',
          }}>
            <window.Companion id={c.id} size={34} />
          </button>
        );
      })}
    </div>
  );
}

function Row({ t, label, hint, control, stack }) {
  return (
    <div style={{
      display: 'flex', alignItems: stack ? 'flex-start' : 'center', justifyContent: 'space-between',
      gap: 14, padding: '14px 16px', flexDirection: stack ? 'column' : 'row',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: t.font.body, fontSize: 15, fontWeight: 500, color: t.color.text }}>{label}</div>
        {hint ? <div style={{ fontSize: 12.5, color: t.color.textFaint, marginTop: 2, lineHeight: 1.3 }}>{hint}</div> : null}
      </div>
      <div style={{ flex: '0 0 auto', width: stack ? '100%' : 'auto' }}>{control}</div>
    </div>
  );
}

function Section({ t, title, children }) {
  const cardBorder = cardBorderOf(t);
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ fontFamily: t.font.head, fontSize: 11.5, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: t.color.textMuted, padding: '0 6px 8px' }}>{title}</div>
      <div style={{ background: t.color.surface, ...fx(t), borderRadius: t.radius.card, border: cardBorder, boxShadow: t.shadow.card, overflow: 'hidden' }}>
        {React.Children.toArray(children).filter(Boolean).map((ch, i) => (
          <div key={i} style={{ borderTop: i > 0 ? `1px solid ${t.color.divider}` : 'none' }}>{ch}</div>
        ))}
      </div>
    </div>
  );
}

function SettingsScreen({ t, tw, setTweak, accents, open, onClose }) {
  const L = window.I18N_T ? window.I18N_T(tw.lang || 'en') : null;
  const tr = (k) => (L ? L.ui(k) : k);
  const dir = L ? L.dir : 'ltr';
  const optL = (o) => tr(String(o).toLowerCase());
  const langOpts = ['en', 'fi', 'ar'];
  const langName = (o) => (window.I18N && window.I18N[o] ? window.I18N[o].langName : o);
  const [mounted, setMounted] = useState(open);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (open) { setMounted(true); requestAnimationFrame(() => requestAnimationFrame(() => setShown(true))); }
    else { setShown(false); const id = setTimeout(() => setMounted(false), 280); return () => clearTimeout(id); }
  }, [open]);
  if (!mounted) return null;

  return (
    <div dir={dir} style={{
      position: 'absolute', inset: 0, zIndex: 70, display: 'flex', flexDirection: 'column',
      background: t.color.canvas, color: t.color.text, fontFamily: t.font.body, direction: dir,
      transform: shown ? 'translateY(0)' : 'translateY(100%)',
      transition: 'transform .3s cubic-bezier(.3,.8,.3,1)', overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{ flex: '0 0 auto', paddingTop: 'max(env(safe-area-inset-top, 0px), 10px)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 12px 12px' }}>
          <button onClick={onClose} aria-label="Back" style={{
            flex: '0 0 auto', width: 38, height: 38, borderRadius: t.radius.pill, border: 'none', cursor: 'pointer',
            background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
          }}><span style={{ display: 'inline-flex', transform: dir === 'rtl' ? 'scaleX(-1)' : 'none' }}>{Ico.back(t.color.text, 19)}</span></button>
          <div style={{ fontFamily: t.font.head, fontSize: 21, fontWeight: t.headerWeight, letterSpacing: t.titleSpacing, color: t.color.text }}>{tr('settings')}</div>
          <div style={{ flex: '1 1 auto' }} />
          <button onClick={onClose} style={{
            flex: '0 0 auto', padding: '9px 16px', borderRadius: t.radius.pill, border: 'none', cursor: 'pointer',
            background: t.color.accent, color: t.color.accentText, fontFamily: t.font.head, fontSize: 13.5, fontWeight: 700,
          }}>{tr('done')}</button>
        </div>
      </div>

      {/* scroll body */}
      <div className="noscroll" style={{ flex: '1 1 auto', overflowY: 'auto', padding: '4px 16px 24px' }}>
        <Section t={t} title={tr('appearance')}>
          <Row t={t} label={tr('mode')} control={<Seg t={t} value={tw.mode} options={['Dark', 'Light']} render={optL} onChange={(v) => setTweak('mode', v)} />} />
          <Row t={t} label={tr('finish')} hint={tr('finishHint')} control={<Seg t={t} value={tw.finish} options={['Solid', 'Glass']} render={optL} onChange={(v) => setTweak('finish', v)} />} />
          {tw.bg !== undefined && <Row t={t} label={tr('background')} hint={tr('backgroundHint')} stack control={<Seg t={t} value={tw.bg} options={['Dynamic', 'Static', 'Off']} render={optL} onChange={(v) => setTweak('bg', v)} />} />}
          <Row t={t} label={tr('accent')} stack control={<Swatches t={t} value={tw.accent} options={accents}
            customColors={tw.customAccents || []}
            onChange={(v) => setTweak('accent', v)}
            onAddCustom={(c) => { const list = [...(tw.customAccents || []).filter((x) => String(x).toLowerCase() !== String(c).toLowerCase()), c].slice(-10); setTweak({ customAccents: list, accent: c }); }}
            onRemoveCustom={(c) => { const list = (tw.customAccents || []).filter((x) => String(x).toLowerCase() !== String(c).toLowerCase()); const next = { customAccents: list }; if (String(tw.accent).toLowerCase() === String(c).toLowerCase()) next.accent = accents[0]; setTweak(next); }} />} />
          <Row t={t} label={tr('companion')} stack control={<CompanionPick t={t} value={tw.companion || 'brock'} onChange={(v) => setTweak('companion', v)} />} />
        </Section>

        <Section t={t} title={tr('layout')}>
          <Row t={t} label={tr('corners')} control={<Seg t={t} value={tw.corners} options={['Rounded', 'Sharp']} render={optL} onChange={(v) => setTweak('corners', v)} />} />
          <Row t={t} label={tr('density')} control={<Seg t={t} value={tw.density} options={['Cozy', 'Compact']} render={optL} onChange={(v) => setTweak('density', v)} />} />
          <Row t={t} label={tr('itemIcons')} hint={tr('itemIconsHint')} control={<Toggle t={t} value={tw.thumbs} onChange={(v) => setTweak('thumbs', v)} />} />
        </Section>

        <Section t={t} title={tr('region')}>
          <Row t={t} label={tr('language')} control={<Seg t={t} value={tw.lang || 'en'} options={langOpts} render={langName} onChange={(v) => setTweak('lang', v)} />} />
          <Row t={t} label={tr('units')} hint={tr('unitsHint')} control={<Seg t={t} value={tw.units} options={['Metric', 'Imperial']} render={optL} onChange={(v) => setTweak('units', v)} />} />
          <Row t={t} label={tr('showRecents')} hint={tr('showRecentsHint')} control={<Toggle t={t} value={tw.recents !== false} onChange={(v) => setTweak('recents', v)} />} />
        </Section>

        <Section t={t} title={tr('about')}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px' }}>
            <img src="icons/icon-192.png" alt="Lista app icon" width="56" height="56" style={{ flex: '0 0 auto', width: 56, height: 56, borderRadius: 14, boxShadow: t.shadow.card }} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: t.font.head, fontSize: 17, fontWeight: 700, color: t.color.text }}>Lista</div>
              <div style={{ fontSize: 13, color: t.color.textFaint, marginTop: 2 }}>{tr('aboutTagline')} · v1.0</div>
            </div>
          </div>
        </Section>

        <div style={{ textAlign: 'center', fontSize: 12, color: t.color.textFaint, padding: '4px 0 max(env(safe-area-inset-bottom, 0px), 8px)' }}>
          {tr('madeWith')} · Lista
        </div>
      </div>
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
})();
