/* Tweaks panel for the Gustavo Ferreira site.
   Loads after tweaks-panel.jsx (which exports TweaksPanel + useTweaks + control primitives to window). */
(function(){
  const { useEffect } = React;
  const { TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakSelect } = window;

  function GFTweaks(){
    // Initialise from whatever the page's inline DEFAULTS script already applied
    // BEFORE React mounted — this preserves each page's own direction lock and
    // density instead of clobbering them with a single global default.
    const rootEl = document.documentElement;
    const initDir = rootEl.getAttribute("data-dir") || "sereno";
    const initDensityVal = parseFloat(
      getComputedStyle(rootEl).getPropertyValue("--density")
    ) || 1;
    const initDensidade = initDensityVal < 0.95 ? "compacto" : "arejado";

    const [t, setTweak] = useTweaks({
      direcao: initDir,
      densidade: initDensidade,
    });
    const firstDensity = React.useRef(true);

    // Apply visual direction via root attribute
    useEffect(() => {
      document.documentElement.setAttribute("data-dir", t.direcao);
    }, [t.direcao]);

    // Skip the first run so the page keeps its own bespoke density on load;
    // only react to explicit user toggles afterwards.
    useEffect(() => {
      if (firstDensity.current) { firstDensity.current = false; return; }
      document.documentElement.style.setProperty(
        "--density",
        t.densidade === "compacto" ? "0.85" : "1"
      );
    }, [t.densidade]);

    return (
      <TweaksPanel title="Tweaks">
        <TweakSection label="Direção visual">
          <TweakSelect
            label="Estilo"
            value={t.direcao}
            onChange={(v) => setTweak("direcao", v)}
            options={[
              { value: "sereno",    label: "Sereno — off-white + serifa" },
              { value: "mono",      label: "Mono — carvão + sans técnica" },
              { value: "editorial", label: "Editorial — areia + serifa" },
            ]}
          />
          <TweakRadio
            label="Densidade"
            value={t.densidade}
            onChange={(v) => setTweak("densidade", v)}
            options={[
              { value: "arejado",  label: "Arejado" },
              { value: "compacto", label: "Compacto" },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    );
  }

  const root = ReactDOM.createRoot(document.getElementById("tweaks-root"));
  root.render(<GFTweaks />);
})();
