/* ========================================================================
   LUMINA — Top bar + Transport bar + Export modal
   ======================================================================== */
const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

/* ----------  TOP BAR  ---------- */
function MenuBar({ onLoadAudio, onMic, onDemo, openExport }) {
  const [open, setOpen] = useStateT(null);
  const [anchor, setAnchor] = useStateT(null);
  const barRef = useRefT(null);

  useEffectT(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (barRef.current && barRef.current.contains(e.target)) return;
      if (e.target.closest && e.target.closest("[data-lumina-menu]")) return;
      setOpen(null);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  const openMenu = (m, el) => {
    const r = el.getBoundingClientRect();
    setAnchor({ left: r.left, top: r.bottom + 6 });
    setOpen(m);
  };

  const cmdK = () => document.dispatchEvent(new KeyboardEvent("keydown",
    { key: "k", metaKey: true, ctrlKey: true, bubbles: true }));
  const go = (ws) => window.__setWorkspace && window.__setWorkspace(ws);
  const clickTool = (label) => {
    const b = [...document.querySelectorAll("button")].find(x =>
      !x.closest(".menubar") && (x.textContent || "").trim().toLowerCase().includes(label.toLowerCase()));
    if (b) b.click();
  };
  const cycleViz = (rnd) => {
    const list = window.VISUALIZERS || [];
    if (!list.length || !window.__setVizId) return;
    const cur = window.__vizIdSnapshot ? window.__vizIdSnapshot() : null;
    let i = list.findIndex(v => v.id === cur);
    i = rnd ? Math.floor(Math.random() * list.length) : (i + 1) % list.length;
    window.__setVizId(list[i].id);
  };
  const fullscreen = () => {
    if (document.fullscreenElement) document.exitFullscreen();
    else document.documentElement.requestFullscreen && document.documentElement.requestFullscreen();
  };

  const MENUS = {
    File: [
      { title: "Project", items: [
        { label: "New Project", icon: "✛", run: () => { if (confirm("Start a new project? Unsaved changes will be lost.")) { try { localStorage.removeItem("lumina_autosave_v1"); } catch (e) {} location.reload(); } } },
        { label: "Open Project…", icon: "▸", kbd: "⌘O", run: () => window.LuminaProject && window.LuminaProject.load() },
        { label: "Save Project", icon: "▾", kbd: "⌘S", run: () => window.LuminaProject && window.LuminaProject.save() },
      ]},
      { title: "Media", items: [
        { label: "Load Audio File…", icon: "♪", run: onLoadAudio },
        { label: "Export / Render…", icon: "⤓", run: openExport },
      ]},
    ],
    Edit: [
      { title: "Search", items: [
        { label: "Command Palette…", icon: "⌕", kbd: "⌘K", run: cmdK },
      ]},
      { title: "Reset", items: [
        { label: "Reset Parameters", icon: "↺", run: () => window.__resetParams && window.__resetParams() },
        { label: "Reset Tool Positions", icon: "⊞", run: () => window.LuminaResetLauncherPositions && window.LuminaResetLauncherPositions() },
      ]},
    ],
    View: [
      { title: "Perform", items: [
        { label: "Stage", icon: "▶", run: () => go("stage") },
        { label: "Live Loops", icon: "▦", run: () => go("composition") },
        { label: "Slideshow", icon: "▣", run: () => go("slideshow") },
      ]},
      { title: "Design", items: [
        { label: "3D Scene", icon: "◆", run: () => go("scene3d") },
        { label: "Boards", icon: "A", run: () => go("text") },
        { label: "Output Map", icon: "▥", run: () => go("mapping") },
        { label: "Lighting · DMX", icon: "✸", run: () => go("lighting") },
      ]},
      { title: "Advanced", items: [
        { label: "Nodes", icon: "⊣", run: () => go("nodes") },
        { label: "Generative", icon: "✦", run: () => go("generative") },
      ]},
      { title: "Display", items: [
        { label: "Toggle Fullscreen", icon: "⛶", kbd: "F", run: fullscreen },
      ]},
    ],
    Audio: [
      { title: "Source", items: [
        { label: "Load File…", icon: "♪", run: onLoadAudio },
        { label: "Microphone", icon: "🎙", run: onMic },
        { label: "Demo Synth", icon: "〜", run: onDemo },
      ]},
      { title: "Capture", items: [
        { label: "Webcam", icon: "◉", run: () => window.AudioEngine && window.AudioEngine.useWebcam() },
        { label: "Screen Capture", icon: "▭", run: () => window.AudioEngine && window.AudioEngine.useScreen() },
      ]},
      { title: "Transport", items: [
        { label: "Stop All", icon: "■", run: () => window.AudioEngine && window.AudioEngine.stop() },
      ]},
    ],
    Visualizer: [
      { title: "Browse", items: [
        { label: "Browse All…", icon: "⌕", kbd: "⌘K", run: cmdK },
        { label: "Next Visualizer", icon: "⏭", run: () => cycleViz(false) },
        { label: "Random Visualizer", icon: "⚄", run: () => cycleViz(true) },
      ]},
      { title: "Automate", items: [
        { label: "Auto VJ", icon: "🤖", run: () => clickTool("auto vj") },
        { label: "Custom FX Studio", icon: "✦", run: () => clickTool("custom fx") },
      ]},
    ],
    Render: [
      { title: "Export", items: [
        { label: "Export Video / Image…", icon: "⤓", run: openExport },
        { label: "Start / Stop Recording", icon: "●", run: () => clickTool("record") },
      ]},
      { title: "Analyze", items: [
        { label: "Performance Monitor", icon: "📊", run: () => clickTool("fps") },
      ]},
    ],
    Cast: [
      { title: "Output", items: [
        { label: "Open Output Window", icon: "⧉", run: () => clickTool("new window") },
        { label: "Live Output On/Off", icon: "◉", run: () => clickTool("live output") },
        { label: "Preview Monitor", icon: "▢", run: () => clickTool("preview") },
      ]},
      { title: "Setup", items: [
        { label: "Projector Calibration", icon: "⊹", run: () => clickTool("calibrate") },
      ]},
    ],
    Help: [
      { title: "Learn", items: [
        { label: "Quick Start / Guide", icon: "?", run: () => window.__openHelp && window.__openHelp() },
        { label: "Command Palette…", icon: "⌕", kbd: "⌘K", run: cmdK },
      ]},
      { title: "Info", items: [
        { label: "About LUMINA", icon: "✦", run: () => window.__openHelp && window.__openHelp() },
      ]},
    ],
  };

  return (
    <div className="menubar hide-mobile" ref={barRef} style={{ position: "relative" }}>
      {Object.keys(MENUS).map(m => (
        <div key={m} style={{ position: "relative" }}>
          <button className={`nbtn compact ${open === m ? "glow pressed" : ""}`}
            onClick={(e) => open === m ? setOpen(null) : openMenu(m, e.currentTarget)}
            onMouseEnter={(e) => { if (open && open !== m) openMenu(m, e.currentTarget); }}>
            {m}
          </button>
          {open === m && anchor && ReactDOM.createPortal(
            <div data-lumina-menu="1" style={{
              position: "fixed", top: anchor.top, left: anchor.left, zIndex: 9000,
              minWidth: 210, padding: 6,
              background: "linear-gradient(180deg, var(--panel-hi), var(--panel-lo))",
              borderRadius: 11, boxShadow: "0 16px 40px rgba(0,0,0,0.72), inset 0 1px 0 rgba(255,255,255,0.05)",
              border: "1px solid rgba(255,255,255,0.06)",
            }}
              onMouseDown={(e) => e.stopPropagation()}>
              {MENUS[m].map((group, gi) => (
                <div key={gi} style={{
                  marginTop: gi === 0 ? 0 : 4, padding: 4, borderRadius: 8,
                  background: "rgba(0,0,0,0.22)",
                  boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.03)",
                }}>
                  <div style={{
                    fontFamily: "var(--font-display)", fontSize: 8.5, fontWeight: 700,
                    letterSpacing: "0.2em", textTransform: "uppercase",
                    color: "var(--accent)", opacity: 0.65, padding: "3px 8px 5px",
                  }}>{group.title}</div>
                  {group.items.map((it, i) => (
                    <button key={i}
                      onClick={() => { setOpen(null); try { it.run(); } catch (e) { console.warn(e); } }}
                      style={{
                        display: "flex", width: "100%", alignItems: "center",
                        gap: 10, padding: "7px 9px", border: "none", borderRadius: 6,
                        background: "transparent", color: "var(--ink)", cursor: "pointer",
                        fontFamily: "var(--font-ui)", fontSize: 12, textAlign: "left", whiteSpace: "nowrap",
                      }}
                      onMouseEnter={e => e.currentTarget.style.background = "rgba(255,174,58,0.16)"}
                      onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                      <span style={{
                        width: 18, textAlign: "center", flexShrink: 0,
                        color: "var(--ink-dim)", fontSize: 12,
                      }}>{it.icon}</span>
                      <span style={{ flex: 1 }}>{it.label}</span>
                      {it.kbd && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-faint)" }}>{it.kbd}</span>}
                    </button>
                  ))}
                </div>
              ))}
            </div>,
            document.body
          )}
        </div>
      ))}
    </div>
  );
}

