/* ========================================================================
   LUMINA — Strobo floating control panel (self-mounted)
   Always-on-top compact UI for toggling strobe modes.
   ======================================================================== */
(function () {
  const { useState, useEffect, useRef } = React;

  function StroboPanel() {
    const [open, setOpen] = useState(false);
    const [, tick] = useState(0);
    const [pos, setPos] = useState({ x: window.innerWidth - 340, y: 80 });

    // Force re-render at 10Hz so values stay in sync
    useEffect(() => {
      const id = setInterval(() => tick(n => n + 1), 100);
      return () => clearInterval(id);
    }, []);

    const S = window.Strobo;
    if (!S) return null;

    const startDrag = (e) => {
      if (e.target.tagName === "BUTTON" || e.target.tagName === "INPUT" || e.target.tagName === "SELECT") return;
      const start = { x: e.clientX, y: e.clientY };
      const sp = { ...pos };
      const onMove = (m) => setPos({ x: sp.x + (m.clientX - start.x), y: sp.y + (m.clientY - start.y) });
      const onUp = () => {
        window.removeEventListener("mousemove", onMove);
        window.removeEventListener("mouseup", onUp);
      };
      window.addEventListener("mousemove", onMove);
      window.addEventListener("mouseup", onUp);
    };

    const styles = {
      btn: {
        padding: "5px 9px", border: "none", borderRadius: 5,
        background: "linear-gradient(180deg, #2a2a30, #1a1a1e)",
        color: "var(--ink-dim)", fontFamily: "var(--font-mono)", fontSize: 9,
        cursor: "pointer", letterSpacing: "0.1em", textTransform: "uppercase",
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.06)",
      },
      btnActive: {
        background: "radial-gradient(circle at 50% 0%, #ffe39a 0%, #ffb02a 50%, #c87016 100%)",
        color: "#1a0a02", textShadow: "0 1px 0 rgba(255,255,255,0.3)",
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.4), 0 0 8px rgba(255,122,26,0.6)",
      },
      sel: {
        padding: "4px 6px", borderRadius: 4, border: "none",
        background: "#0a0a0c", color: "var(--accent)",
        textShadow: "0 0 3px var(--accent-glow)",
        fontFamily: "var(--font-mono)", fontSize: 10, outline: "none",
        boxShadow: "inset 2px 2px 5px rgba(0,0,0,0.6)",
      },
    };

    if (!open) {
      return (
        <button
          onClick={() => setOpen(true)}
          style={{
            position: "fixed", right: 18, bottom: 110, zIndex: 600,
            padding: "10px 14px", border: "none", borderRadius: 8,
            background: S.enabled
              ? "radial-gradient(circle at 50% 0%, #ffe39a 0%, #ffb02a 50%, #c87016 100%)"
              : "linear-gradient(180deg, var(--panel-hi), var(--panel))",
            color: S.enabled ? "#1a0a02" : "var(--ink-dim)",
            fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 11,
            letterSpacing: "0.18em", textTransform: "uppercase",
            cursor: "pointer",
            boxShadow: S.enabled
              ? "inset 0 1px 0 rgba(255,255,255,0.4), 0 0 16px rgba(255,122,26,0.6)"
              : "var(--nshadow-out-sm)",
            display: "flex", alignItems: "center", gap: 8,
            animation: S.enabled && S.pulse > 0.3 ? "pulse 0.15s" : "none",
          }}>
          <span style={{
            width: 10, height: 10, borderRadius: "50%",
            background: S.enabled ? "#fff" : "var(--ink-faint)",
            boxShadow: S.enabled ? "0 0 8px #fff" : "none",
          }} />
          ⚡ Strobo {S.enabled ? "ON" : ""}
        </button>
      );
    }

    return (
      <div style={{
        position: "fixed", left: pos.x, top: pos.y,
        width: 320, zIndex: 600,
        background: "linear-gradient(180deg, var(--panel-hi), var(--panel-lo))",
        borderRadius: 10,
        boxShadow: "0 20px 50px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.06)",
        padding: 12,
      }}>
        {/* Header */}
        <div onMouseDown={startDrag} style={{
          display: "flex", alignItems: "center", gap: 10, marginBottom: 10,
          cursor: "move", userSelect: "none",
        }}>
          <span style={{
            width: 10, height: 10, borderRadius: "50%",
            background: S.enabled && S.pulse > 0.1 ? "#ffae3a" : "#3a3a42",
            boxShadow: S.enabled && S.pulse > 0.1 ? "0 0 10px #ff7a1a" : "none",
          }} />
          <span style={{
            flex: 1, fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 12,
            letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--accent)",
          }}>⚡ Strobo Engine</span>
          <button data-lum-close="1" style={styles.btn} onClick={() => setOpen(false)}>×</button>
        </div>

        {/* Enable + Mode */}
        <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
          <button
            style={{ ...styles.btn, ...(S.enabled ? styles.btnActive : {}), flex: 1 }}
            onClick={() => { S.enabled = !S.enabled; tick(n => n+1); }}>
            {S.enabled ? "● ON" : "○ OFF"}
          </button>
          <button
            style={{ ...styles.btn, ...(S.mode === "manual" ? styles.btnActive : {}) }}
            onClick={() => { S.fire(); tick(n => n+1); }}>
            FIRE
          </button>
        </div>

        {/* Mode selector */}
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-faint)",
          textTransform: "uppercase", letterSpacing: "0.18em", margin: "8px 0 4px" }}>Trigger by</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 4 }}>
          {["audio", "video", "timed", "manual"].map(m => (
            <button key={m}
              style={{ ...styles.btn, ...(S.mode === m ? styles.btnActive : {}) }}
              onClick={() => { S.mode = m; tick(n => n+1); }}>
              {m}
            </button>
          ))}
        </div>

        {/* Type */}
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-faint)",
          textTransform: "uppercase", letterSpacing: "0.18em", margin: "10px 0 4px" }}>Effect type</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 4 }}>
          {["flash", "hue", "edges", "vignette", "bands", "scale"].map(t => (
            <button key={t}
              style={{ ...styles.btn, ...(S.type === t ? styles.btnActive : {}) }}
              onClick={() => { S.type = t; tick(n => n+1); }}>
              {t}
            </button>
          ))}
        </div>

        {/* Audio band (only relevant for audio mode) */}
        {S.mode === "audio" && (
          <>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-faint)",
              textTransform: "uppercase", letterSpacing: "0.18em", margin: "10px 0 4px" }}>Audio band</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 4 }}>
              {["bass", "mid", "high", "energy"].map(b => (
                <button key={b}
                  style={{ ...styles.btn, ...(S.band === b ? styles.btnActive : {}) }}
                  onClick={() => { S.band = b; tick(n => n+1); }}>
                  {b}
                </button>
              ))}
            </div>
            <label style={{ display: "flex", gap: 6, alignItems: "center", marginTop: 8,
              fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-dim)" }}>
              <input type="checkbox" checked={S.audioFollowColor}
                onChange={(e) => { S.audioFollowColor = e.target.checked; tick(n => n+1); }} />
              Color from band (bass=red mid=green high=blue)
            </label>
          </>
        )}

        {/* Timed: rate */}
        {S.mode === "timed" && (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-faint)",
              textTransform: "uppercase", letterSpacing: "0.18em", marginBottom: 4 }}>
              Rate · {S.rate.toFixed(1)} Hz
            </div>
            <input type="range" min="0.5" max="24" step="0.1" value={S.rate}
              onChange={(e) => { S.rate = Number(e.target.value); tick(n => n+1); }}
              style={{ width: "100%" }} />
          </div>
        )}

        {/* Video: status */}
        {S.mode === "video" && (
          <div style={{ marginTop: 10, padding: 8,
            background: "rgba(75,230,255,0.06)", border: "1px solid rgba(75,230,255,0.2)",
            borderRadius: 6, fontSize: 9, color: "var(--ink-dim)", lineHeight: 1.6,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{
                width: 16, height: 16, borderRadius: 3,
                background: S.detectedColor
                  ? `rgb(${S.detectedColor.r|0},${S.detectedColor.g|0},${S.detectedColor.b|0})`
                  : "#000",
                boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.1)",
              }} />
              <span>Detected: <b style={{ color: "var(--led-cyan)" }}>
                {S.detectedColor
                  ? `rgb(${S.detectedColor.r|0}, ${S.detectedColor.g|0}, ${S.detectedColor.b|0})`
                  : "no video"}
              </b></span>
            </div>
            <div style={{ marginTop: 4, fontSize: 8 }}>
              Add a webcam or video layer. Strobo will flash matching the dominant color.
            </div>
          </div>
        )}

        {/* Threshold + Manual color */}
        <div style={{ marginTop: 10 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-faint)",
            textTransform: "uppercase", letterSpacing: "0.18em", marginBottom: 4 }}>
            Threshold · {S.threshold.toFixed(2)}
          </div>
          <input type="range" min="0.05" max="0.95" step="0.01" value={S.threshold}
            onChange={(e) => { S.threshold = Number(e.target.value); tick(n => n+1); }}
            style={{ width: "100%" }} />
        </div>

        {S.mode !== "audio" && S.mode !== "video" && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 10 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-dim)" }}>Color</span>
            <input type="color" value={S.color}
              onChange={(e) => { S.color = e.target.value; tick(n => n+1); }}
              style={{ width: 30, height: 22, border: "none", background: "transparent" }} />
            <div style={{ flex: 1 }} />
            {/* Activity meter */}
            <div style={{
              width: 100, height: 6, borderRadius: 3,
              background: "#0a0a0c", boxShadow: "inset 1px 1px 3px rgba(0,0,0,0.6)",
              overflow: "hidden",
            }}>
              <div style={{
                width: `${S.pulse * 100}%`, height: "100%",
                background: "linear-gradient(90deg, var(--accent-glow), var(--accent))",
                boxShadow: "0 0 6px var(--accent-glow)",
                transition: "width 60ms",
              }} />
            </div>
          </div>
        )}
      </div>
    );
  }

  // Self-mount in a new root once DOM ready
  function mount() {
    if (!window.React || !window.ReactDOM) {
      setTimeout(mount, 100);
      return;
    }
    let host = document.getElementById("__strobo_panel");
    if (!host) {
      host = document.createElement("div");
      host.id = "__strobo_panel";
      document.body.appendChild(host);
    }
    const root = ReactDOM.createRoot(host);
    root.render(<StroboPanel />);
  }
  if (document.readyState === "complete" || document.readyState === "interactive") {
    setTimeout(mount, 600);
  } else {
    document.addEventListener("DOMContentLoaded", () => setTimeout(mount, 600));
  }
})();
