/* CaptionsShowcase.jsx — transcript/caption sync with playback showcase */
(function () {
  'use strict';

  const CDS = {
    bg:'#0f0f0f', panel:'#1a1a1a', surface:'#252525',
    border:'#2e2e2e', border2:'#333333',
    text:'#f5f5f5', dim:'#999999', muted:'#666666',
    accent:'#00FF00',
  };

  const CSS = `
    @keyframes cap-pulse { 0%,100%{opacity:1} 50%{opacity:0} }
    .cap-seg:hover { background:#1e1e1e !important; border-color:#333 !important; }
    .cap-seg.active { background:#1a2a1a !important; border-color:rgba(0,255,0,0.4) !important; }
    .cap-word.active { background:rgba(0,255,0,0.2); border-radius:2px; }
  `;

  const SEGMENTS = [
    { id:0, start:0.0,  end:2.6,  text:'Welcome to VLStudio,', words:[
      {t:0.0, w:'Welcome'},{t:0.5,w:'to'},{t:0.8,w:'VLStudio,'}]},
    { id:1, start:2.7,  end:5.4,  text:'the editor that stays on your machine.', words:[
      {t:2.7,w:'the'},{t:3.0,w:'editor'},{t:3.5,w:'that'},{t:3.8,w:'stays'},{t:4.2,w:'on'},{t:4.4,w:'your'},{t:4.7,w:'machine.'}]},
    { id:2, start:5.5,  end:8.8,  text:'No cloud uploads. No subscriptions.', words:[
      {t:5.5,w:'No'},{t:5.9,w:'cloud'},{t:6.3,w:'uploads.'},{t:6.9,w:'No'},{t:7.3,w:'subscriptions.'}]},
    { id:3, start:9.0,  end:12.2, text:'AI captions with word-level timestamps', words:[
      {t:9.0,w:'AI'},{t:9.4,w:'captions'},{t:9.9,w:'with'},{t:10.2,w:'word-level'},{t:10.8,w:'timestamps'}]},
    { id:4, start:12.4, end:15.0, text:'in 30+ languages, fully offline.', words:[
      {t:12.4,w:'in'},{t:12.7,w:'30+'},{t:13.0,w:'languages,'},{t:13.5,w:'fully'},{t:13.9,w:'offline.'}]},
    { id:5, start:15.2, end:18.5, text:"Export captions as SRT, VTT, or burn them in.", words:[
      {t:15.2,w:'Export'},{t:15.7,w:'captions'},{t:16.2,w:'as'},{t:16.4,w:'SRT,'},{t:16.8,w:'VTT,'},{t:17.1,w:'or'},{t:17.4,w:'burn'},{t:17.7,w:'them'},{t:17.9,w:'in.'}]},
    { id:6, start:18.7, end:22.0, text:'Edit any word. Change timing. Style each line.', words:[
      {t:18.7,w:'Edit'},{t:19.1,w:'any'},{t:19.4,w:'word.'},{t:19.8,w:'Change'},{t:20.3,w:'timing.'},{t:20.8,w:'Style'},{t:21.2,w:'each'},{t:21.5,w:'line.'}]},
  ];

  const TOTAL = 22;

  function VideoPreview({ time, segments, totalTime }) {
    const seg = segments.find(s => time >= s.start && time < s.end);
    const pct = (time / totalTime) * 100;

    const getActiveWord = (seg) => {
      if (!seg) return null;
      let lastWord = null;
      for (const w of seg.words) {
        if (time >= w.t) lastWord = w;
        else break;
      }
      return lastWord?.w;
    };

    const activeWord = getActiveWord(seg);

    return (
      <div style={{ position:'relative', width:'100%', aspectRatio:'16/9', background:'#050505', borderRadius:6, overflow:'hidden', border:`1px solid ${CDS.border}` }}>
        {/* Fake video frame — gradient background with subject silhouette */}
        <svg viewBox="0 0 320 180" style={{ position:'absolute', inset:0, width:'100%', height:'100%' }}>
          <defs>
            <linearGradient id="cap-bg" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#1a2a3a"/><stop offset="100%" stopColor="#0a0a0a"/>
            </linearGradient>
            <radialGradient id="cap-spot" cx="50%" cy="40%" r="50%">
              <stop offset="0%" stopColor="#2a3a4a"/><stop offset="100%" stopColor="transparent"/>
            </radialGradient>
          </defs>
          <rect width="320" height="180" fill="url(#cap-bg)"/>
          <ellipse cx="160" cy="72" rx="80" ry="70" fill="url(#cap-spot)" opacity="0.6"/>
          {/* Subject silhouette */}
          <ellipse cx="160" cy="62" rx="22" ry="26" fill="#1c1c1c"/>
          <rect x="130" y="88" width="60" height="70" rx="5" fill="#161616"/>
          {/* Microphone suggestion */}
          <rect x="155" y="48" width="10" height="22" rx="5" fill="#222"/>
          <path d="M148 68 Q148 78 160 78 Q172 78 172 68" fill="none" stroke="#2a2a2a" strokeWidth="2"/>
        </svg>

        {/* Caption overlay */}
        {seg && (
          <div style={{ position:'absolute', bottom:16, left:12, right:12, textAlign:'center' }}>
            <div style={{ background:'rgba(0,0,0,0.78)', borderRadius:4, display:'inline-block', padding:'4px 10px' }}>
              <span style={{ fontSize:12, color:'#fff', fontWeight:600, lineHeight:1.5 }}>
                {seg.words.map((w, i) => (
                  <span key={i} className={w.w === activeWord ? 'cap-word active' : 'cap-word'}
                    style={{ marginRight: i < seg.words.length-1 ? 3 : 0 }}>
                    {w.w}
                  </span>
                ))}
              </span>
            </div>
          </div>
        )}

        {/* Timecode */}
        <div style={{ position:'absolute', top:8, left:10, background:'rgba(0,0,0,0.6)', borderRadius:3, padding:'2px 7px' }}>
          <span style={{ fontFamily:'monospace', fontSize:10, color:'#bbb' }}>
            {String(Math.floor(time/60)).padStart(2,'0')}:{String(Math.floor(time%60)).padStart(2,'0')}
          </span>
        </div>

        {/* Progress bar */}
        <div style={{ position:'absolute', bottom:0, left:0, right:0, height:2, background:'rgba(255,255,255,0.1)' }}>
          <div style={{ height:'100%', width:`${pct}%`, background:CDS.accent, transition:'width 0.05s linear' }}/>
        </div>
      </div>
    );
  }

  function CaptionsShowcase({ scale = 1, style = {}, className = '' }) {
    const [time, setTime]         = React.useState(0);
    const [playing, setPlaying]   = React.useState(false);
    const [editSeg, setEditSeg]   = React.useState(null);
    const [editText, setEditText] = React.useState('');
    const [segs, setSegs]         = React.useState(SEGMENTS);
    const [userDid, setUserDid]   = React.useState(false);
    const [lang, setLang]         = React.useState('English');
    const [toast, setToast]       = React.useState(null);
    const rafRef                  = React.useRef(null);
    const lastTRef                = React.useRef(null);
    const timeRef                 = React.useRef(time);
    const listRef                 = React.useRef(null);
    timeRef.current = time;

    React.useEffect(() => () => cancelAnimationFrame(rafRef.current), []);

    // Auto-scroll transcript to active segment
    React.useEffect(() => {
      const seg = segs.find(s => time >= s.start && time < s.end);
      if (seg && listRef.current) {
        const el = listRef.current.querySelector(`[data-seg="${seg.id}"]`);
        if (el) el.scrollIntoView({ block:'nearest', behavior:'smooth' });
      }
    }, [Math.floor(time * 2), segs]);

    const interact = () => setUserDid(true);

    const startPlay = () => {
      setPlaying(true);
      lastTRef.current = performance.now();
      const tick = now => {
        const dt = (now - lastTRef.current) / 1000;
        lastTRef.current = now;
        const next = timeRef.current + dt;
        if (next >= TOTAL) { setTime(0); setPlaying(false); return; }
        setTime(next);
        rafRef.current = requestAnimationFrame(tick);
      };
      rafRef.current = requestAnimationFrame(tick);
    };

    const stopPlay = () => { cancelAnimationFrame(rafRef.current); setPlaying(false); };
    const togglePlay = () => { interact(); playing ? stopPlay() : startPlay(); };

    const startEdit = (seg) => {
      interact();
      stopPlay();
      setEditSeg(seg.id);
      setEditText(seg.text);
    };

    const commitEdit = () => {
      setSegs(ss => ss.map(s => s.id === editSeg ? { ...s, text: editText } : s));
      setEditSeg(null);
      setToast('Caption saved ✓');
      setTimeout(() => setToast(null), 1800);
    };

    const activeSeg = segs.find(s => time >= s.start && time < s.end);

    return (
      <div onMouseDown={interact} className={className}
        style={{
          width:680, background:CDS.bg, border:`1px solid ${CDS.border}`,
          borderRadius:8, overflow:'hidden', display:'flex', flexDirection:'column',
          fontFamily:"'Inter',-apple-system,sans-serif", position:'relative',
          transform: scale !== 1 ? `scale(${scale})` : undefined,
          transformOrigin:'top left',
          ...style,
        }}>
        <style>{CSS}</style>

        {/* ── Header ── */}
        <div style={{ height:36, background:'#111', borderBottom:`1px solid ${CDS.border}`, display:'flex', alignItems:'center', padding:'0 14px', gap:8 }}>
          <span style={{ fontSize:11, fontWeight:700, color:CDS.text, letterSpacing:2, textTransform:'uppercase' }}>AI Captions</span>
          <div style={{ flex:1 }}/>
          <span style={{ fontSize:10, color:CDS.muted }}>Language:</span>
          <select value={lang} onChange={e => { interact(); setLang(e.target.value); }}
            style={{ background:CDS.surface, border:`1px solid ${CDS.border2}`, color:CDS.text, fontSize:10, borderRadius:3, padding:'2px 6px', fontFamily:'inherit', cursor:'pointer' }}>
            {['English','Spanish','French','German','Japanese','Portuguese'].map(l => <option key={l}>{l}</option>)}
          </select>
          <button onClick={() => { interact(); setToast('Exported as SRT ✓'); setTimeout(()=>setToast(null),2000); }}
            style={{ background:'transparent', border:`1px solid ${CDS.border2}`, color:CDS.muted, borderRadius:3, padding:'3px 9px', fontSize:10, cursor:'pointer', fontFamily:'inherit' }}>
            Export SRT
          </button>
        </div>

        {/* ── Body: video + transcript ── */}
        <div style={{ display:'flex', flex:1, minHeight:0 }}>

          {/* Video preview pane */}
          <div style={{ width:300, flexShrink:0, padding:12, display:'flex', flexDirection:'column', gap:10, borderRight:`1px solid ${CDS.border}`, background:'#0d0d0d' }}>
            <VideoPreview time={time} segments={segs} totalTime={TOTAL}/>

            {/* Playback controls */}
            <div style={{ display:'flex', alignItems:'center', gap:6, justifyContent:'center' }}>
              <button onClick={() => { interact(); setTime(Math.max(0, time - 5)); }}
                style={{ background:'transparent', border:`1px solid ${CDS.border}`, color:CDS.muted, borderRadius:3, padding:'3px 9px', fontSize:11, cursor:'pointer', fontFamily:'inherit' }}>
                ‹‹
              </button>
              <button onClick={togglePlay}
                style={{ background: playing ? 'rgba(0,255,0,0.15)' : 'transparent', border:`1px solid ${playing ? CDS.accent : CDS.border}`, color: playing ? CDS.accent : CDS.muted, borderRadius:3, padding:'4px 16px', fontSize:13, cursor:'pointer', fontFamily:'inherit', minWidth:44 }}>
                {playing ? '⏸' : '▶'}
              </button>
              <button onClick={() => { interact(); setTime(Math.min(TOTAL, time + 5)); }}
                style={{ background:'transparent', border:`1px solid ${CDS.border}`, color:CDS.muted, borderRadius:3, padding:'3px 9px', fontSize:11, cursor:'pointer', fontFamily:'inherit' }}>
                ››
              </button>
            </div>

            {/* Stats */}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6 }}>
              {[
                { label:'Segments', val: segs.length },
                { label:'Language', val: lang.slice(0,3).toUpperCase() },
                { label:'Words', val: segs.reduce((s,seg)=>s+seg.words.length,0) },
                { label:'Accuracy', val:'98.2%' },
              ].map(s => (
                <div key={s.label} style={{ background:CDS.panel, border:`1px solid ${CDS.border}`, borderRadius:4, padding:'5px 8px' }}>
                  <div style={{ fontSize:9, color:CDS.muted }}>{s.label}</div>
                  <div style={{ fontSize:12, color:CDS.text, fontWeight:600 }}>{s.val}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Transcript list */}
          <div ref={listRef} style={{ flex:1, overflowY:'auto', padding:'8px 6px' }}>
            {segs.map(seg => {
              const isActive = activeSeg?.id === seg.id;
              const isEditing = editSeg === seg.id;
              const fmt = t => `${String(Math.floor(t/60)).padStart(2,'0')}:${String(Math.floor(t%60)).padStart(2,'0')}.${String(Math.round((t%1)*10)).padStart(1,'0')}`;
              return (
                <div key={seg.id} data-seg={seg.id}
                  className={`cap-seg${isActive?' active':''}`}
                  onClick={() => { interact(); stopPlay(); setTime(seg.start); }}
                  style={{
                    padding:'7px 10px', marginBottom:4, borderRadius:4, cursor:'pointer',
                    background: isActive ? '#1a2a1a' : 'transparent',
                    border: isActive ? `1px solid rgba(0,255,0,0.3)` : `1px solid transparent`,
                    transition:'all 0.1s',
                  }}>
                  <div style={{ display:'flex', alignItems:'flex-start', gap:8 }}>
                    {/* Timecode */}
                    <div style={{ flexShrink:0, width:76, paddingTop:1 }}>
                      <span style={{ fontFamily:'monospace', fontSize:10, color: isActive ? CDS.accent : CDS.muted }}>
                        {fmt(seg.start)}
                      </span>
                      <br/>
                      <span style={{ fontFamily:'monospace', fontSize:9, color:'#555' }}>→ {fmt(seg.end)}</span>
                    </div>

                    {/* Text or edit input */}
                    {isEditing ? (
                      <div style={{ flex:1, display:'flex', gap:6 }}>
                        <input value={editText}
                          onChange={e => setEditText(e.target.value)}
                          onKeyDown={e => { if (e.key === 'Enter') commitEdit(); if (e.key === 'Escape') setEditSeg(null); }}
                          autoFocus
                          style={{ flex:1, background:CDS.surface, border:`1px solid ${CDS.accent}`, borderRadius:3, color:CDS.text, fontSize:11, padding:'3px 7px', fontFamily:'inherit', outline:'none' }}/>
                        <button onClick={commitEdit}
                          style={{ background:CDS.accent, border:'none', color:'#000', borderRadius:3, padding:'3px 9px', fontSize:10, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>
                          Save
                        </button>
                      </div>
                    ) : (
                      <div style={{ flex:1, display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
                        <span style={{ fontSize:12, color: isActive ? CDS.text : CDS.dim, lineHeight:1.5 }}>{seg.text}</span>
                        <button onClick={e => { e.stopPropagation(); startEdit(seg); }}
                          style={{ background:'transparent', border:`1px solid ${CDS.border}`, color:'#555', borderRadius:2, padding:'1px 6px', fontSize:9, cursor:'pointer', fontFamily:'inherit', marginLeft:8, flexShrink:0, opacity: isActive ? 1 : 0.4 }}>
                          Edit
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Toast */}
        {toast && (
          <div style={{ position:'absolute', bottom:12, left:'50%', transform:'translateX(-50%)', background:CDS.accent, color:'#000', padding:'6px 14px', borderRadius:6, fontSize:11, fontWeight:700, whiteSpace:'nowrap', zIndex:20, boxShadow:'0 0 14px rgba(0,255,0,0.4)', pointerEvents:'none' }}>
            {toast}
          </div>
        )}
      </div>
    );
  }

  window.CaptionsShowcase = CaptionsShowcase;
})();