function TopBar({ projectName, setProjectName, audio, fileName,
                  onLoadFile, onMic, onDemo, openExport, source }) {
  const fileInputRef = useRefT(null);
  return (
    <div className="panel" style={{ padding: 0 }}>
      <div className="topbar-inner">
        <div className="brand">
          <div className="brand-mark">L</div>
          <div className="brand-text">
            LUMINA<small>VJ SUITE · v2026.1 · BETA</small>
          </div>
        </div>

        <MenuBar
          onLoadAudio={() => fileInputRef.current && fileInputRef.current.click()}
          onMic={onMic} onDemo={onDemo} openExport={openExport} />

        {/* Source switcher */}
        <div className="hide-mobile" style={{ display: "flex", gap: 4, marginLeft: 12, alignItems: "center" }}>
          <input ref={fileInputRef} type="file" accept="audio/*" hidden
            onChange={e => e.target.files[0] && onLoadFile(e.target.files[0])} />
          <span className="cap" style={{ marginRight: 4 }}>SRC</span>
          <button className={`nbtn compact ${source === "file" ? "glow pressed" : ""}`}
            onClick={() => fileInputRef.current.click()} title="Load audio file">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>
            </svg>
            File
          </button>
          <button className={`nbtn compact ${source === "mic" ? "glow pressed" : ""}`}
            onClick={onMic} title="Live microphone input">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3"/>
            </svg>
            Mic
          </button>
          <button className={`nbtn compact ${source === "demo" ? "glow pressed" : ""}`}
            onClick={onDemo} title="Demo synth">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M3 12h3l3-9 3 18 3-12 3 6h3"/>
            </svg>
            Demo
          </button>
          <button className="nbtn compact" onClick={() => window.AudioEngine.useWebcam()} title="Webcam (live video to layers)">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="13" r="4"/><path d="M3 7h4l2-3h6l2 3h4v13H3z"/>
            </svg>
            Cam
          </button>
          <button className="nbtn compact" onClick={() => window.AudioEngine.useScreen()} title="Screen capture">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>
            </svg>
            Screen
          </button>
          <button className={`nbtn compact ${source === "off" ? "" : "danger"}`}
            onClick={() => window.AudioEngine.stop()}
            title="Stop all audio sources"
            style={{ marginLeft: 4, fontWeight: 700 }}>
            <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor">
              <rect x="1" y="1" width="8" height="8" rx="1"/>
            </svg>
            STOP
          </button>
        </div>

        {/* Now playing LCD */}
        <Lcd tone="amber" className="now-playing hide-mobile"
          style={{ minWidth: 220, display: "flex", alignItems: "center", gap: 8 }}>
          <div className="np-label" style={{ flex: 1 }}>
            {fileName || "— no signal —"}
          </div>
          <Led on={audio?.energy > 0.05} color="green" />
        </Lcd>

        <div className="topbar-spacer" />

        {/* project name */}
        <input
          value={projectName}
          onChange={e => setProjectName(e.target.value)}
          className="hide-mobile"
          style={{
            background: "transparent", border: "none",
            color: "var(--ink-dim)", fontFamily: "var(--font-display)",
            fontSize: 11, letterSpacing: "0.1em", textAlign: "right",
            outline: "none", width: 140
          }}
        />

        {/* Right cluster */}
        <div className="topbar-cluster">
          <button className="nbtn compact">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.4-2.3l2-1.5-2-3.4-2.4.9a7 7 0 0 0-4-2.3L12 1H10l-.2 2.4a7 7 0 0 0-4 2.3l-2.4-.9-2 3.4 2 1.5A7 7 0 0 0 3 12c0 .8.1 1.6.4 2.3l-2 1.5 2 3.4 2.4-.9a7 7 0 0 0 4 2.3L10 23h2l.2-2.4a7 7 0 0 0 4-2.3l2.4.9 2-3.4-2-1.5c.3-.7.4-1.5.4-2.3z"/>
            </svg>
          </button>
          <button className="nbtn glow pressed" onClick={openExport}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 3v12M7 10l5 5 5-5M5 21h14"/>
            </svg>
            Export
          </button>
        </div>
      </div>
    </div>
  );
}

