/* Groundwork — Tweaks island.
   Applies serif / accent / motion / dark-preview to :root.
   The site itself is plain HTML; this only drives CSS variables. */

const GW_DEFAULTS = /*EDITMODE-BEGIN*/{
  "serif": "Source Serif 4",
  "accent": "#E0A92E",
  "motion": "subtle",
  "theme": "auto",
  "grain": true
}/*EDITMODE-END*/;

const SERIFS = {
  "Source Serif 4": '"Source Serif 4", Georgia, serif',
  "Newsreader":     '"Newsreader", Georgia, serif',
  "Lora":           '"Lora", Georgia, serif',
  "Spectral":       '"Spectral", Georgia, serif'
};

const MOTION_SCALE = { off: 0, subtle: 1, lively: 1.6 };

function applyTweaks(t) {
  const root = document.documentElement;
  root.style.setProperty("--serif", SERIFS[t.serif] || SERIFS["Source Serif 4"]);
  root.style.setProperty("--ochre", t.accent);
  root.style.setProperty("--motion", String(MOTION_SCALE[t.motion] ?? 1));
  root.style.setProperty("--paper-grain", t.grain ? "0.06" : "0");
  // theme preview: auto = let media query decide; otherwise force
  if (t.theme === "auto") root.removeAttribute("data-theme");
  else root.setAttribute("data-theme", t.theme);
  // tone down on-ochre text if a darker accent is picked
  document.body.classList.toggle("motion-off", t.motion === "off");
}

function GroundworkTweaks() {
  const [t, setTweak] = useTweaks(GW_DEFAULTS);
  React.useEffect(() => { applyTweaks(t); }, [t]);

  return (
    <TweaksPanel>
      <TweakSection label="Headline serif" />
      <TweakSelect
        label="Typeface"
        value={t.serif}
        options={Object.keys(SERIFS)}
        onChange={(v) => setTweak("serif", v)}
      />

      <TweakSection label="Accent — ochre only" />
      <TweakColor
        label="Ochre"
        value={t.accent}
        options={["#E0A92E", "#CF8F1E", "#C77A12", "#EBC04A"]}
        onChange={(v) => setTweak("accent", v)}
      />

      <TweakSection label="Motion" />
      <TweakRadio
        label="Amount"
        value={t.motion}
        options={["off", "subtle", "lively"]}
        onChange={(v) => setTweak("motion", v)}
      />

      <TweakSection label="Review" />
      <TweakRadio
        label="Theme"
        value={t.theme}
        options={["auto", "light", "dark"]}
        onChange={(v) => setTweak("theme", v)}
      />
      <TweakToggle
        label="Paper grain"
        value={t.grain}
        onChange={(v) => setTweak("grain", v)}
      />
    </TweaksPanel>
  );
}

// apply persisted/default values immediately on load (before React mounts)
(function () {
  try {
    const saved = JSON.parse(localStorage.getItem("__tweaks") || "null");
    applyTweaks(Object.assign({}, GW_DEFAULTS, saved || {}));
  } catch (e) { applyTweaks(GW_DEFAULTS); }
})();

const gwTweakMount = document.getElementById("tweaks-root");
if (gwTweakMount) ReactDOM.createRoot(gwTweakMount).render(<GroundworkTweaks />);
