// Tweaks app for Dun Cairn Co. — mounts the floating tweaks panel and
// applies palette/density/display-font choices via data-attributes on
// document.documentElement (CSS variables do the rest).

const DUNCAIRN_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "ink",
  "density": "regular",
  "display": "cormorant"
}/*EDITMODE-END*/;

// Palette swatch triples used in the curated TweakColor control. The first
// color is the page bg, the second is the ink, the third is the accent.
const DUNCAIRN_PALETTES = {
  bone:  ["#f1ece2", "#1a2840", "#4a6a55"],
  mist:  ["#eef0ef", "#16243a", "#4a6a55"],
  stone: ["#e6dfce", "#1a2840", "#4a6a55"],
  ink:   ["#14181f", "#ece7dc", "#b8c9b6"],
};

function DuncairnTweaks() {
  const [t, setTweak] = useTweaks(DUNCAIRN_TWEAK_DEFAULTS);

  // Apply tweaks to <html> data-* attributes so the CSS picks them up.
  React.useEffect(() => {
    const root = document.documentElement;
    root.setAttribute("data-palette", t.palette);
    root.setAttribute("data-density", t.density);
    root.setAttribute("data-display", t.display);
  }, [t.palette, t.density, t.display]);

  // Reverse-map a palette triple (the TweakColor value) back to its key.
  const paletteValue = DUNCAIRN_PALETTES[t.palette] || DUNCAIRN_PALETTES.bone;
  const onPaletteChange = (triple) => {
    const key = Object.keys(DUNCAIRN_PALETTES).find(
      (k) => JSON.stringify(DUNCAIRN_PALETTES[k]) === JSON.stringify(triple),
    );
    if (key) setTweak("palette", key);
  };

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Palette">
        <TweakColor
          label="Theme"
          value={paletteValue}
          options={Object.values(DUNCAIRN_PALETTES)}
          onChange={onPaletteChange}
        />
      </TweakSection>

      <TweakSection label="Layout">
        <TweakRadio
          label="Density"
          value={t.density}
          options={["compact", "regular", "comfy"]}
          onChange={(v) => setTweak("density", v)}
        />
      </TweakSection>

      <TweakSection label="Typography">
        <TweakSelect
          label="Display face"
          value={t.display}
          options={[
            { value: "cormorant",  label: "Cormorant Garamond" },
            { value: "newsreader", label: "Newsreader" },
            { value: "ebgaramond", label: "EB Garamond" },
          ]}
          onChange={(v) => setTweak("display", v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// Apply persisted defaults synchronously on first paint, before the
// React tree mounts (avoids a flicker from default to persisted values).
(function () {
  const root = document.documentElement;
  root.setAttribute("data-palette", DUNCAIRN_TWEAK_DEFAULTS.palette);
  root.setAttribute("data-density", DUNCAIRN_TWEAK_DEFAULTS.density);
  root.setAttribute("data-display", DUNCAIRN_TWEAK_DEFAULTS.display);
})();

ReactDOM.createRoot(document.getElementById("tweaks-root"))
  .render(<DuncairnTweaks />);