/* ----------  TRANSPORT BAR  ---------- */
function Transport({ audio, source, volume, setVolume, muted, setMuted }) {
  const [, force] = useStateT(0);
  // tick every 100ms to update meters/time
  useEffectT(() => {
    const id = setInterval(() => force(n => n + 1), 80);
    return () => clearInterval(id);
  }, []);

  const A = window.AudioEngine;
  const dur = A.audioEl?.duration || 0;
  const cur = A.audioEl?.currentTime || 0;
  const fmtT = (s) => {
    if (!isFinite(s)) return "00:00";
    const m = Math.floor(s / 60), ss = Math.floor(s % 60);
    return `${m.toString().padStart(2,"0")}:${ss.toString().padStart(2,"0")}`;
  };
  const progress = dur ? cur / dur : 0;

  // fake waveform of timeline (static, drawn once-ish based on dur)
  const wavebars = [];
  for (let i = 0; i < 120; i++) {
    const seed = Math.sin(i * 0.45) * Math.cos(i * 0.18) * 0.5 + 0.5;
    const v = 0.2 + seed * 0.8;
    wavebars.push(v);
  }
  const beatLed = audio?.beat > 0.4;

  return (
    <div className="panel" style={{ padding: 0 }}>
      <div className="transport-bar">
        {/* LEFT: time displays */}
        <div className="transport-section">
          <Lcd tone="amber" style={{ fontSize: 16, fontWeight: 700, padding: "8px 12px", minWidth: 90, textAlign: "center" }}>
            {fmtT(cur)}
          </Lcd>
          <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
            <span className="cap">Elapsed</span>
            <span className="cap">/ {fmtT(dur)}</span>
          </div>
          <div style={{ flex: 1 }} />
          <VU level={audio?.energy || 0} segments={10} />
        </div>

        {/* CENTER: timeline + transport buttons */}
        <div className="transport-section" style={{ flexDirection: "column", gap: 6, padding: "10px 12px" }}>
          <div className="timeline" onClick={(e) => {
            const r = e.currentTarget.getBoundingClientRect();
            A.seek((e.clientX - r.left) / r.width);
          }}>
            <div className="timeline-wave">
              {wavebars.map((v, i) => {
                const passed = (i / wavebars.length) < progress;
                return <span key={i} style={{
                  height: `${v * 100}%`,
                  opacity: passed ? 0.95 : 0.35,
                  filter: passed ? "none" : "saturate(0.4)",
                }} />;
              })}
            </div>
            <div className="timeline-playhead" style={{ left: `${progress * 100}%` }} />
          </div>
          <div style={{ display: "flex", gap: 6, justifyContent: "center", alignItems: "center" }}>
            <button className="nbtn square compact" onClick={() => A.audioEl && (A.audioEl.currentTime = 0)}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                <path d="M6 6h2v12H6zM22 6L10 12l12 6z"/>
              </svg>
            </button>
            <button className="nbtn square compact" onClick={() => A.audioEl && (A.audioEl.currentTime = Math.max(0, A.audioEl.currentTime - 5))}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                <path d="M11 18V6L2 12zM22 18V6l-9 6z"/>
              </svg>
            </button>
            <button className="nbtn glow pressed square" style={{ width: 44, height: 38 }}
              onClick={() => A.toggle()}>
              {A.audioEl && !A.audioEl.paused ? (
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M6 4h4v16H6zM14 4h4v16h-4z"/>
                </svg>
              ) : (
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M6 4l14 8-14 8z"/>
                </svg>
              )}
            </button>
            <button className="nbtn square compact" onClick={() => A.audioEl && (A.audioEl.currentTime = Math.min(A.audioEl.duration || 0, A.audioEl.currentTime + 5))}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                <path d="M2 6l9 6-9 6zM13 6l9 6-9 6z"/>
              </svg>
            </button>
            <button className="nbtn square compact"
              onClick={() => { if (A.audioEl) A.audioEl.loop = !A.audioEl.loop; force(n=>n+1); }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M17 1l4 4-4 4M3 11V9a4 4 0 0 1 4-4h14M7 23l-4-4 4-4M21 13v2a4 4 0 0 1-4 4H3"/>
              </svg>
            </button>
            <div style={{ width: 14 }} />
            <Led on={beatLed} color="red" />
            <span className="cap" style={{ marginLeft: 4 }}>BPM</span>
            <Lcd tone="red" style={{ fontSize: 10, padding: "3px 6px" }}>
              {audio?.beat > 0.4 ? "128" : "—"}
            </Lcd>
          </div>
        </div>

        {/* RIGHT: master + volume + mute */}
        <div className="transport-section">
          <VU level={audio?.bass || 0} segments={10} />
          <VU level={audio?.high || 0} segments={10} />
          <div style={{ flex: 1 }} />
          <button className={`nbtn square compact ${muted ? "danger pressed" : ""}`}
            onClick={() => setMuted(!muted)}>
            {muted ? (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M11 5L6 9H2v6h4l5 4zM23 9l-6 6M17 9l6 6"/>
              </svg>
            ) : (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M11 5L6 9H2v6h4l5 4zM19 5a8 8 0 0 1 0 14M15 9a4 4 0 0 1 0 6"/>
              </svg>
            )}
          </button>
          <Fader value={volume} onChange={v => setVolume(v)} min={0} max={1} height={60} label="MAIN" />
        </div>
      </div>
    </div>
  );
}

/* ----------  EXPORT MODAL  ---------- */
function ExportModal({ open, onClose, format, setFormat, res, setRes, orient, setOrient,
                       fps, setFps, duration, setDuration, codec, setCodec, quality, setQuality,
                       onRender }) {
  if (!open) return null;
  const [tab, setTab] = useStateT("video");

  const presets = {
    "1920x1080": "Full HD",
    "3840x2160": "4K UHD",
    "1280x720": "HD",
    "1080x1080": "Square",
    "1080x1920": "Mobile / Stories",
    "2048x2048": "2K Square",
    "custom":     "Custom",
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <Screws />
        <div className="modal-title">Render &amp; Export</div>
        <div className="modal-sub">Set destination format, resolution, and quality.</div>

        {/* tabs */}
        <div className="chips" style={{ marginBottom: 16 }}>
          {[
            { value: "video", label: "Video" },
            { value: "sequence", label: "Image Seq." },
            { value: "still", label: "Still Frame" },
            { value: "stream", label: "Stream Out" },
          ].map(t => (
            <button key={t.value}
              className={`chip ${tab === t.value ? "active" : ""}`}
              onClick={() => setTab(t.value)}>{t.label}</button>
          ))}
        </div>

        {/* FORMAT */}
        <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 14, marginBottom: 14, alignItems: "center" }}>
          <div className="cap lit">Format</div>
          <div className="chips">
            {tab === "video" && ["MP4 H.264", "MP4 H.265", "WebM VP9", "MOV ProRes", "GIF"].map(f => (
              <button key={f} className={`chip ${format === f ? "active" : ""}`}
                onClick={() => setFormat(f)}>{f}</button>
            ))}
            {tab === "sequence" && ["PNG seq", "JPG seq", "EXR seq", "TIFF seq"].map(f => (
              <button key={f} className={`chip ${format === f ? "active" : ""}`}
                onClick={() => setFormat(f)}>{f}</button>
            ))}
            {tab === "still" && ["PNG", "JPG", "WebP", "SVG"].map(f => (
              <button key={f} className={`chip ${format === f ? "active" : ""}`}
                onClick={() => setFormat(f)}>{f}</button>
            ))}
            {tab === "stream" && ["RTMP", "NDI", "Texture Share", "Wireless Display", "Cast"].map(f => (
              <button key={f} className={`chip ${format === f ? "active" : ""}`}
                onClick={() => setFormat(f)}>{f}</button>
            ))}
          </div>
        </div>

        {/* RESOLUTION */}
        <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 14, marginBottom: 14, alignItems: "center" }}>
          <div className="cap lit">Resolution</div>
          <div className="chips" style={{ flexWrap: "wrap" }}>
            {Object.entries(presets).map(([k, lbl]) => (
              <button key={k} className={`chip ${res === k ? "active" : ""}`}
                onClick={() => setRes(k)}>{lbl}<br/>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 8, opacity: 0.7 }}>
                  {k !== "custom" ? k : "—"}
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* ORIENTATION */}
        <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 14, marginBottom: 14, alignItems: "center" }}>
          <div className="cap lit">Orientation</div>
          <div className="chips">
            <button className={`chip ${orient === "landscape" ? "active" : ""}`}
              onClick={() => setOrient("landscape")}>▭ Landscape</button>
            <button className={`chip ${orient === "portrait" ? "active" : ""}`}
              onClick={() => setOrient("portrait")}>▯ Portrait</button>
            <button className={`chip ${orient === "square" ? "active" : ""}`}
              onClick={() => setOrient("square")}>▢ Square</button>
          </div>
        </div>

        {/* FPS + duration + codec + quality knobs */}
        <div className="dock-section" style={{ marginBottom: 14 }}>
          <div className="dock-label">Quality</div>
          <div className="knob-grid">
            <Knob value={fps} onChange={setFps} min={24} max={120} step={1} label="FPS"
              display={v => v.toFixed(0)} />
            <Knob value={duration} onChange={setDuration} min={1} max={300} step={1} label="Length"
              display={v => `${v}s`} />
            <Knob value={quality} onChange={setQuality} min={1} max={100} step={1} label="Quality"
              display={v => `${v}%`} />
            <Knob value={parseInt(codec)} onChange={v => setCodec(String(v))}
              min={1} max={5} step={1} label="Bitrate"
              display={v => `${["6","12","24","48","100"][v-1]}M`} />
          </div>
        </div>

        {/* Audio mux */}
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          marginBottom: 14, padding: "8px 12px",
          background: "linear-gradient(180deg, var(--panel-lo), #1a1a1e)",
          borderRadius: "var(--r-md)", boxShadow: "var(--nshadow-in-sm)"
        }}>
          <div>
            <div className="cap lit">Mux audio</div>
            <div style={{ fontSize: 10, color: "var(--ink-faint)", marginTop: 2 }}>
              Embed source audio in output
            </div>
          </div>
          <Flip value={true} onChange={() => {}} />
        </div>

        {/* Action row */}
        <div style={{ display: "flex", gap: 8, justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontSize: 10, color: "var(--ink-faint)", fontFamily: "var(--font-mono)" }}>
            EST ~ {Math.ceil(duration * fps / 30)} MB · {Math.ceil(duration * 1.2)}s
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="nbtn" onClick={onClose}>Cancel</button>
            <button className="nbtn glow pressed" onClick={() => { onRender(); onClose(); }}>
              ● Start Render
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.TopBar = TopBar;
window.Transport = Transport;
window.ExportModal = ExportModal;
