// Tweaks app — adds an in-page panel for grain/effects/mode controls.
// Loaded on every page after React + the tweaks-panel starter.

const RE_DEFAULTS = /*EDITMODE-BEGIN*/{
  "grain": 0.18,
  "effects": true,
  "mode": "dark"
}/*EDITMODE-END*/;

function applyAll(t) {
  const root = document.documentElement;
  if (t.grain != null) root.style.setProperty('--grain-opacity', t.grain);
  root.dataset.effects = t.effects ? 'on' : 'off';
  root.dataset.mode = t.mode || 'dark';
  try { localStorage.setItem('re_tweaks', JSON.stringify(t)); } catch(e) {}
}

// Apply persisted tweaks immediately so the page doesn't flash defaults
try {
  const saved = JSON.parse(localStorage.getItem('re_tweaks') || 'null');
  if (saved) applyAll({ ...RE_DEFAULTS, ...saved });
  else applyAll(RE_DEFAULTS);
} catch(e) { applyAll(RE_DEFAULTS); }

function ReTweaks() {
  const [tweaks, setTweak] = useTweaks(RE_DEFAULTS);

  React.useEffect(() => { applyAll(tweaks); }, [tweaks]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Atmosphere">
        <TweakSlider
          label="Brush / grain density"
          value={tweaks.grain}
          min={0} max={0.45} step={0.01}
          onChange={(v) => setTweak('grain', v)}
        />
        <TweakToggle
          label="Scroll & ambient effects"
          value={tweaks.effects}
          onChange={(v) => setTweak('effects', v)}
        />
      </TweakSection>
      <TweakSection title="Mode">
        <TweakRadio
          label="Tone"
          value={tweaks.mode}
          options={[
            { value: 'dark', label: 'Dark' },
            { value: 'dim', label: 'Dim' },
          ]}
          onChange={(v) => setTweak('mode', v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

const reTweaksRoot = document.createElement('div');
reTweaksRoot.id = 're-tweaks-root';
document.body.appendChild(reTweaksRoot);
ReactDOM.createRoot(reTweaksRoot).render(<ReTweaks />);
