// tweaks.jsx — Oleus tweaks panel.
// Loaded after React + tweaks-panel.jsx. Persists accent / font pair / theme
// / hero motif. Reads/writes the same theme storage key as shared.js so the
// theme toggle in the header and the tweaks panel stay in sync.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "amber",
  "fontPair": "geist",
  "theme": "dark",
  "heroMotif": "dashboard"
}/*EDITMODE-END*/;

// Accent presets — each is an oklch quad we apply to CSS vars.
const ACCENTS = {
  amber:    { swatch: '#e8a35c', l: 0.74, c: 0.17, h: 60,  hover_l: 0.78, soft: 0.12, line: 0.32 },
  phosphor: { swatch: '#7adb7e', l: 0.78, c: 0.18, h: 145, hover_l: 0.82, soft: 0.14, line: 0.34 },
  cyan:     { swatch: '#7cd3e0', l: 0.80, c: 0.12, h: 220, hover_l: 0.84, soft: 0.14, line: 0.34 },
  magenta:  { swatch: '#e57aaa', l: 0.74, c: 0.18, h: 350, hover_l: 0.78, soft: 0.12, line: 0.32 },
};

function applyAccent(name) {
  const a = ACCENTS[name] || ACCENTS.amber;
  const r = document.documentElement;
  r.style.setProperty('--accent',       `oklch(${a.l} ${a.c} ${a.h})`);
  r.style.setProperty('--accent-hover', `oklch(${a.hover_l} ${a.c} ${a.h})`);
  r.style.setProperty('--accent-fg',    a.l > 0.7 ? 'oklch(0.18 0.012 60)' : 'oklch(0.96 0.008 80)');
  r.style.setProperty('--accent-soft',  `oklch(${a.l} ${a.c} ${a.h} / ${a.soft})`);
  r.style.setProperty('--accent-line',  `oklch(${a.l} ${a.c} ${a.h} / ${a.line})`);
}

function applyFontPair(name) {
  document.documentElement.setAttribute('data-mono-pair', name);
}

function applyHeroMotif(name) {
  const targets = document.querySelectorAll('[data-hero-host]');
  targets.forEach((host) => {
    host.setAttribute('data-hero-motif', name);
    // Re-render the hero visual based on motif
    if (window.Oleus && window.Oleus.renderHero) {
      window.Oleus.renderHero(host, name);
    }
  });
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks on mount and on change.
  React.useEffect(() => { applyAccent(t.accent); }, [t.accent]);
  React.useEffect(() => { applyFontPair(t.fontPair); }, [t.fontPair]);
  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', t.theme);
    try { localStorage.setItem('oleus.theme', t.theme); } catch (e) {}
  }, [t.theme]);
  React.useEffect(() => { applyHeroMotif(t.heroMotif); }, [t.heroMotif]);

  // Header theme toggle dispatches 'themechange' — sync back into tweak state
  // so the panel reflects user toggles from the header.
  React.useEffect(() => {
    const onChange = (e) => {
      const next = e.detail || (typeof localStorage !== 'undefined' ? localStorage.getItem('oleus.theme') : null);
      if (next && next !== t.theme) setTweak('theme', next);
    };
    document.addEventListener('themechange', onChange);
    return () => document.removeEventListener('themechange', onChange);
  }, [t.theme, setTweak]);

  return (
    <TweaksPanel title="Oleus tweaks">
      <TweakSection label="Theme" />
      <TweakRadio label="Mode" value={t.theme}
        options={[{ value: 'dark', label: 'Dark' }, { value: 'light', label: 'Light' }]}
        onChange={(v) => setTweak('theme', v)} />
      <TweakColor label="Accent" value={t.accent}
        options={Object.keys(ACCENTS)}
        onChange={(v) => setTweak('accent', v)} />

      <TweakSection label="Type" />
      <TweakRadio label="Pairing" value={t.fontPair}
        options={[
          { value: 'geist', label: 'Geist' },
          { value: 'space', label: 'Space' },
          { value: 'instrument', label: 'Editorial' },
        ]}
        onChange={(v) => setTweak('fontPair', v)} />

      <TweakSection label="Hero" />
      <TweakRadio label="Motif" value={t.heroMotif}
        options={[
          { value: 'dashboard', label: 'Dashboard' },
          { value: 'terminal', label: 'Terminal' },
          { value: 'arch', label: 'Architecture' },
        ]}
        onChange={(v) => setTweak('heroMotif', v)} />
    </TweaksPanel>
  );
}

// TweakColor with string options: render a custom version since the starter
// expects hex codes. Override here with a small custom strip when options
// is a list of preset names.
const _OrigTweakColor = TweakColor;
function TweakColorPresets(props) {
  const { label, value, options, onChange } = props;
  if (!options || !options.length || typeof options[0] !== 'string' || !ACCENTS[options[0]]) {
    return <_OrigTweakColor {...props} />;
  }
  return (
    <TweakRow label={label}>
      <div className="twk-chips" role="radiogroup">
        {options.map((name) => {
          const on = value === name;
          const sw = ACCENTS[name].swatch;
          return (
            <button key={name} type="button" className="twk-chip" role="radio"
                    aria-checked={on} data-on={on ? '1' : '0'}
                    title={name}
                    style={{ background: sw }}
                    onClick={() => onChange(name)}>
              {on && (
                <svg viewBox="0 0 14 14" aria-hidden="true">
                  <path d="M3 7.2 5.8 10 11 4.2" fill="none" strokeWidth="2.2"
                        strokeLinecap="round" strokeLinejoin="round"
                        stroke="rgba(0,0,0,.78)" />
                </svg>
              )}
            </button>
          );
        })}
      </div>
    </TweakRow>
  );
}
window.TweakColor = TweakColorPresets;

const root = document.createElement('div');
root.id = 'oleus-tweaks-root';
document.body.appendChild(root);
ReactDOM.createRoot(root).render(<App />);
