(function () {
  'use strict';

  // ── Theme tokens ─────────────────────────────────────────────────────────────
  const tk = {
    bgPage: '#0f0f0f', bgCard: '#1a1a1a', bgCardAlt: '#141414', bgInput: '#111',
    bgHover: '#222', bgSunken: '#0a0a0a', bgOverlay: 'rgba(0,0,0,0.75)',
    border: '#2a2a2a', borderSubtle: '#1e1e1e',
    textPrimary: '#f5f5f5', textSecondary: '#aaaaaa', textMuted: '#666',
    textDisabled: '#444', accent: '#00ff00', accentText: '#000', error: '#ff4444',
  };

  // ── Demo data ─────────────────────────────────────────────────────────────────
  const TOTAL_DURATION = 78;

  const DEMO_CLIPS = [
    { id: 'v1a', row: 0, start: 0,  dur: 45, name: 'Interview.mp4',     color: '#1e3a8a' },
    { id: 'v1b', row: 0, start: 47, dur: 29, name: 'BRoll_Park.mp4',    color: '#1e40af' },
    { id: 'v2a', row: 1, start: 8,  dur: 22, name: 'Logo_Reveal.mp4',   color: '#4c1d95' },
    { id: 'v2b', row: 1, start: 52, dur: 18, name: 'Title_Card.png',    color: '#5b21b6' },
    { id: 'a1a', row: 2, start: 0,  dur: 45, name: 'Interview Audio',   color: '#064e3b' },
    { id: 'a2a', row: 3, start: 0,  dur: 78, name: 'Background_Music.mp3', color: '#065f46' },
  ];

  const TRACK_LABELS = ['V1', 'V2', 'A1', 'A2'];

  const DEMO_MEDIA = [
    { id: 'm1', name: 'Interview.mp4',        dur: '1:30', type: 'video', seed: 'vlsm1' },
    { id: 'm2', name: 'BRoll_Park.mp4',        dur: '0:48', type: 'video', seed: 'vlsm2' },
    { id: 'm3', name: 'Logo_Reveal.mp4',       dur: '0:22', type: 'video', seed: 'vlsm3' },
    { id: 'm4', name: 'Background_Music.mp3',  dur: '3:24', type: 'audio', seed: null    },
    { id: 'm5', name: 'Title_Card.png',        dur: null,   type: 'image', seed: 'vlsm5' },
  ];

  const CAPTION_SEGMENTS = [
    { t: '0:00', text: 'Welcome to our brand showcase.' },
    { t: '0:08', text: "We've been building this for two years." },
    { t: '0:18', text: 'The technology is finally ready.' },
    { t: '0:31', text: 'And today we launch to the world.' },
  ];

  const LUT_NAMES = ['Cinematic', 'Warm Summer', 'Teal & Orange', 'Matte Black', 'Film Grain', 'Golden Hour'];
  const LUT_COLORS = ['#1a3a5a', '#3d2a1a', '#1a3a3a', '#2a1a1a', '#2a2a1a', '#3a2800'];

  const FILTER_NAMES = ['Vivid', 'Faded', 'Chrome', 'Noir', 'Warm', 'Cool', 'Vintage', 'Punch', 'Matte'];
  const FILTER_STYLES = [
    'saturate(1.6) contrast(1.1)',
    'saturate(0.7) brightness(1.05)',
    'saturate(0.9) hue-rotate(10deg) contrast(1.15)',
    'grayscale(1) contrast(1.2)',
    'sepia(0.4) brightness(1.08)',
    'hue-rotate(200deg) saturate(1.2)',
    'sepia(0.6) hue-rotate(340deg)',
    'saturate(1.8) contrast(1.3)',
    'saturate(0.5) brightness(1.05) contrast(0.95)',
  ];

  const TRANSITION_NAMES = ['Crossfade', 'Slide L', 'Slide R', 'Wipe', 'Blur', 'Zoom In', 'Glitch', 'Dip Black', 'Cube'];
  const TRANSITION_COLORS = ['#1d4ed8','#7c3aed','#5b21b6','#065f46','#0e7490','#b45309','#991b1b','#1f2937','#374151'];

  const EQ_BANDS = ['Sub', 'Low', 'Mid', 'Hi', 'Air'];
  const EQ_DEFAULTS = [0, 2, -1, 3, 1];

  // ── CSS ───────────────────────────────────────────────────────────────────────
  const css = `
    .vlsed { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; display: flex; flex-direction: column; background: ${tk.bgPage}; color: ${tk.textPrimary}; width: 100%; height: 560px; overflow: hidden; font-size: 12px; line-height: 1.4; }
    .vlsed-topbar { height: 40px; background: #111; border-bottom: 1px solid ${tk.border}; display: flex; align-items: center; gap: 5px; padding: 0 10px; flex-shrink: 0; }
    .vlsed-body { flex: 1; display: flex; overflow: hidden; min-height: 0; }
    .vlsed-rail { width: 38px; background: #111; border-right: 1px solid ${tk.borderSubtle}; display: flex; flex-direction: column; align-items: center; padding: 4px 0; gap: 1px; flex-shrink: 0; overflow: hidden; }
    .vlsed-rail-btn { width: 32px; height: 34px; border-radius: 5px; border: none; background: transparent; color: ${tk.textDisabled}; cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; transition: background 0.1s, color 0.1s; padding: 0; }
    .vlsed-rail-btn:hover { background: ${tk.bgHover}; color: ${tk.textSecondary}; }
    .vlsed-rail-btn.active { background: rgba(0,255,0,0.08); color: ${tk.accent}; }
    .vlsed-rail-label { font-size: 7px; font-weight: 700; letter-spacing: 0.2px; text-transform: uppercase; line-height: 1; }
    .vlsed-sidebar { width: 220px; background: #0d0d0d; border-right: 1px solid ${tk.border}; display: flex; flex-direction: column; overflow: hidden; flex-shrink: 0; }
    .vlsed-sidebar-head { height: 28px; background: #111; border-bottom: 1px solid ${tk.borderSubtle}; display: flex; align-items: center; padding: 0 10px; font-size: 10px; font-weight: 700; color: ${tk.textMuted}; text-transform: uppercase; letter-spacing: 1.5px; flex-shrink: 0; }
    .vlsed-sidebar-body { flex: 1; overflow-y: auto; overflow-x: hidden; }
    .vlsed-center { flex: 1; display: flex; flex-direction: column; overflow: hidden; min-width: 0; }
    .vlsed-preview { flex: 1; background: #000; position: relative; overflow: hidden; cursor: pointer; min-height: 0; }
    .vlsed-controls { height: 40px; background: #141414; border-top: 1px solid ${tk.border}; display: flex; align-items: center; gap: 8px; padding: 0 10px; flex-shrink: 0; }
    .vlsed-timeline { height: 190px; background: ${tk.bgSunken}; border-top: 1px solid ${tk.border}; flex-shrink: 0; display: flex; flex-direction: column; }
    .vlsed-tl-toolbar { height: 28px; background: #111; border-bottom: 1px solid ${tk.borderSubtle}; display: flex; align-items: center; gap: 6px; padding: 0 10px; flex-shrink: 0; }
    .vlsed-tl-ruler { height: 18px; background: #0d0d0d; border-bottom: 1px solid ${tk.borderSubtle}; position: relative; display: flex; flex-shrink: 0; }
    .vlsed-tl-ruler-label { width: 46px; flex-shrink: 0; border-right: 1px solid ${tk.borderSubtle}; }
    .vlsed-tl-ruler-track { flex: 1; position: relative; overflow: hidden; }
    .vlsed-tl-tracks { flex: 1; overflow: hidden; }
    .vlsed-tl-row { display: flex; height: 36px; border-bottom: 1px solid #1a1a1a; }
    .vlsed-tl-label { width: 46px; background: #0d0d0d; border-right: 1px solid ${tk.borderSubtle}; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 700; color: #444; flex-shrink: 0; }
    .vlsed-tl-track { flex: 1; position: relative; background: #0c0c0c; overflow: hidden; cursor: pointer; }
    .vlsed-clip { position: absolute; top: 3px; height: 28px; border-radius: 3px; display: flex; align-items: center; overflow: hidden; cursor: pointer; transition: opacity 0.1s, box-shadow 0.1s; border: 1px solid rgba(255,255,255,0.08); box-sizing: border-box; }
    .vlsed-clip:hover { opacity: 0.85; }
    .vlsed-clip.selected { border-color: rgba(255,255,255,0.5); box-shadow: 0 0 0 1px rgba(255,255,255,0.2); }
    .vlsed-clip-label { font-size: 9px; color: rgba(255,255,255,0.8); padding: 0 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 600; }
    .vlsed-btn { padding: 3px 9px; border-radius: 4px; border: 1px solid ${tk.border}; background: #1a1a1a; color: ${tk.textMuted}; font-size: 11px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; transition: background 0.1s, color 0.1s; }
    .vlsed-btn:hover { background: #222; color: ${tk.textSecondary}; }
    .vlsed-btn.active { background: rgba(0,255,0,0.1); border-color: rgba(0,255,0,0.4); color: ${tk.accent}; }
    .vlsed-btn:disabled { opacity: 0.35; cursor: not-allowed; pointer-events: none; }
    .vlsed-media-item { display: flex; gap: 8px; padding: 5px 8px; border-radius: 4px; cursor: pointer; align-items: center; }
    .vlsed-media-item:hover { background: ${tk.bgHover}; }
    .vlsed-swatch-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; padding: 8px; }
    .vlsed-swatch { border-radius: 4px; overflow: hidden; cursor: pointer; border: 1px solid rgba(255,255,255,0.06); transition: border-color 0.1s; }
    .vlsed-swatch:hover { border-color: rgba(255,255,255,0.25); }
    .vlsed-swatch.active { border-color: ${tk.accent} !important; }
    .vlsed-range { width: 100%; height: 3px; border-radius: 2px; accent-color: ${tk.accent}; cursor: pointer; }
    .vlsed-caption-seg { padding: 6px 10px; border-bottom: 1px solid ${tk.borderSubtle}; cursor: pointer; display: flex; gap: 8px; align-items: flex-start; }
    .vlsed-caption-seg:hover { background: ${tk.bgHover}; }
    .vlsed-caption-seg.active { background: rgba(0,255,0,0.05); border-left: 2px solid ${tk.accent}; }
  `;

  // ── Panel components ──────────────────────────────────────────────────────────

  function PanelGetContent({ onClose }) {
    return (
      <div style={{ padding: 0 }}>
        <div style={{ padding: '8px', borderBottom: `1px solid ${tk.borderSubtle}` }}>
          <button className="vlsed-btn" style={{ width: '100%', justifyContent: 'center', color: tk.accent, borderColor: 'rgba(0,255,0,0.3)' }}>
            + Import Media
          </button>
        </div>
        <div style={{ padding: '6px 4px' }}>
          {DEMO_MEDIA.map(m => (
            <div key={m.id} className="vlsed-media-item">
              <div style={{ width: 48, height: 27, borderRadius: 3, overflow: 'hidden', background: '#1a1a1a', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {m.seed ? (
                  <img src={`https://picsum.photos/seed/${m.seed}/96/54`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                ) : (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={tk.textDisabled} strokeWidth="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                )}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 11, color: tk.textSecondary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.name}</div>
                <div style={{ fontSize: 10, color: tk.textDisabled, marginTop: 1 }}>
                  {m.dur && <span>{m.dur}</span>}
                  <span style={{ marginLeft: m.dur ? 6 : 0, textTransform: 'uppercase' }}>{m.type}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  const FX_LABELS = ['Compressor', 'Reverb', 'De-Esser'];

  function PanelAudio() {
    const [vals, setVals] = React.useState(EQ_DEFAULTS.slice());
    const [fxVals, setFxVals] = React.useState([40, 20, 0]);
    const presets = [
      { name: 'Voice', v: [0, -1, 2, 4, 2] },
      { name: 'Music', v: [3, 1, -1, 1, 3] },
      { name: 'Podcast', v: [-2, 1, 3, 2, 1] },
    ];
    return (
      <div style={{ padding: 10 }}>
        <div style={{ fontSize: 10, color: tk.textMuted, fontWeight: 700, letterSpacing: 1, marginBottom: 8, textTransform: 'uppercase' }}>EQ Bands</div>
        <div style={{ display: 'flex', gap: 6, justifyContent: 'space-between', height: 80, alignItems: 'flex-end', marginBottom: 8 }}>
          {EQ_BANDS.map((band, i) => (
            <div key={band} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, flex: 1 }}>
              <input type="range" min={-12} max={12} value={vals[i]}
                onChange={e => setVals(prev => prev.map((v, j) => j === i ? Number(e.target.value) : v))}
                style={{ writingMode: 'vertical-lr', direction: 'rtl', height: 60, width: 4, accentColor: vals[i] > 0 ? tk.accent : '#3b82f6', cursor: 'pointer' }} />
              <span style={{ fontSize: 8, color: tk.textDisabled }}>{band}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 4, marginBottom: 12 }}>
          {presets.map(p => (
            <button key={p.name} className="vlsed-btn" style={{ flex: 1, justifyContent: 'center', fontSize: 10, padding: '3px 4px' }}
              onClick={() => setVals(p.v.slice())}>{p.name}</button>
          ))}
        </div>
        {FX_LABELS.map((label, i) => (
          <div key={label} style={{ marginBottom: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3, fontSize: 10 }}>
              <span style={{ color: tk.textMuted }}>{label}</span>
              <span style={{ color: tk.textSecondary }}>{fxVals[i]}%</span>
            </div>
            <input type="range" min={0} max={100} value={fxVals[i]}
              onChange={e => setFxVals(prev => prev.map((v, j) => j === i ? Number(e.target.value) : v))}
              className="vlsed-range" />
          </div>
        ))}
      </div>
    );
  }

  function PanelFilters() {
    const [active, setActive] = React.useState(null);
    return (
      <div>
        <div style={{ padding: '6px 8px', borderBottom: `1px solid ${tk.borderSubtle}`, fontSize: 10, color: tk.textMuted }}>
          Click a filter to preview on your clip
        </div>
        <div className="vlsed-swatch-grid">
          {FILTER_NAMES.map((name, i) => (
            <div key={name} className={`vlsed-swatch${active === name ? ' active' : ''}`} onClick={() => setActive(active === name ? null : name)}>
              <div style={{ height: 44, background: '#1a1a1a', overflow: 'hidden' }}>
                <img src="https://picsum.photos/seed/vlsf/220/124" alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', filter: FILTER_STYLES[i] }} />
              </div>
              <div style={{ padding: '3px 5px', fontSize: 9, color: active === name ? tk.accent : tk.textMuted, fontWeight: 600 }}>{name}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function PanelText() {
    const [bold, setBold] = React.useState(false);
    const [italic, setItalic] = React.useState(false);
    const [size, setSize] = React.useState(48);
    const [color, setColor] = React.useState('#ffffff');
    const fonts = ['Inter', 'Georgia', 'Courier New', 'Impact', 'Playfair Display'];
    const [font, setFont] = React.useState(fonts[0]);
    const alignments = [
      { id: 'left', svg: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="18" y2="18"/></svg> },
      { id: 'center', svg: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="6" y1="12" x2="18" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg> },
      { id: 'right', svg: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="9" y1="12" x2="21" y2="12"/><line x1="6" y1="18" x2="21" y2="18"/></svg> },
    ];
    const [align, setAlign] = React.useState('left');
    return (
      <div style={{ padding: 10 }}>
        <div style={{ fontSize: 10, color: tk.textMuted, marginBottom: 4 }}>Font</div>
        <select value={font} onChange={e => setFont(e.target.value)}
          style={{ width: '100%', background: tk.bgInput, border: `1px solid ${tk.border}`, color: tk.textPrimary, fontSize: 11, padding: '4px 6px', borderRadius: 4, marginBottom: 10, cursor: 'pointer' }}>
          {fonts.map(f => <option key={f}>{f}</option>)}
        </select>
        <div style={{ display: 'flex', gap: 4, marginBottom: 10 }}>
          <button className={`vlsed-btn${bold?' active':''}`} onClick={() => setBold(b => !b)} style={{ fontWeight: 800, width: 28, justifyContent: 'center' }}>B</button>
          <button className={`vlsed-btn${italic?' active':''}`} onClick={() => setItalic(b => !b)} style={{ fontStyle: 'italic', width: 28, justifyContent: 'center' }}>I</button>
          {alignments.map(a => (
            <button key={a.id} className={`vlsed-btn${align===a.id?' active':''}`} onClick={() => setAlign(a.id)} style={{ width: 28, justifyContent: 'center' }}>{a.svg}</button>
          ))}
        </div>
        <div style={{ marginBottom: 10 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginBottom: 3 }}>
            <span style={{ color: tk.textMuted }}>Size</span>
            <span style={{ color: tk.textSecondary }}>{size}px</span>
          </div>
          <input type="range" min={8} max={120} value={size} onChange={e => setSize(Number(e.target.value))} className="vlsed-range" />
        </div>
        <div>
          <div style={{ fontSize: 10, color: tk.textMuted, marginBottom: 4 }}>Color</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {['#ffffff','#000000','#ff4444','#00ff00','#ffcc00','#3b82f6','#a855f7','#f97316'].map(c => (
              <div key={c} onClick={() => setColor(c)} style={{ width: 20, height: 20, borderRadius: 3, background: c, cursor: 'pointer', border: color === c ? '2px solid #fff' : '1px solid rgba(255,255,255,0.2)' }} />
            ))}
          </div>
        </div>
        <div style={{ marginTop: 12 }}>
          <div style={{ fontSize: 10, color: tk.textMuted, marginBottom: 4 }}>Preview</div>
          <div style={{ background: tk.bgCard, border: `1px solid ${tk.border}`, borderRadius: 4, padding: '10px', textAlign: align === 'center' ? 'center' : (align === 'right' ? 'right' : 'left') }}>
            <span style={{ fontFamily: font, fontSize: Math.min(size, 24), fontWeight: bold ? 700 : 400, fontStyle: italic ? 'italic' : 'normal', color }}>Sample Text</span>
          </div>
        </div>
      </div>
    );
  }

  function PanelCaptions() {
    const [activeSeg, setActiveSeg] = React.useState(0);
    const [editing, setEditing] = React.useState(null);
    const [editText, setEditText] = React.useState('');
    return (
      <div>
        <div style={{ padding: '6px 8px', borderBottom: `1px solid ${tk.borderSubtle}`, display: 'flex', gap: 6 }}>
          <button className="vlsed-btn active" style={{ flex: 1, justifyContent: 'center', fontSize: 10 }}>Captions</button>
          <button className="vlsed-btn" style={{ flex: 1, justifyContent: 'center', fontSize: 10 }}>Style</button>
          <button className="vlsed-btn" style={{ flex: 1, justifyContent: 'center', fontSize: 10 }}>Export</button>
        </div>
        {CAPTION_SEGMENTS.map((seg, i) => (
          <div key={i} className={`vlsed-caption-seg${activeSeg === i ? ' active' : ''}`} onClick={() => { setActiveSeg(i); setEditing(null); }}>
            <span style={{ fontSize: 9, color: tk.accent, fontFamily: 'monospace', flexShrink: 0 }}>{seg.t}</span>
            {editing === i ? (
              <div style={{ flex: 1 }} onClick={e => e.stopPropagation()}>
                <input autoFocus value={editText} onChange={e => setEditText(e.target.value)}
                  style={{ width: '100%', background: tk.bgInput, border: `1px solid rgba(0,255,0,0.4)`, borderRadius: 3, color: tk.textPrimary, fontSize: 11, padding: '2px 5px', outline: 'none' }}
                  onBlur={() => setEditing(null)} />
              </div>
            ) : (
              <span style={{ fontSize: 11, color: activeSeg === i ? tk.textPrimary : tk.textSecondary, flex: 1, lineHeight: 1.3 }}
                onDoubleClick={() => { setEditing(i); setEditText(seg.text); }}>
                {seg.text}
              </span>
            )}
          </div>
        ))}
        <div style={{ padding: 8 }}>
          <button className="vlsed-btn" style={{ width: '100%', justifyContent: 'center', fontSize: 10 }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
            Transcribe with Whisper
          </button>
        </div>
      </div>
    );
  }

  function PanelTransitions() {
    const [active, setActive] = React.useState('Crossfade');
    const [cat, setCat] = React.useState('All');
    return (
      <div>
        <div style={{ padding: '6px 8px', borderBottom: `1px solid ${tk.borderSubtle}`, display: 'flex', gap: 4, overflowX: 'auto' }}>
          {['All','Dissolve','Motion','Warp'].map(c => (
            <button key={c} className={`vlsed-btn${cat===c?' active':''}`} style={{ flex: 'none', fontSize: 10, padding: '2px 7px' }} onClick={() => setCat(c)}>{c}</button>
          ))}
        </div>
        <div className="vlsed-swatch-grid">
          {TRANSITION_NAMES.map((name, i) => (
            <div key={name} className={`vlsed-swatch${active===name?' active':''}`} onClick={() => setActive(name)}>
              <div style={{ height: 40, background: TRANSITION_COLORS[i], display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 2 }}>
                <div style={{ width: 18, height: 28, background: 'rgba(0,0,0,0.4)', borderRadius: 2 }} />
                <div style={{ width: 14, height: 22, background: 'rgba(255,255,255,0.1)', borderRadius: 2 }} />
                <div style={{ width: 18, height: 28, background: 'rgba(0,0,0,0.4)', borderRadius: 2 }} />
              </div>
              <div style={{ padding: '3px 5px', fontSize: 9, color: active===name ? tk.accent : tk.textMuted, fontWeight: 600 }}>{name}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: '6px 8px', borderTop: `1px solid ${tk.borderSubtle}` }}>
          <div style={{ fontSize: 10, color: tk.textMuted, marginBottom: 3 }}>Duration</div>
          <div style={{ display: 'flex', gap: 4 }}>
            {['0.3s','0.5s','1.0s','1.5s'].map(d => (
              <button key={d} className="vlsed-btn" style={{ flex: 1, justifyContent: 'center', fontSize: 10, padding: '2px 0' }}>{d}</button>
            ))}
          </div>
        </div>
      </div>
    );
  }

  const EFFECT_DEFS = [
    { name: 'Blur', def: 0, max: 20 },
    { name: 'Sharpen', def: 0, max: 20 },
    { name: 'Vignette', def: 25, max: 100 },
    { name: 'Opacity', def: 100, max: 100 },
    { name: 'Grain', def: 0, max: 20 },
  ];

  function PanelEffects() {
    const [blend, setBlend] = React.useState('Normal');
    const [effectVals, setEffectVals] = React.useState(() => Object.fromEntries(EFFECT_DEFS.map(e => [e.name, e.def])));
    const blendModes = ['Normal', 'Multiply', 'Screen', 'Overlay', 'Soft Light', 'Hard Light', 'Color Dodge', 'Difference'];
    return (
      <div style={{ padding: 10 }}>
        <div style={{ fontSize: 10, color: tk.textMuted, marginBottom: 4 }}>Blend Mode</div>
        <select value={blend} onChange={e => setBlend(e.target.value)}
          style={{ width: '100%', background: tk.bgInput, border: `1px solid ${tk.border}`, color: tk.textPrimary, fontSize: 11, padding: '4px 6px', borderRadius: 4, marginBottom: 12, cursor: 'pointer' }}>
          {blendModes.map(m => <option key={m}>{m}</option>)}
        </select>
        {EFFECT_DEFS.map(({ name, max }) => (
          <div key={name} style={{ marginBottom: 9 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginBottom: 3 }}>
              <span style={{ color: tk.textMuted }}>{name}</span>
              <span style={{ color: tk.textSecondary }}>{effectVals[name]}{name === 'Opacity' ? '%' : ''}</span>
            </div>
            <input type="range" min={0} max={max} value={effectVals[name]}
              onChange={e => setEffectVals(prev => ({ ...prev, [name]: Number(e.target.value) }))}
              className="vlsed-range" />
          </div>
        ))}
      </div>
    );
  }

  function PanelPresets() {
    const [activeLut, setActiveLut] = React.useState(null);
    const [bright, setBright] = React.useState(100);
    const [contr, setContr] = React.useState(100);
    const [sat, setSat] = React.useState(100);
    return (
      <div>
        <div style={{ padding: '6px 8px 0' }}>
          <div style={{ fontSize: 10, color: tk.textMuted, marginBottom: 6, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>LUT Presets</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4, marginBottom: 10 }}>
            {LUT_NAMES.map((name, i) => (
              <div key={name} onClick={() => setActiveLut(activeLut === name ? null : name)}
                style={{ borderRadius: 4, overflow: 'hidden', cursor: 'pointer', border: activeLut === name ? `1px solid ${tk.accent}` : `1px solid ${tk.border}`, transition: 'border-color 0.1s' }}>
                <div style={{ height: 28, background: LUT_COLORS[i] }} />
                <div style={{ padding: '2px 5px', fontSize: 9, fontWeight: 600, color: activeLut === name ? tk.accent : tk.textMuted }}>{name}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '0 8px 8px' }}>
          {[['Brightness', bright, setBright, 50, 150], ['Contrast', contr, setContr, 50, 150], ['Saturation', sat, setSat, 0, 200]].map(([label, val, setVal, mn, mx]) => (
            <div key={label} style={{ marginBottom: 8 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginBottom: 2 }}>
                <span style={{ color: tk.textMuted }}>{label}</span>
                <span style={{ color: tk.textSecondary }}>{val}%</span>
              </div>
              <input type="range" min={mn} max={mx} value={val} onChange={e => setVal(Number(e.target.value))} className="vlsed-range" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  function PanelAuto() {
    const [analyzed, setAnalyzed] = React.useState(false);
    const [analyzing, setAnalyzing] = React.useState(false);
    const suggestions = [
      { label: 'Stabilize clip at 0:08', type: 'Video', action: 'Apply' },
      { label: 'Lower music between 0:18–0:25', type: 'Audio', action: 'Apply' },
      { label: 'Add captions to interview segment', type: 'Captions', action: 'Generate' },
    ];
    const typeColors = { Video: '#1d4ed8', Audio: '#065f46', Captions: '#7c3aed' };
    const handleAnalyze = () => {
      setAnalyzing(true);
      setTimeout(() => { setAnalyzing(false); setAnalyzed(true); }, 1800);
    };
    return (
      <div style={{ padding: 10 }}>
        {!analyzed ? (
          <div style={{ textAlign: 'center', paddingTop: 20 }}>
            <div style={{ fontSize: 22, marginBottom: 8, opacity: 0.3 }}>⚡</div>
            <div style={{ fontSize: 12, color: tk.textSecondary, marginBottom: 12 }}>AI analysis finds issues and suggests fixes automatically.</div>
            <button className="vlsed-btn" style={{ color: tk.accent, borderColor: 'rgba(0,255,0,0.3)', margin: '0 auto' }}
              onClick={handleAnalyze} disabled={analyzing}>
              {analyzing ? 'Analyzing...' : 'Analyze Project'}
            </button>
          </div>
        ) : (
          <div>
            <div style={{ fontSize: 10, color: tk.accent, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10 }}>3 Suggestions</div>
            {suggestions.map((s, i) => (
              <div key={i} style={{ background: tk.bgCard, border: `1px solid ${tk.border}`, borderRadius: 6, padding: '8px 10px', marginBottom: 6 }}>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 4 }}>
                  <span style={{ fontSize: 9, fontWeight: 700, padding: '1px 5px', borderRadius: 3, background: typeColors[s.type] + '22', color: typeColors[s.type] }}>{s.type}</span>
                </div>
                <div style={{ fontSize: 11, color: tk.textPrimary, marginBottom: 6 }}>{s.label}</div>
                <button className="vlsed-btn" style={{ fontSize: 10, padding: '2px 8px' }}>{s.action}</button>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  // ── Rail buttons ──────────────────────────────────────────────────────────────
  const RAIL_ITEMS = [
    { id: 'Get Content', label: 'Media', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg> },
    { id: 'Audio', label: 'Audio', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg> },
    { id: 'Filters', label: 'Filters', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="4"/></svg> },
    { id: 'Text', label: 'Text', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg> },
    { id: 'Captions', label: 'Caps', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="7" width="20" height="15" rx="2"/><path d="M8 3l-4 4 4 4"/></svg> },
    { id: 'Transitions', label: 'Trans', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg> },
    { id: 'Effects', label: 'Effects', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg> },
    { id: 'Presets', label: 'Color', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22a7 7 0 0 0 7-7c0-2.38-1.19-4.47-3-5.74L10 3 4.08 9.26C2.28 10.53 1 12.62 1 15c0 3.87 3.13 7 7 7"/></svg> },
    { id: 'Auto', label: 'Auto', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93l-1.41 1.41M4.93 4.93l1.41 1.41M12 2v2m0 18v-2m7.07-3.07l-1.41-1.41M4.93 19.07l1.41-1.41M22 12h-2M4 12H2"/></svg> },
  ];

  const PANEL_MAP = {
    'Get Content': PanelGetContent,
    'Audio': PanelAudio,
    'Filters': PanelFilters,
    'Text': PanelText,
    'Captions': PanelCaptions,
    'Transitions': PanelTransitions,
    'Effects': PanelEffects,
    'Presets': PanelPresets,
    'Auto': PanelAuto,
  };

  // ── Main component ─────────────────────────────────────────────────────────────
  function AppEnhancedReal() {
    const [activePanel, setActivePanel] = React.useState('Get Content');
    const [sidebarOpen, setSidebarOpen] = React.useState(true);
    const [isPlaying, setIsPlaying] = React.useState(false);
    const [currentTime, setCurrentTime] = React.useState(0);
    const [selectedClipId, setSelectedClipId] = React.useState(null);
    const [activeTool, setActiveTool] = React.useState('select');

    const rafRef = React.useRef(null);
    const lastTRef = React.useRef(null);
    const ctRef = React.useRef(0);
    ctRef.current = currentTime;

    React.useEffect(() => {
      if (isPlaying) {
        lastTRef.current = performance.now();
        const tick = (now) => {
          const dt = (now - lastTRef.current) / 1000;
          lastTRef.current = now;
          const next = ctRef.current + dt;
          if (next >= TOTAL_DURATION) { setCurrentTime(0); setIsPlaying(false); return; }
          setCurrentTime(next);
          rafRef.current = requestAnimationFrame(tick);
        };
        rafRef.current = requestAnimationFrame(tick);
      } else {
        cancelAnimationFrame(rafRef.current);
      }
      return () => cancelAnimationFrame(rafRef.current);
    }, [isPlaying]);

    const pct = (currentTime / TOTAL_DURATION) * 100;

    const fmt = (s) => {
      const m = Math.floor(s / 60);
      const sec = Math.floor(s % 60);
      const f = Math.floor((s % 1) * 30);
      return `${String(m).padStart(2,'0')}:${String(sec).padStart(2,'0')}.${String(f).padStart(2,'0')}`;
    };

    const PanelComp = PANEL_MAP[activePanel] || PanelGetContent;

    const handleRailClick = (panelId) => {
      if (activePanel === panelId && sidebarOpen) { setSidebarOpen(false); }
      else { setActivePanel(panelId); setSidebarOpen(true); }
    };

    const handleTimelineClick = (e) => {
      const rect = e.currentTarget.getBoundingClientRect();
      const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
      setCurrentTime(ratio * TOTAL_DURATION);
    };

    return (
      <div className="vlsed">
        <style>{css}</style>

        {/* Top toolbar */}
        <div className="vlsed-topbar">
          <span style={{ fontSize: 11, fontWeight: 700, color: tk.accent, marginRight: 4 }}>VLS</span>
          <span style={{ fontSize: 11, color: tk.textMuted, marginRight: 10 }}>Untitled Project</span>
          <div style={{ width: 1, height: 18, background: tk.border, marginRight: 6 }} />
          {[
            { id: 'select', label: '↖ Select' },
            { id: 'split', label: '⊹ Split' },
            { id: 'delete', label: '✕ Delete' },
          ].map(tool => (
            <button key={tool.id} className={`vlsed-btn${activeTool===tool.id?' active':''}`}
              onClick={() => setActiveTool(tool.id)} style={{ fontSize: 11 }}>{tool.label}</button>
          ))}
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 10, color: tk.textDisabled, fontFamily: 'monospace' }}>{fmt(currentTime)}</span>
          <div style={{ width: 1, height: 18, background: tk.border, marginLeft: 4 }} />
          <button className="vlsed-btn" disabled style={{ fontSize: 11 }}>Save</button>
          <button className="vlsed-btn" disabled style={{ fontSize: 11, color: tk.accent, borderColor: 'rgba(0,255,0,0.25)' }}>Export</button>
        </div>

        {/* Body */}
        <div className="vlsed-body">
          {/* Left rail */}
          <div className="vlsed-rail">
            {RAIL_ITEMS.map(item => (
              <button key={item.id}
                className={`vlsed-rail-btn${activePanel===item.id && sidebarOpen?' active':''}`}
                title={item.id}
                onClick={() => handleRailClick(item.id)}>
                {item.icon}
                <span className="vlsed-rail-label">{item.label}</span>
              </button>
            ))}
          </div>

          {/* Sidebar */}
          {sidebarOpen && (
            <div className="vlsed-sidebar">
              <div className="vlsed-sidebar-head">{activePanel}</div>
              <div className="vlsed-sidebar-body">
                <PanelComp />
              </div>
            </div>
          )}

          {/* Center */}
          <div className="vlsed-center">
            {/* Preview */}
            <div className="vlsed-preview" onClick={() => setIsPlaying(p => !p)}>
              <img src="https://picsum.photos/seed/vlseditor/960/540" alt=""
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', userSelect: 'none', pointerEvents: 'none' }}
                draggable={false}
              />
              {!isPlaying && (
                <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.15)' }}>
                  <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="white"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                  </div>
                </div>
              )}
              {/* Timecode overlay */}
              <div style={{ position: 'absolute', bottom: 8, left: 8, background: 'rgba(0,0,0,0.6)', padding: '2px 6px', borderRadius: 3, fontFamily: 'monospace', fontSize: 11, color: '#fff' }}>
                {fmt(currentTime)}
              </div>
            </div>

            {/* Controls */}
            <div className="vlsed-controls">
              <button className="vlsed-btn" onClick={() => setCurrentTime(0)} style={{ padding: '3px 7px' }}>
                <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><polygon points="19 20 9 12 19 4 19 20"/><line x1="5" y1="19" x2="5" y2="5" stroke="currentColor" strokeWidth="2"/></svg>
              </button>
              <button className="vlsed-btn" onClick={() => setIsPlaying(p => !p)} style={{ padding: '3px 10px' }}>
                {isPlaying
                  ? <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
                  : <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                }
              </button>
              <span style={{ fontFamily: 'monospace', fontSize: 12, color: tk.accent, minWidth: 88 }}>{fmt(currentTime)}</span>
              <span style={{ fontSize: 10, color: tk.textDisabled }}>/ {fmt(TOTAL_DURATION)}</span>
              <div style={{ flex: 1 }} />
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={tk.textDisabled} strokeWidth="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>
              <input type="range" min={0} max={100} defaultValue={80} style={{ width: 64, accentColor: tk.accent, cursor: 'pointer' }} />
            </div>
          </div>
        </div>

        {/* Timeline */}
        <div className="vlsed-timeline">
          {/* Toolbar */}
          <div className="vlsed-tl-toolbar">
            <span style={{ fontSize: 9, color: tk.textDisabled, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase' }}>Timeline</span>
            <div style={{ flex: 1 }} />
            <button className="vlsed-btn" style={{ padding: '1px 7px', fontSize: 10 }}>+ Track</button>
            <button className="vlsed-btn" style={{ padding: '1px 7px', fontSize: 10 }}>⊞ Markers</button>
            <select defaultValue="1×" style={{ background: '#1a1a1a', border: `1px solid ${tk.border}`, color: tk.textMuted, fontSize: 10, padding: '2px 4px', borderRadius: 3, cursor: 'pointer' }}>
              {['0.5×','1×','2×','4×'].map(z => <option key={z}>{z}</option>)}
            </select>
          </div>

          {/* Tracks */}
          <div className="vlsed-tl-tracks" style={{ position: 'relative' }}>
            {TRACK_LABELS.map((label, rowIdx) => {
              const rowClips = DEMO_CLIPS.filter(c => c.row === rowIdx);
              const isAudio = rowIdx >= 2;
              return (
                <div key={label} className="vlsed-tl-row">
                  <div className="vlsed-tl-label" style={{ color: isAudio ? '#1d6e4d' : '#444' }}>{label}</div>
                  <div className="vlsed-tl-track" onClick={handleTimelineClick}>
                    {/* Playhead */}
                    <div style={{ position: 'absolute', top: 0, bottom: 0, left: `${pct}%`, width: 1, background: 'rgba(255,255,255,0.35)', zIndex: 5, pointerEvents: 'none' }} />
                    {/* Clips */}
                    {rowClips.map(clip => (
                      <div key={clip.id}
                        className={`vlsed-clip${selectedClipId===clip.id?' selected':''}`}
                        style={{ left: `${(clip.start/TOTAL_DURATION)*100}%`, width: `${(clip.dur/TOTAL_DURATION)*100}%`, background: clip.color }}
                        onClick={e => { e.stopPropagation(); setSelectedClipId(clip.id===selectedClipId ? null : clip.id); }}>
                        <span className="vlsed-clip-label">{clip.name}</span>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  window.AppEnhancedReal = AppEnhancedReal;
})();
