/* global React, ReactDOM, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakToggle, useTweaks */

const JUSSTIPS_TWEAK_DEFAULTS = window.__TWEAKS__ || {
  palette: "cream",
  displayFont: "instrument",
  showRibbon: true,
};

// Read palette/display from localStorage (cross-page persistence) overriding defaults
function readJusstipsState() {
  const stored = {};
  try {
    const raw = localStorage.getItem("jusstips:tweaks");
    if (raw) Object.assign(stored, JSON.parse(raw));
  } catch (_) {}
  return { ...JUSSTIPS_TWEAK_DEFAULTS, ...stored };
}

function applyJusstipsTweaks(t) {
  document.body.dataset.palette = t.palette;
  document.body.dataset.display = t.displayFont;
  const ribbon = document.getElementById("ribbon");
  if (ribbon) ribbon.style.display = t.showRibbon ? "" : "none";
}

// Apply IMMEDIATELY (before React mounts) so reload restores cleanly
applyJusstipsTweaks(readJusstipsState());

function JusstipsTweaks() {
  const initial = readJusstipsState();
  const [t, setTweak] = useTweaks(initial);
  React.useEffect(() => {
    applyJusstipsTweaks(t);
    try { localStorage.setItem("jusstips:tweaks", JSON.stringify(t)); } catch (_) {}
  }, [t]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Palette">
        <TweakColor
          label="Color theme"
          value={t.palette}
          onChange={(v) => setTweak("palette", v)}
          options={[
            { value: "cream",  palette: ["#F2ECE0","#2F4A35","#B85A35","#1B1F1B"] },
            { value: "paper",  palette: ["#F6F4EE","#173B66","#C75A2A","#14171A"] },
            { value: "forest", palette: ["#1F2A22","#D9C28A","#D98553","#EFE8D8"] },
            { value: "rose",   palette: ["#F5E9DF","#6B2A2A","#C75A2A","#2B1A18"] },
          ]}
        />
      </TweakSection>
      <TweakSection title="Typografi">
        <TweakRadio
          label="Display"
          value={t.displayFont}
          onChange={(v) => setTweak("displayFont", v)}
          options={[
            { value: "instrument", label: "Serif" },
            { value: "geist",      label: "Sans" },
          ]}
        />
      </TweakSection>
      <TweakSection title="Elementer">
        <TweakToggle
          label="Topp-stripe"
          value={t.showRibbon}
          onChange={(v) => setTweak("showRibbon", v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

const tweakRoot = document.createElement("div");
document.body.appendChild(tweakRoot);
ReactDOM.createRoot(tweakRoot).render(<JusstipsTweaks />);
