/* Tweaks panel — bridges user controls into the Three.js scene.
   Stores layout capitalized for nice labels; lowercases on the way out. */
const ROOCHE_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "layout": "Floating Wall",
  "accent": "#EB1C30",
  "motionSpeed": 1,
  "background": "Glow"
}/*EDITMODE-END*/;

const LAYOUT_MAP = { "Floating Wall": "wall", "Orbit": "orbit" };
const LAYOUT_INV = { wall: "Floating Wall", orbit: "Orbit" };

function pushTweaks(t, skipLayout) {
  const payload = {
    accent: t.accent,
    motionSpeed: t.motionSpeed,
    background: (t.background || "Glow").toLowerCase(),
  };
  if (!skipLayout) payload.layout = LAYOUT_MAP[t.layout] || "wall";
  if (window.RoocheApp) window.RoocheApp.applyTweaks(payload);
  else window.__pendingTweaks = payload;
}

function RoocheTweaks() {
  const [t, setTweak] = useTweaks(ROOCHE_TWEAK_DEFAULTS);
  const first = React.useRef(true);

  // push every change into the scene (skip layout on first mount so the
  // panel never fights the scene's own default at boot)
  React.useEffect(() => {
    pushTweaks(t, first.current);
    first.current = false;
  }, [t]);

  // keep panel in sync when the in-scene dock changes layout
  React.useEffect(() => {
    const onLayout = (e) => {
      const cap = LAYOUT_INV[e.detail];
      if (cap && cap !== t.layout) setTweak("layout", cap);
    };
    window.addEventListener("rooche-layout", onLayout);
    return () => window.removeEventListener("rooche-layout", onLayout);
  }, [t.layout]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Arrangement" />
      <TweakRadio
        label="3D layout"
        value={t.layout}
        options={["Floating Wall", "Orbit"]}
        onChange={(v) => setTweak("layout", v)}
      />
      <TweakSection label="Atmosphere" />
      <TweakColor
        label="Accent"
        value={t.accent}
        options={["#EB1C30", "#2A6FDB", "#1F8A5B", "#C9A36B"]}
        onChange={(v) => setTweak("accent", v)}
      />
      <TweakRadio
        label="Background"
        value={t.background}
        options={["Glow", "Grid", "Solid"]}
        onChange={(v) => setTweak("background", v)}
      />
      <TweakSlider
        label="Ambient motion"
        value={t.motionSpeed}
        min={0} max={2} step={0.1}
        onChange={(v) => setTweak("motionSpeed", v)}
      />
    </TweaksPanel>
  );
}

(function mount() {
  const el = document.createElement("div");
  el.id = "tweaks-root";
  document.body.appendChild(el);
  ReactDOM.createRoot(el).render(<RoocheTweaks />);
})();
