/* ========================================================================
   LUMINA — Welcome / Help overlay
   First-run guide + always-available help (? button). Surfaces the many
   tools so new users aren't lost.
   ======================================================================== */
(function () {
  const { useState, useEffect } = React;

  const SECTIONS = [
    { title: "Workspaces", color: "#ffae3a", items: [
      ["Stage", "Live visualizer output + Go Live / Cast"],
      ["Live Loops", "Clip grid + DJ mixer · beat-snap · auto-pilot"],
      ["Slideshow", "Image/video sequence with transitions"],
      ["3D Scene", "Import GLB/OBJ/PLY · Niagara particles · splats"],
      ["Boards", "Multi-element title cards (text+image+shapes)"],
      ["Output Map", "Projection mapping · warp · masks · edge-blend"],
      ["Nodes", "Visual patching of the signal flow"],
      ["Generative", "Local Stable Diffusion / FLUX bridge"],
    ]},
    { title: "Floating Tools (dock under tabs)", color: "#4be6ff", items: [
      ["♩ Clock", "Master BPM · tap tempo · beat snap"],
      ["⌘ Cues", "16 snapshot slots · keys 1-8"],
      ["☰ Layers", "Per-layer opacity/blend/solo mixer"],
      ["⚡ Strobo", "Audio/video/timed strobe engine"],
      ["📝 Notes", "Sticky notes anchored to workspaces"],
      ["✦ Custom FX", "Write & save your own JS effects"],
      ["● Record", "Capture output to WebM/MP4"],
      ["🤖 Auto VJ", "Hands-free auto-mixing"],
      ["◎ Calibrate", "Projector test patterns"],
    ]},
    { title: "Keyboard", color: "#7cff4f", items: [
      ["⌘K", "Quick command palette — search anything"],
      ["Space", "Play / pause audio"],
      ["1-8", "Recall composition cue"],
      ["⌘1-8", "Save composition cue"],
      ["⌘S / ⌘O", "Save / open project"],
      ["Right-click knob", "MIDI learn"],
      ["Shift+drag tool", "Detach floating button from dock"],
    ]},
  ];

  function Welcome() {
    const [open, setOpen] = useState(() => {
      try { return !localStorage.getItem("lumina_seen_welcome_v1"); }
      catch (e) { return true; }
    });

    const close = () => {
      setOpen(false);
      try { localStorage.setItem("lumina_seen_welcome_v1", "1"); } catch (e) {}
    };

    useEffect(() => { window.__openHelp = () => setOpen(true); }, []);

    return (
      <>
        {/* persistent ? button */}
        <button onClick={() => setOpen(true)}
          style={{
            position: "fixed", bottom: 18, right: 18, zIndex: 588,
            width: 38, height: 38, borderRadius: "50%", border: "none",
            background: "linear-gradient(180deg, var(--panel-hi), var(--panel))",
            color: "var(--accent)", cursor: "pointer",
            fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 16,
            boxShadow: "var(--nshadow-out-sm)",
            textShadow: "0 0 6px var(--accent-glow)",
          }}>?</button>

        {open && (
          <div onClick={close} style={{
            position: "fixed", inset: 0, zIndex: 800,
            background: "rgba(0,0,0,0.78)", backdropFilter: "blur(8px)",
            display: "grid", placeItems: "center", padding: 20,
          }}>
            <div onClick={e => e.stopPropagation()} style={{
              width: "min(820px, 96vw)", maxHeight: "88vh", overflowY: "auto",
              background: "linear-gradient(180deg, var(--panel-hi), var(--panel-lo))",
              borderRadius: 16, padding: 28,
              boxShadow: "0 30px 80px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,174,58,0.3)",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 8 }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 10,
                  background: "linear-gradient(180deg, #1a1a1e, #0a0a0c)",
                  boxShadow: "inset 0 1px 0 rgba(255,255,255,0.06), 0 2px 4px rgba(0,0,0,0.5)",
                  position: "relative",
                }}>
                  <span style={{ position: "absolute", left: 13, top: 12, width: 4, height: 20,
                    background: "var(--accent)", borderRadius: 2, boxShadow: "0 0 8px var(--accent-glow)" }} />
                  <span style={{ position: "absolute", left: 13, bottom: 12, width: 18, height: 4,
                    background: "var(--accent)", borderRadius: 2, boxShadow: "0 0 8px var(--accent-glow)" }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22,
                    letterSpacing: "0.12em", color: "var(--ink)" }}>LUMINA</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-dim)" }}>
                    VJ Suite BETA · {window.VISUALIZERS?.length || 0} visualizers · pro live performance
                  </div>
                </div>
                <button className="nbtn" onClick={close} style={{ padding: "8px 16px", fontWeight: 700 }}>
                  Start →
                </button>
              </div>
              <p style={{ fontSize: 12, color: "var(--ink-dim)", lineHeight: 1.6, marginBottom: 20 }}>
                Pick an audio source (top bar: File / Mic / Demo), then explore. Everything is audio-reactive.
                Open it in a full browser tab for the best experience.
              </p>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
                {SECTIONS.map(s => (
                  <div key={s.title}>
                    <div style={{
                      fontFamily: "var(--font-display)", fontSize: 11, fontWeight: 700,
                      letterSpacing: "0.16em", textTransform: "uppercase",
                      color: s.color, marginBottom: 8, textShadow: `0 0 6px ${s.color}66`,
                      borderBottom: `1px solid ${s.color}33`, paddingBottom: 5,
                    }}>{s.title}</div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                      {s.items.map(([k, v]) => (
                        <div key={k} style={{ fontSize: 10.5, lineHeight: 1.4 }}>
                          <span style={{ color: "var(--ink)", fontWeight: 600,
                            fontFamily: "var(--font-mono)" }}>{k}</span>
                          <span style={{ color: "var(--ink-faint)", display: "block" }}>{v}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>

              <div style={{
                marginTop: 20, padding: "10px 14px",
                background: "rgba(255,174,58,0.06)",
                border: "1px solid rgba(255,174,58,0.2)",
                borderRadius: 8, fontSize: 11, color: "var(--ink-dim)", lineHeight: 1.5,
              }}>
                <b style={{ color: "var(--accent)" }}>Pro tip:</b> press <b>⌘K</b> (or Ctrl+K) anytime
                to instantly search and trigger any visualizer, effect, sound, or action.
                Everything works offline after first load — no internet required at the venue.
              </div>
            </div>
          </div>
        )}
      </>
    );
  }

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