/* ════════════════════════════════════════════════════════════
   AJAIA — Tweaks bridge
   Visual-only controls (content stays identical). Drives CSS vars
   on :root and window.AJAIA.{globe,stage} so the WebGL globe and
   the transformation stage react live.
   ════════════════════════════════════════════════════════════ */
const { useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#6fb0f8",
  "glow": 1,
  "spin": 1,
  "arcs": true,
  "demo": true
}/*EDITMODE-END*/;

// map a hex accent to an HSL hue
function hexToHue(hex) {
  const m = hex.replace('#', '');
  const r = parseInt(m.substring(0, 2), 16) / 255;
  const g = parseInt(m.substring(2, 4), 16) / 255;
  const b = parseInt(m.substring(4, 6), 16) / 255;
  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  let h = 0; const d = max - min;
  if (d !== 0) {
    if (max === r) h = ((g - b) / d) % 6;
    else if (max === g) h = (b - r) / d + 2;
    else h = (r - g) / d + 4;
    h *= 60; if (h < 0) h += 360;
  }
  return Math.round(h);
}

function AjaiaTweaks() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    const root = document.documentElement;
    const hue = hexToHue(t.accent);
    root.style.setProperty('--accent-h', hue);
    root.style.setProperty('--glow', t.glow);
    const A = window.AJAIA || {};
    if (A.globe) {
      A.globe.hue = hue; A.globe.glow = t.glow; A.globe.speed = t.spin;
      A.globe.arcs = t.arcs ? 1 : 0;
      if (A.globe._apply) A.globe._apply();
    }
    if (A.stage) { A.stage.hue = hue; A.stage.glow = t.glow; A.stage.demo = t.demo; }
  }, [t.accent, t.glow, t.spin, t.arcs, t.demo]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Accent" />
      <TweakColor label="Light color" value={t.accent}
        options={['#6fb0f8', '#97c2f8', '#3f7be0', '#39c7e8', '#7c8cff']}
        onChange={(v) => setTweak('accent', v)} />
      <TweakSlider label="Glow intensity" value={t.glow} min={0.2} max={1.8} step={0.1}
        onChange={(v) => setTweak('glow', v)} />

      <TweakSection label="Globe" />
      <TweakSlider label="Rotation speed" value={t.spin} min={0} max={2.4} step={0.1}
        onChange={(v) => setTweak('spin', v)} />
      <TweakToggle label="Network arcs" value={t.arcs}
        onChange={(v) => setTweak('arcs', v)} />

      <TweakSection label="Transformation" />
      <TweakToggle label="Auto demo cursor" value={t.demo}
        onChange={(v) => setTweak('demo', v)} />
    </TweaksPanel>
  );
}

ReactDOM.createRoot(document.getElementById('tweaks-root')).render(<AjaiaTweaks />);
