/* Jovana Universe — Tweaks wiring (mounts the panel, drives the WebGL scene) */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "spectrum": ["#5b8cff", "#9fc4ff"],
  "motion": 1,
  "density": "standard",
  "grain": true
}/*EDITMODE-END*/;

function hexA(hex, a) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
}

function applyEffects(t) {
  const root = document.documentElement.style;
  root.setProperty('--accent', t.spectrum[0]);
  root.setProperty('--accent-soft', hexA(t.spectrum[0], 0.16));
  if (window.JUScene) {
    window.JUScene.setColors('#f4f6ff', t.spectrum[1]);
    window.JUScene.setMotion(t.motion);
  }
  const grain = document.querySelector('.grain');
  if (grain) grain.style.display = t.grain ? '' : 'none';
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const firstDens = React.useRef(true);

  React.useEffect(() => { applyEffects(t); }, [t]);

  React.useEffect(() => {
    if (firstDens.current) { firstDens.current = false; return; }
    if (window.JUScene && window.JUScene.rebuild) {
      const map = { sparse: 0.6, standard: 1, dense: 1.5 };
      window.JUScene.rebuild(map[t.density] || 1);
    }
  }, [t.density]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Spectrum" />
      <TweakColor
        label="Field"
        value={t.spectrum}
        options={[
          ['#5b8cff', '#9fc4ff'],
          ['#9a6cff', '#c6abff'],
          ['#3fd9c8', '#a9f0e6'],
          ['#c9d2e6', '#ffffff'],
          ['#ff7a59', '#ffc4ad']
        ]}
        onChange={(v) => setTweak('spectrum', v)}
      />
      <TweakSection label="Motion" />
      <TweakSlider label="Intensity" value={t.motion} min={0} max={1.6} step={0.05}
        onChange={(v) => setTweak('motion', v)} />
      <TweakRadio label="Density" value={t.density}
        options={['sparse', 'standard', 'dense']}
        onChange={(v) => setTweak('density', v)} />
      <TweakSection label="Atmosphere" />
      <TweakToggle label="Film grain" value={t.grain}
        onChange={(v) => setTweak('grain', v)} />
    </TweaksPanel>
  );
}

(function mount() {
  const node = document.getElementById('tweaks-root');
  if (!node || !window.ReactDOM) return;
  ReactDOM.createRoot(node).render(<App />);
})();
