/* ========================================================================
   LUMINA — Floating Recorder Panel
   Real WebM/MP4 capture of the stage with audio mux + screenshot.
   ======================================================================== */
(function () {
  const { useState, useEffect, useRef } = React;

  function RecorderButton() {
    const [open, setOpen] = useState(false);
    const [, tick] = useState(0);
    useEffect(() => {
      const id = setInterval(() => tick(n => n + 1), 250);
      const R = window.LuminaRecorder;
      const unsub = R?.on?.(() => tick(n => n + 1));
      return () => { clearInterval(id); unsub?.(); };
    }, []);

    const R = window.LuminaRecorder;
    if (!R) return null;
    const active = R.active;
    const elapsed = R.elapsed();
    const mm = String(Math.floor(elapsed / 60)).padStart(2, "0");
    const ss = String(Math.floor(elapsed % 60)).padStart(2, "0");

    if (!open) {
      return (
        <button
          onClick={() => setOpen(true)}
          style={{
            padding: "8px 14px", border: "none", borderRadius: 8,
            background: active
              ? "radial-gradient(circle at 50% 0%, #ffc4c4 0%, #ff3b3b 50%, #8a1818 100%)"
              : "linear-gradient(180deg, var(--panel-hi), var(--panel))",
            color: active ? "#fff" : "var(--led-red)",
            fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 11,
            letterSpacing: "0.18em", textTransform: "uppercase",
            cursor: "pointer",
            boxShadow: active
              ? "inset 0 1px 0 rgba(255,255,255,0.4), 0 0 16px rgba(255,59,59,0.6)"
              : "var(--nshadow-out-sm)",
            display: "flex", alignItems: "center", gap: 6,
            textShadow: active ? "0 0 6px rgba(255,255,255,0.4)" : "0 0 4px rgba(255,59,59,0.5)",
            animation: active ? "pulse 1.2s infinite" : "none",
          }}>
          <span style={{
            width: 8, height: 8, borderRadius: "50%",
            background: active ? "#fff" : "var(--led-red)",
            boxShadow: active ? "0 0 8px #fff" : "0 0 6px var(--led-red-glow)",
          }} />
          {active ? `REC ${mm}:${ss}` : "RECORD"}
        </button>
      );
    }

    return (
      <div style={{
        width: 280,
        background: "linear-gradient(180deg, var(--panel-hi), var(--panel-lo))",
        borderRadius: 10, padding: 12,
        boxShadow: "0 20px 50px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,59,59,0.3)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{
            fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 12,
            letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--led-red)",
            textShadow: "0 0 4px var(--led-red-glow)", flex: 1,
          }}>● Output Recorder</span>
          <button data-lum-close="1" className="nbtn compact" onClick={() => setOpen(false)} style={{ padding: "2px 7px" }}>×</button>
        </div>

        {/* Status display */}
        <div style={{
          background: "linear-gradient(180deg, #0a0a0c, #14141a)",
          borderRadius: 6, padding: "12px 14px",
          textAlign: "center",
          boxShadow: "var(--nshadow-in-sm)",
          marginBottom: 10,
        }}>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 700,
            color: active ? "var(--led-red)" : "var(--ink-faint)",
            textShadow: active ? "0 0 8px var(--led-red-glow)" : "none",
            lineHeight: 1,
          }}>{mm}:{ss}</div>
          <div style={{ fontSize: 9, color: "var(--ink-faint)", letterSpacing: "0.2em",
            textTransform: "uppercase", marginTop: 4 }}>
            {active ? "● Recording" : "Stopped"} · {R.format.toUpperCase()} · {R.fps}fps
          </div>
        </div>

        {/* Settings */}
        <div className="cap" style={{ marginBottom: 4 }}>Format</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 4, marginBottom: 8 }}>
          {["webm", "mp4"].map(f => (
            <button key={f} className={`nbtn compact ${R.format === f ? "glow pressed" : ""}`}
              onClick={() => { R.format = f; tick(n => n+1); }}
              disabled={active}
              style={{ padding: "5px 0", fontSize: 9 }}>{f.toUpperCase()}</button>
          ))}
        </div>

        <div className="cap" style={{ marginBottom: 4 }}>FPS</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 4, marginBottom: 8 }}>
          {[24, 30, 60, 120].map(n => (
            <button key={n} className={`nbtn compact ${R.fps === n ? "glow pressed" : ""}`}
              onClick={() => { R.fps = n; tick(n => n+1); }}
              disabled={active}
              style={{ padding: "5px 0", fontSize: 9 }}>{n}</button>
          ))}
        </div>

        <div className="cap" style={{ marginBottom: 4 }}>Bitrate</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 4, marginBottom: 10 }}>
          {[{l:"Low", v:2_000_000}, {l:"Med", v:8_000_000}, {l:"High", v:24_000_000}].map(o => (
            <button key={o.l} className={`nbtn compact ${R.bitrate === o.v ? "glow pressed" : ""}`}
              onClick={() => { R.bitrate = o.v; tick(n => n+1); }}
              disabled={active}
              style={{ padding: "5px 0", fontSize: 9 }}>{o.l}</button>
          ))}
        </div>

        {/* Transport */}
        <div style={{ display: "grid", gridTemplateColumns: active ? "1fr" : "1fr 1fr", gap: 6, marginBottom: 6 }}>
          {!active ? (
            <button className="nbtn glow pressed" style={{ padding: "10px", fontWeight: 700 }}
              onClick={() => R.start()}>● START</button>
          ) : (
            <button className="nbtn danger pressed" style={{ padding: "10px", fontWeight: 700 }}
              onClick={() => R.stop()}>■ STOP &amp; SAVE</button>
          )}
          {!active && (
            <button className="nbtn compact" style={{ padding: "10px" }}
              onClick={() => R.snapshot()}>📸 SNAPSHOT</button>
          )}
        </div>

        <div style={{ fontSize: 9, color: "var(--ink-faint)", lineHeight: 1.5, textAlign: "center" }}>
          Captures the live stage canvas + AudioEngine output.
          {R.canRecord() ? "" : <><br/>⚠ MediaRecorder unavailable in this browser.</>}
        </div>
      </div>
    );
  }

  function mount() {
    if (!window.React || !window.ReactDOM) { setTimeout(mount, 100); return; }
    let host = document.getElementById("__recorder_panel");
    if (!host) {
      host = document.createElement("div");
      host.id = "__recorder_panel";
      host.style.cssText = "position: fixed; z-index: 596;";
      document.body.appendChild(host);
    }
    ReactDOM.createRoot(host).render(<RecorderButton />);
  }
  if (document.readyState === "complete" || document.readyState === "interactive") setTimeout(mount, 1100);
  else document.addEventListener("DOMContentLoaded", () => setTimeout(mount, 1100));
})();
