/* === PHYSL 210 — Tweaks panel (accent, surface, corners, dark mode) === */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E7876D",
  "bg": "Cream",
  "radius": "Rounded",
  "dark": false
}/*EDITMODE-END*/;

const ACCENTS = {
  '#E7876D': { name:'Coral', hue:36, heart:'none', vars:{
    '--coral':'oklch(0.72 0.124 36)', '--coral-deep':'oklch(0.60 0.130 34)',
    '--coral-tint':'oklch(0.94 0.040 44)', '--coral-tint-2':'oklch(0.90 0.058 42)' } },
  '#6FA383': { name:'Sage', hue:158, heart:'hue-rotate(108deg) saturate(.8)', vars:{
    '--coral':'oklch(0.66 0.085 158)', '--coral-deep':'oklch(0.52 0.090 160)',
    '--coral-tint':'oklch(0.945 0.033 160)', '--coral-tint-2':'oklch(0.90 0.048 160)' } },
  '#6E93C8': { name:'Sky', hue:245, heart:'hue-rotate(178deg) saturate(.9)', vars:{
    '--coral':'oklch(0.66 0.105 245)', '--coral-deep':'oklch(0.54 0.115 248)',
    '--coral-tint':'oklch(0.945 0.035 240)', '--coral-tint-2':'oklch(0.90 0.050 240)' } },
  '#9A86D6': { name:'Lavender', hue:300, heart:'hue-rotate(252deg) saturate(.85)', vars:{
    '--coral':'oklch(0.66 0.115 300)', '--coral-deep':'oklch(0.54 0.125 302)',
    '--coral-tint':'oklch(0.945 0.040 302)', '--coral-tint-2':'oklch(0.90 0.055 302)' } },
};

const BGS = {
  Cream:  { '--bg':'oklch(0.986 0.008 72)', '--surface':'oklch(0.998 0.004 80)' },
  Cool:   { '--bg':'oklch(0.985 0.006 225)', '--surface':'oklch(0.997 0.003 225)' },
  Bright: { '--bg':'oklch(0.992 0.003 80)', '--surface':'oklch(1 0 0)' },
};

const RADII = {
  Soft:    { '--r-sm':'18px', '--r-md':'26px', '--r-lg':'34px', '--r-xl':'44px' },
  Rounded: { '--r-sm':'14px', '--r-md':'20px', '--r-lg':'28px', '--r-xl':'36px' },
  Sharp:   { '--r-sm':'8px',  '--r-md':'12px', '--r-lg':'16px', '--r-xl':'22px' },
};

const LIGHT_NEUTRALS = {
  '--ink':'oklch(0.34 0.028 48)', '--ink-soft':'oklch(0.50 0.022 48)', '--muted':'oklch(0.64 0.018 52)',
  '--line':'oklch(0.92 0.012 64)', '--line-soft':'oklch(0.95 0.010 66)',
};
const DARK_NEUTRALS = {
  '--bg':'oklch(0.205 0.012 60)', '--surface':'oklch(0.258 0.014 60)',
  '--ink':'oklch(0.95 0.008 75)', '--ink-soft':'oklch(0.80 0.010 75)', '--muted':'oklch(0.63 0.012 72)',
  '--line':'oklch(0.335 0.012 60)', '--line-soft':'oklch(0.29 0.012 60)',
};

const DARK_CSS = `
  .media-ph{background-color:var(--surface);background-image:repeating-linear-gradient(135deg, oklch(0.31 0.012 60) 0 14px, oklch(0.26 0.012 60) 14px 28px);}
  .opt.correct{background:oklch(0.33 0.05 165);border-color:oklch(0.55 0.09 165)}
  .opt.wrong{background:oklch(0.33 0.055 28);border-color:oklch(0.56 0.12 28)}
  .opt.correct .opt-key{background:oklch(0.62 0.10 165);border-color:oklch(0.62 0.10 165)}
  .opt.wrong .opt-key{background:oklch(0.60 0.14 28);border-color:oklch(0.60 0.14 28)}
`;

function applyTweaks(t) {
  const root = document.documentElement;
  const A = ACCENTS[t.accent] || ACCENTS['#E7876D'];
  const vars = { ...(RADII[t.radius] || RADII.Rounded), '--coral': A.vars['--coral'] };
  if (t.dark) {
    Object.assign(vars, DARK_NEUTRALS, {
      '--coral-deep': `oklch(0.82 0.11 ${A.hue})`,
      '--coral-tint': `oklch(0.305 0.035 ${A.hue})`,
      '--coral-tint-2': `oklch(0.365 0.045 ${A.hue})`,
    });
  } else {
    Object.assign(vars, LIGHT_NEUTRALS, BGS[t.bg] || BGS.Cream, {
      '--coral-deep': A.vars['--coral-deep'],
      '--coral-tint': A.vars['--coral-tint'],
      '--coral-tint-2': A.vars['--coral-tint-2'],
    });
  }
  Object.entries(vars).forEach(([k, v]) => root.style.setProperty(k, v));
  let s = document.getElementById('tweak-style');
  if (!s) { s = document.createElement('style'); s.id = 'tweak-style'; document.head.appendChild(s); }
  s.textContent = `.heart-mark{filter:${A.heart};}` + (t.dark ? DARK_CSS : '');
}

// end-user dark preference (the panel's postMessage persistence only lands in edit mode);
// falls back to the on-disk default when the key is absent
function darkPref() {
  try { const v = localStorage.getItem('physl.dark'); return v === null ? !!TWEAK_DEFAULTS.dark : v === '1'; }
  catch (e) { return !!TWEAK_DEFAULTS.dark; }
}

function Tweaks() {
  const [t, setTweak] = useTweaks({ ...TWEAK_DEFAULTS, dark: darkPref() });
  React.useEffect(() => { applyTweaks(t); }, [t]);
  // persist dark + notify the top-nav toggle so its icon stays in sync whatever flipped it
  React.useEffect(() => {
    try { localStorage.setItem('physl.dark', t.dark ? '1' : '0'); } catch (e) {}
    try { window.dispatchEvent(new CustomEvent('physl-dark-set', { detail: !!t.dark })); } catch (e) {}
  }, [t.dark]);
  // accept toggle requests from the nav button (single applier stays here, so accent/bg keep working)
  React.useEffect(() => {
    const onReq = (e) => setTweak('dark', !!(e && e.detail));
    window.addEventListener('physl-dark', onReq);
    return () => window.removeEventListener('physl-dark', onReq);
  }, [setTweak]);
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Accent" />
      <TweakColor label="Theme colour" value={t.accent}
        options={Object.keys(ACCENTS)} onChange={(v) => setTweak('accent', v)} />
      <TweakSection label="Surface" />
      <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
      {!t.dark && <TweakRadio label="Background" value={t.bg}
        options={Object.keys(BGS)} onChange={(v) => setTweak('bg', v)} />}
      <TweakRadio label="Corners" value={t.radius}
        options={Object.keys(RADII)} onChange={(v) => setTweak('radius', v)} />
    </TweaksPanel>
  );
}
window.Tweaks = Tweaks;

// Apply the saved accent/surface/dark preference at load — so the login gate (which renders
// before <Tweaks/> mounts) is themed correctly, especially in dark mode. Idempotent: the
// Tweaks component re-applies the same values when it later mounts inside the app.
try { applyTweaks({ ...TWEAK_DEFAULTS, dark: darkPref() }); } catch (e) {}
