/* ========================================================================
   LUMINA — Floating Preview & Live Output monitors
   Always-visible draggable monitors. Pin them anywhere on the UI.
   ======================================================================== */
(function () {
  const { useState, useEffect, useRef } = React;

  function findStageCanvas() {
    // The Stage panel renders a canvas inside .screen-frame
    const frames = document.querySelectorAll(".screen-frame canvas");
    return frames[0] || null;
  }

  function Monitor({ label, color, defaultPos, isLive, onClose }) {
    const [pos, setPos] = useState(defaultPos);
    const [size, setSize] = useState({ w: 320, h: 200 });
    const [collapsed, setCollapsed] = useState(false);
    const cnvRef = useRef(null);

    useEffect(() => {
      let raf;
      const tick = (t) => {
        const out = cnvRef.current;
        if (out && !collapsed) {
          const dpr = 1.5;
          const W = Math.floor(size.w * dpr);
          const H = Math.floor(size.h * dpr);
          if (out.width !== W) out.width = W;
          if (out.height !== H) out.height = H;
          out.style.width = size.w + "px";
          out.style.height = size.h + "px";
          const ctx = out.getContext("2d");
          const B = window.__blind;
          if (!isLive && B && B.armed) {
            // PREVIEW monitor in blind mode → render the STAGED look,
            // not what's on air. This is where you sculpt before TAKE.
            try {
              const A = window.AudioEngine || {};
              const audio = { bass: A.bass || 0, mid: A.mid || 0, high: A.high || 0,
                energy: A.energy || 0, beat: A.beat || 0, freq: A.freq, wave: A.wave };
              const VIS = window.VISUALIZERS || [];
              const viz = VIS.find(v => v.id === B.vizId) || VIS[0];
              const computed = window.Prog ? window.Prog.computeParams(B.params || {}, audio, t / 1000) : (B.params || {});
              ctx.fillStyle = "#05050a"; ctx.fillRect(0, 0, W, H);
              if (viz) viz.draw(ctx, W, H, audio, computed, t / 1000);
              // staged badge
              ctx.fillStyle = "rgba(255,174,58,0.92)";
              ctx.font = "bold 11px monospace";
              ctx.textAlign = "left"; ctx.textBaseline = "top";
              ctx.fillText("STAGED · TAKE to launch", 8, 6);
            } catch (e) {}
          } else {
            const src = findStageCanvas();
            if (src && src.width > 0) {
              try {
                ctx.imageSmoothingQuality = "high";
                ctx.drawImage(src, 0, 0, W, H);
              } catch (e) {}
            } else if (window.LuminaComposite) {
              // Stage not mounted (other workspace active) → render the
              // composite directly so the monitor NEVER goes dark
              try { window.LuminaComposite(ctx, W, H, t / 1000); } catch (e) {}
            }
          }
        }
        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => cancelAnimationFrame(raf);
    }, [size, collapsed]);

    const startDrag = (e) => {
      if (["BUTTON", "INPUT"].includes(e.target.tagName)) 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 startResize = (e) => {
      e.stopPropagation();
      const start = { x: e.clientX, y: e.clientY };
      const ss = { ...size };
      const onMove = (m) => setSize({
        w: Math.max(180, ss.w + (m.clientX - start.x)),
        h: Math.max(110, ss.h + (m.clientY - start.y)),
      });
      const onUp = () => { window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseup", onUp); };
      window.addEventListener("mousemove", onMove);
      window.addEventListener("mouseup", onUp);
    };

    return (
      <div style={{
        position: "fixed", left: pos.x, top: pos.y,
        width: size.w, zIndex: 590,
        background: "linear-gradient(180deg, var(--panel-hi), var(--panel-lo))",
        borderRadius: 8,
        boxShadow: `0 20px 50px rgba(0,0,0,0.8), 0 0 0 2px ${color}, 0 0 20px ${color}66`,
        overflow: "hidden",
      }}>
        {/* Title bar */}
        <div onMouseDown={startDrag} style={{
          padding: "5px 9px",
          display: "flex", alignItems: "center", gap: 6,
          cursor: "move", userSelect: "none",
          background: `linear-gradient(180deg, ${color}40, transparent)`,
          borderBottom: "1px solid rgba(255,255,255,0.06)",
        }}>
          <span style={{
            width: 7, height: 7, borderRadius: "50%",
            background: color, boxShadow: `0 0 6px ${color}`,
            animation: isLive ? "pulse 1.2s infinite" : "none",
          }} />
          <span style={{
            flex: 1, fontFamily: "var(--font-display)", fontSize: 9, fontWeight: 800,
            letterSpacing: "0.18em", textTransform: "uppercase", color,
            textShadow: `0 0 4px ${color}80`,
          }}>{label}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 8, color: "var(--ink-faint)" }}>
            {size.w}×{size.h}
          </span>
          <button
            onClick={() => setCollapsed(c => !c)}
            style={{
              border: "none", background: "transparent", cursor: "pointer",
              color: "var(--ink-dim)", padding: "0 4px", fontSize: 11, lineHeight: 1,
            }}>{collapsed ? "▢" : "─"}</button>
          <button data-lum-close="1" onClick={onClose}
            style={{
              border: "none", background: "transparent", cursor: "pointer",
              color: "var(--ink-dim)", padding: "0 4px", fontSize: 11, lineHeight: 1,
            }}>×</button>
        </div>
        {/* Canvas */}
        {!collapsed && (
          <div style={{ position: "relative", background: "#000" }}>
            <canvas ref={cnvRef} style={{ display: "block" }} />
            {/* Resize handle */}
            <div onMouseDown={startResize}
              style={{
                position: "absolute", right: 0, bottom: 0,
                width: 14, height: 14, cursor: "nwse-resize",
                background: `linear-gradient(135deg, transparent 50%, ${color} 50%)`,
                opacity: 0.6,
              }} />
          </div>
        )}
      </div>
    );
  }

  function MonitorButtons() {
    const [preview, setPreview] = useState(false);
    const [output, setOutput] = useState(false);

    const openPopupMirror = () => {
      window.open("popup-monitor.html", "lumina_output_mirror_" + Date.now(),
        "width=960,height=540,menubar=no,toolbar=no,location=no,status=no");
    };
    const openNewWindow = () => {
      window.open(window.location.href, "lumina_window_" + Date.now(),
        "width=1400,height=900,menubar=no,toolbar=no,location=no,status=no");
    };

    return (
      <>
        <div style={{
          position: "fixed", top: 80, right: 18, zIndex: 596,
          display: "flex", flexDirection: "column", gap: 6,
        }}>
          <button
            onClick={() => setPreview(p => !p)}
            style={{
              padding: "8px 12px", border: "none", borderRadius: 8,
              background: preview
                ? "linear-gradient(180deg, var(--led-amber), #c87016)"
                : "linear-gradient(180deg, var(--panel-hi), var(--panel))",
              color: preview ? "#1a0a02" : "var(--ink-dim)",
              fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 10,
              letterSpacing: "0.16em", textTransform: "uppercase",
              cursor: "pointer", textAlign: "left",
              boxShadow: preview
                ? "inset 0 1px 0 rgba(255,255,255,0.4), 0 0 12px rgba(255,174,58,0.5)"
                : "var(--nshadow-out-sm)",
              display: "flex", alignItems: "center", gap: 6,
              minWidth: 150,
            }}>
            <span style={{
              width: 8, height: 8, borderRadius: "50%",
              background: preview ? "#1a0a02" : "var(--ink-faint)",
              boxShadow: preview ? "0 0 6px #fff" : "none",
            }} />
            ◐ Preview
          </button>
          <button
            onClick={() => setOutput(o => !o)}
            style={{
              padding: "8px 12px", border: "none", borderRadius: 8,
              background: output
                ? "linear-gradient(180deg, var(--led-red), #8a1818)"
                : "linear-gradient(180deg, var(--panel-hi), var(--panel))",
              color: output ? "#fff" : "var(--ink-dim)",
              fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 10,
              letterSpacing: "0.16em", textTransform: "uppercase",
              cursor: "pointer", textAlign: "left",
              boxShadow: output
                ? "inset 0 1px 0 rgba(255,255,255,0.4), 0 0 12px rgba(255,59,59,0.6)"
                : "var(--nshadow-out-sm)",
              display: "flex", alignItems: "center", gap: 6,
              minWidth: 150,
              textShadow: output ? "0 0 6px rgba(255,255,255,0.4)" : "none",
            }}>
            <span style={{
              width: 8, height: 8, borderRadius: "50%",
              background: output ? "#fff" : "var(--ink-faint)",
              boxShadow: output ? "0 0 6px #fff" : "none",
              animation: output ? "pulse 1.2s infinite" : "none",
            }} />
            ● Live Output
          </button>
          <div style={{ position: "relative" }}>
            <button onClick={openPopupMirror}
              title="Open output as new browser window (drag to second screen) · long-click for Duplicate UI"
              onContextMenu={(e) => { e.preventDefault(); openNewWindow(); }}
              style={{
                padding: "8px 12px", border: "none", borderRadius: 8,
                background: "linear-gradient(180deg, var(--led-cyan), #1880a0)",
                color: "#062028",
                fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 10,
                letterSpacing: "0.16em", textTransform: "uppercase",
                cursor: "pointer", textAlign: "left",
                boxShadow: "inset 0 1px 0 rgba(255,255,255,0.4), 0 0 12px rgba(75,230,255,0.5)",
                display: "flex", alignItems: "center", gap: 6,
                minWidth: 150, width: "100%",
              }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                <path d="M14 3h7v7M21 3l-9 9M9 21H3v-6M3 21l9-9"/>
              </svg>
              ↗ New Window
            </button>
            <button onClick={openNewWindow}
              title="Duplicate the full UI in a new window (separate instance)"
              style={{
                position: "absolute", right: 4, top: "50%", transform: "translateY(-50%)",
                padding: "3px 6px", border: "none", borderRadius: 4,
                background: "rgba(6,32,40,0.6)",
                color: "#062028", cursor: "pointer", fontSize: 9, fontWeight: 700,
                letterSpacing: "0.1em",
              }}>UI</button>
          </div>
        </div>
        {preview && (
          <Monitor label="◐ Preview · what you're editing"
            color="#ffae3a" defaultPos={{ x: window.innerWidth - 360, y: 280 }}
            isLive={false} onClose={() => setPreview(false)} />
        )}
        {output && (
          <Monitor label="● Live Output · on air"
            color="#ff3b3b" defaultPos={{ x: window.innerWidth - 360, y: 500 }}
            isLive={true} onClose={() => setOutput(false)} />
        )}
      </>
    );
  }

  function mount() {
    if (!window.React || !window.ReactDOM) { setTimeout(mount, 100); return; }
    let host = document.getElementById("__monitors_panel");
    if (!host) {
      host = document.createElement("div");
      host.id = "__monitors_panel";
      document.body.appendChild(host);
    }
    ReactDOM.createRoot(host).render(<MonitorButtons />);
  }
  if (document.readyState === "complete" || document.readyState === "interactive") setTimeout(mount, 800);
  else document.addEventListener("DOMContentLoaded", () => setTimeout(mount, 800));
})();
