// preferences.jsx — JiffyScore Preferences slide-over.
// Full-app theming: appearance (light/dark), brand palette, density,
// type scale, motion. Mirrors the JiffyEstate Preferences panel.
(function () {
  const PALETTES = [
    { key: 'default', name: 'Estate · default', meta: 'Emerald · gold · lime', dots: ['#0E2418', '#E8B53C', '#B6F26E'] },
    { key: 'ocean', name: 'Ocean', meta: 'Deep blue · silver · azure', dots: ['#0E2A50', '#B9C5D8', '#5BA0F5'] },
    { key: 'sand', name: 'Sand', meta: 'Clay · terracotta · champagne', dots: ['#3C2D22', '#E8B58C', '#F2D885'] },
    { key: 'forest', name: 'Forest', meta: 'Pine · copper · moss', dots: ['#1B2E1F', '#D88B4F', '#A4D67B'] },
  ];

  function Seg({ value, options, onChange }) {
    return (
      <div className="pref-seg">
        {options.map(o => (
          <button key={o.value} className={(value === o.value ? 'is-on' : '') + (o.tone ? ' tone-' + o.tone : '')} onClick={() => onChange(o.value)}>
            {o.icon && <Icon name={o.icon} size={16} />}{o.label}
          </button>
        ))}
      </div>
    );
  }

  function Preferences({ open, onClose, prefs, setPref, onReset }) {
    // Open without freezing the slide-in transition on the first open after a
    // (re)mount: when `open` flips true, force a synchronous reflow on the
    // panel (read offsetWidth) so its closed transform is committed as the
    // transition start value, THEN add `is-open`. A forced reflow is reliable
    // even when rAF is throttled (e.g. a backgrounded iframe).
    const { useState, useLayoutEffect, useRef } = React;
    const [active, setActive] = useState(false);
    const panelRef = useRef(null);
    useLayoutEffect(() => {
      const node = panelRef.current;
      if (open) {
        if (node) {
          // A backgrounded tab pauses CSS transitions, which would hold the
          // panel at its off-screen start. Snap (no transition) when hidden so
          // it's correctly placed the moment the tab is shown; restore the
          // animated transition once visible again for future opens.
          if (document.hidden) {
            node.style.transition = 'none';
            const restore = () => { node.style.transition = ''; document.removeEventListener('visibilitychange', restore); };
            document.addEventListener('visibilitychange', restore);
          }
          void node.offsetWidth; // commit closed transform as the transition start
        }
        setActive(true);
      } else {
        setActive(false);
      }
    }, [open]);

    return (
      <>
        <div className={'pref-backdrop' + (active ? ' is-open' : '')} onClick={onClose} />
        <aside ref={panelRef} className={'pref-panel' + (active ? ' is-open' : '')} role="dialog" aria-label="Preferences" aria-hidden={!open}>
          <div className="pref-head">
            <p className="eyebrow">Make JiffyScore yours</p>
            <h2>Preferences</h2>
            <button className="pref-close" onClick={onClose} aria-label="Close"><Icon name="x" size={18} /></button>
          </div>

          <div className="pref-body">
            <div className="pref-sect">
              <div className="pref-label">Your name</div>
              <p className="pref-desc">Used across greetings, reports, and audit logs.</p>
              <input className="input" value={prefs.name} onChange={e => setPref('name', e.target.value)} placeholder="Your name" />
            </div>

            <div className="pref-sect">
              <div className="pref-label">Appearance</div>
              <p className="pref-desc">Light for daylight reviews, dark for focus. Applies to every page.</p>
              <Seg value={prefs.mode} onChange={v => setPref('mode', v)}
                options={[{ value: 'light', label: 'Light', icon: 'sun' }, { value: 'dark', label: 'Dark', icon: 'moon' }]} />
            </div>

            <div className="pref-sect">
              <div className="pref-label">Why-this-score view</div>
              <p className="pref-desc">How the glass-box drawer opens when you tap a score. Forensic is dense and analytical; editorial is a calm, narrative takeover.</p>
              <Seg value={prefs.scoreLab} onChange={v => setPref('scoreLab', v)}
                options={[{ value: 'forensic', label: 'Forensic', icon: 'flask' }, { value: 'editorial', label: 'Editorial', icon: 'quote' }]} />
            </div>

            <div className="pref-sect">
              <div className="pref-label">Brand theme</div>
              <p className="pref-desc">Same UI, different palette. Saved to your device.</p>
              <div className="pref-palettes">
                {PALETTES.map(p => (
                  <button key={p.key} className={'pref-palette' + (prefs.brand === p.key ? ' is-on' : '')} onClick={() => setPref('brand', p.key)}>
                    <div className="pp-dots">{p.dots.map((d, i) => <span key={i} style={{ background: d }} />)}</div>
                    <div className="pp-name">{p.name}</div>
                    <div className="pp-meta">{p.meta}</div>
                    <span className="pp-check"><Icon name="check" size={18} sw={2.6} /></span>
                  </button>
                ))}
              </div>
            </div>

            <div className="pref-sect">
              <div className="pref-label">Density</div>
              <p className="pref-desc">How much breathing room between elements.</p>
              <Seg value={prefs.density} onChange={v => setPref('density', v)}
                options={[{ value: 'compact', label: 'Compact' }, { value: 'cozy', label: 'Cozy' }, { value: 'spacious', label: 'Spacious' }]} />
            </div>

            <div className="pref-sect">
              <div className="pref-label">Type scale</div>
              <p className="pref-desc">Smaller for dense data; larger for accessibility.</p>
              <Seg value={prefs.typeScale} onChange={v => setPref('typeScale', v)}
                options={[{ value: 'small', label: 'Small' }, { value: 'regular', label: 'Regular' }, { value: 'large', label: 'Large' }]} />
            </div>

            <div className="pref-sect">
              <div className="pref-label">Motion</div>
              <p className="pref-desc">Full animation, subtle transitions only, or none.</p>
              <Seg value={prefs.motion} onChange={v => setPref('motion', v)}
                options={[{ value: 'full', label: 'Full' }, { value: 'subtle', label: 'Subtle' }, { value: 'off', label: 'Off' }]} />
            </div>
          </div>

          <div className="pref-foot">
            <button className="btn btn--ghost" onClick={onReset}>Reset all</button>
            <button className="btn" onClick={onClose}>Done</button>
          </div>
        </aside>
      </>
    );
  }
  window.Preferences = Preferences;
})();
