// tweaks-app.jsx — wires Tweaks panel to root CSS vars + data attrs.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "a",
  "accent": "#A855F7",
  "dark": true
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  '#A855F7', // purple (default)
  '#E36B2B', // warm orange
  '#2A5BD7', // cobalt
  '#1E8A5B', // forest
];

function applyTweaks(t) {
  const root = document.documentElement;
  root.style.setProperty('--accent', t.accent);
  // pick ink color for accent — light if accent is dark, dark if accent is light
  const ink = isLight(t.accent) ? '#1a1a1a' : '#ffffff';
  root.style.setProperty('--accent-ink', ink);
  document.body.dataset.theme = t.dark ? 'dark' : 'light';
  document.body.dataset.direction = t.direction;

  // update the inline svg checkmark color in tier li bullets
  const svg = `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'><path d='M2.5 6.2 5 8.5 9.5 4' fill='none' stroke='${encodeURIComponent(t.accent)}' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/></svg>")`;
  // (We rely on color-mix tinting; bullet svg can stay as the warm default.)
}

function isLight(hex) {
  const h = hex.replace('#', '');
  const x = h.length === 3 ? h.replace(/./g, (c) => c + c) : h;
  const r = parseInt(x.slice(0, 2), 16);
  const g = parseInt(x.slice(2, 4), 16);
  const b = parseInt(x.slice(4, 6), 16);
  return r * 299 + g * 587 + b * 114 > 148000;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  React.useEffect(() => { applyTweaks(t); }, [t]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Layout" />
      <TweakRadio
        label="Direction"
        value={t.direction}
        options={[
          { value: 'a', label: 'Refined' },
          { value: 'b', label: 'Editorial' },
        ]}
        onChange={(v) => setTweak('direction', v)}
      />
      <TweakSection label="Theme" />
      <TweakToggle
        label="Dark mode"
        value={t.dark}
        onChange={(v) => setTweak('dark', v)}
      />
      <TweakColor
        label="Accent"
        value={t.accent}
        options={ACCENT_OPTIONS}
        onChange={(v) => setTweak('accent', v)}
      />
    </TweaksPanel>
  );
}

// Apply defaults immediately so the page doesn't flash with wrong theme.
applyTweaks(TWEAK_DEFAULTS);

const root = ReactDOM.createRoot(document.getElementById('tweaks-root'));
root.render(<App />);
