/* KeyframeShowcase.jsx — motion path keyframe animation showcase */
(function () {
  'use strict';

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

  const CSS = `
    @keyframes kf-spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
  `;

  const W = 420, H = 260; // Canvas/preview dimensions
  const STRIP_H = 56;
  const TOTAL_DUR = 4.0; // seconds

  // Default keyframes: array of {t, x, y, scale, opacity}
  const DEF_KFS = [
    { t:0.0, x:50,  y:200, s:0.5,  o:0   },
    { t:1.0, x:120, y:80,  s:1.0,  o:1.0 },
    { t:2.0, x:280, y:120, s:1.2,  o:1.0 },
    { t:3.0, x:370, y:60,  s:0.9,  o:1.0 },
    { t:4.0, x:390, y:200, s:0.6,  o:0.3 },
  ];

  const PROPS = ['Position', 'Scale', 'Opacity'];

  function lerp(a, b, t) { return a + (b - a) * t; }

  function interpKf(kfs, time) {
    if (kfs.length === 0) return { x: W/2, y: H/2, s: 1, o: 1 };
    if (time <= kfs[0].t) return kfs[0];
    if (time >= kfs[kfs.length-1].t) return kfs[kfs.length-1];
    for (let i = 0; i < kfs.length - 1; i++) {
      const a = kfs[i], b = kfs[i+1];
      if (time >= a.t && time <= b.t) {
        const u = (time - a.t) / (b.t - a.t);
        // Smooth step
        const su = u * u * (3 - 2*u);
        return { x: lerp(a.x, b.x, su), y: lerp(a.y, b.y, su), s: lerp(a.s, b.s, su), o: lerp(a.o, b.o, su), t: time };
      }
    }
    return kfs[kfs.length-1];
  }

  function buildPath(kfs) {
    if (kfs.length < 2) return '';
    const pts = kfs.map(k => [k.x, k.y]);
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = pts[Math.max(0, i-1)];
      const p1 = pts[i];
      const p2 = pts[i+1];
      const p3 = pts[Math.min(pts.length-1, i+2)];
      const cp1x = p1[0] + (p2[0]-p0[0])/5;
      const cp1y = p1[1] + (p2[1]-p0[1])/5;
      const cp2x = p2[0] - (p3[0]-p1[0])/5;
      const cp2y = p2[1] - (p3[1]-p1[1])/5;
      d += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${p2[0]} ${p2[1]}`;
    }
    return d;
  }

  function StripKeyframe({ kf, idx, selected, pps, STRIP_H, TOTAL_DUR, onSelect, onDrag }) {
    const x = (kf.t / TOTAL_DUR) * (pps * TOTAL_DUR);
    return (
      <div onPointerDown={e => {
          e.stopPropagation();
          onSelect(idx);
          const startX = e.clientX;
          const startT = kf.t;
          e.currentTarget.setPointerCapture(e.pointerId);
          const onM = me => {
            const dt = (me.clientX - startX) / (pps * TOTAL_DUR) * TOTAL_DUR;
            const nt = Math.max(0, Math.min(TOTAL_DUR, startT + dt));
            onDrag(idx, nt);
          };
          const onU = () => { e.currentTarget.removeEventListener('pointermove', onM); e.currentTarget.removeEventListener('pointerup', onU); };
          e.currentTarget.addEventListener('pointermove', onM);
          e.currentTarget.addEventListener('pointerup', onU);
        }}
        style={{
          position:'absolute',
          left: x - 6,
          top: STRIP_H/2 - 8,
          width:14, height:14,
          background: selected ? KDS.accent : '#ff8800',
          borderRadius:2,
          transform:'rotate(45deg)',
          cursor:'ew-resize',
          border: selected ? `2px solid #fff` : `1px solid ${selected?KDS.accent:'#cc5500'}`,
          zIndex:10,
          boxShadow: selected ? `0 0 8px rgba(0,255,0,0.6)` : `0 0 4px rgba(255,136,0,0.5)`,
        }}/>
    );
  }

  function KeyframeShowcase({ scale = 1, style = {}, className = '' }) {
    const [kfs, setKfs]           = React.useState(DEF_KFS);
    const [selKf, setSelKf]       = React.useState(null);
    const [playT, setPlayT]       = React.useState(0);
    const [playing, setPlaying]   = React.useState(false);
    const [selProp, setSelProp]   = React.useState('Position');
    const [userDid, setUserDid]   = React.useState(false);
    const [showPath, setShowPath] = React.useState(true);
    const [toast, setToast]       = React.useState(null);
    const rafRef                  = React.useRef(null);
    const lastTRef                = React.useRef(null);
    const playTRef                = React.useRef(playT);
    playTRef.current = playT;

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

    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 = playTRef.current + dt;
        if (next >= TOTAL_DUR) { setPlayT(0); setPlaying(false); return; }
        setPlayT(next);
        rafRef.current = requestAnimationFrame(tick);
      };
      rafRef.current = requestAnimationFrame(tick);
    };

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

    const addKeyframe = e => {
      interact();
      stopPlay();
      const rect = e.currentTarget.getBoundingClientRect();
      const cx = e.clientX - rect.left;
      const cy = e.clientY - rect.top;
      const inter = interpKf(kfs, playT);
      const newKf = { t: playT, x: cx, y: cy, s: inter.s, o: inter.o };
      const next = [...kfs, newKf].sort((a,b) => a.t - b.t);
      setKfs(next);
      setSelKf(next.findIndex(k => k === newKf));
    };

    const dragKf = (idx, nt) => {
      interact();
      setKfs(ks => {
        const next = ks.map((k,i) => i===idx ? {...k, t: Math.round(nt*100)/100} : k);
        return next.sort((a,b) => a.t-b.t);
      });
    };

    const current = interpKf(kfs, playT);
    const pathD = buildPath(kfs);
    const PPS = W / TOTAL_DUR; // pixels-per-second for strip

    const selKfData = selKf !== null ? kfs[selKf] : null;

    return (
      <div onMouseDown={interact} className={className}
        style={{
          width:640, background:KDS.bg, border:`1px solid ${KDS.border}`,
          borderRadius:8, overflow:'hidden',
          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 ${KDS.border}`, display:'flex', alignItems:'center', padding:'0 14px', gap:8 }}>
          <span style={{ fontSize:11, fontWeight:700, color:KDS.text, letterSpacing:2, textTransform:'uppercase' }}>Keyframe Animation</span>
          <div style={{ flex:1 }}/>
          {PROPS.map(p => (
            <button key={p} onClick={() => { interact(); setSelProp(p); }}
              style={{ background: selProp===p ? 'rgba(0,255,0,0.12)' : 'transparent',
                border:`1px solid ${selProp===p ? KDS.accent : KDS.border}`,
                color: selProp===p ? KDS.accent : KDS.muted, borderRadius:3,
                padding:'3px 9px', fontSize:10, cursor:'pointer', fontFamily:'inherit' }}>
              {p}
            </button>
          ))}
          <button onClick={() => { interact(); setShowPath(p => !p); }}
            style={{ background: showPath ? 'rgba(255,136,0,0.12)' : 'transparent',
              border:`1px solid ${showPath ? KDS.motion : KDS.border}`,
              color: showPath ? KDS.motion : KDS.muted, borderRadius:3,
              padding:'3px 9px', fontSize:10, cursor:'pointer', fontFamily:'inherit' }}>
            Path
          </button>
        </div>

        {/* ── Canvas preview ── */}
        <div style={{ position:'relative', width:W, height:H, background:'#050810', borderBottom:`1px solid ${KDS.border}`, overflow:'hidden', cursor:'crosshair' }}
          onClick={addKeyframe}>
          {/* Background grid */}
          <svg style={{ position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none' }}>
            {Array.from({length:8}, (_,i) => <line key={'h'+i} x1={0} y1={(i+1)*H/9} x2={W} y2={(i+1)*H/9} stroke="#111" strokeWidth="1"/>)}
            {Array.from({length:10}, (_,i) => <line key={'v'+i} x1={(i+1)*W/11} y1={0} x2={(i+1)*W/11} y2={H} stroke="#111" strokeWidth="1"/>)}
          </svg>

          {/* Motion path */}
          {showPath && pathD && (
            <svg style={{ position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none' }}>
              <path d={pathD} fill="none" stroke="rgba(255,136,0,0.35)" strokeWidth="1.5" strokeDasharray="5,4"/>
              {/* Keyframe dots on path */}
              {kfs.map((k,i) => (
                <circle key={i} cx={k.x} cy={k.y} r={selKf===i ? 6 : 4}
                  fill={selKf===i ? KDS.accent : KDS.motion}
                  stroke={selKf===i ? '#fff' : KDS.motion}
                  strokeWidth={1.5}
                  style={{ cursor:'pointer' }}
                  onClick={e => { e.stopPropagation(); interact(); setSelKf(i); }}/>
              ))}
            </svg>
          )}

          {/* Animated object */}
          <div style={{
            position:'absolute',
            left: current.x - 20 * current.s,
            top: current.y - 20 * current.s,
            width: 40 * current.s,
            height: 40 * current.s,
            opacity: current.o,
            pointerEvents:'none',
            transition: playing ? 'none' : 'all 0.05s',
          }}>
            {/* VLS logo placeholder */}
            <div style={{ width:'100%', height:'100%', borderRadius:8, background:'linear-gradient(135deg,#00cc44,#0088ff)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:`0 0 ${12*current.s}px rgba(0,255,0,0.5)` }}>
              <span style={{ fontSize: 14*current.s, fontWeight:900, color:'#fff', letterSpacing:-0.5 }}>VL</span>
            </div>
          </div>

          {/* Hint text when no path shown */}
          <div style={{ position:'absolute', bottom:10, left:0, right:0, textAlign:'center', pointerEvents:'none' }}>
            <span style={{ fontSize:10, color:'#2a2a2a' }}>Click to add keyframe at current time</span>
          </div>
        </div>

        {/* ── Keyframe strip ── */}
        <div style={{ position:'relative', background:'#0a0a0a', borderBottom:`1px solid ${KDS.border}`, height:STRIP_H }}>
          {/* Ruler */}
          <div style={{ position:'absolute', top:0, left:0, right:0, height:16, borderBottom:`1px solid #1a1a1a` }}>
            {Array.from({length: TOTAL_DUR*2+1}, (_,i) => {
              const t = i*0.5;
              const x = (t/TOTAL_DUR) * W;
              return (
                <div key={i} style={{ position:'absolute', left:x }}>
                  <div style={{ width:1, height: i%2===0 ? 10 : 5, background: i%2===0 ? '#333' : '#222', marginTop:16-( i%2===0?10:5) }}/>
                  {i%2===0 && <span style={{ position:'absolute', top:2, left:2, fontSize:9, color:'#555' }}>{t}s</span>}
                </div>
              );
            })}
          </div>

          {/* Track row */}
          <div style={{ position:'absolute', top:16, left:0, right:0, height:STRIP_H-16 }}>
            <div style={{ position:'absolute', inset:0, background:'#0d0d0d' }}/>
            <div style={{ position:'absolute', left:0, right:0, top:'50%', height:1, background:'#1f1f1f' }}/>
            {kfs.map((kf, i) => (
              <StripKeyframe key={i} kf={kf} idx={i} selected={selKf===i}
                pps={PPS} STRIP_H={STRIP_H-16} TOTAL_DUR={TOTAL_DUR}
                onSelect={idx => { interact(); setSelKf(idx === selKf ? null : idx); }}
                onDrag={dragKf}/>
            ))}
            {/* Playhead */}
            <div style={{ position:'absolute', top:0, bottom:0, left:(playT/TOTAL_DUR)*W, width:2, background:'rgba(255,40,40,0.8)', pointerEvents:'none', zIndex:20 }}>
              <div style={{ width:0, height:0, borderLeft:'5px solid transparent', borderRight:'5px solid transparent', borderTop:'8px solid #ff2828', marginLeft:-4, marginTop:-8 }}/>
            </div>
          </div>
        </div>

        {/* ── Controls + Inspector ── */}
        <div style={{ display:'flex', background:'#111', height:66 }}>
          {/* Playback */}
          <div style={{ width:220, flexShrink:0, display:'flex', alignItems:'center', gap:6, padding:'0 12px', borderRight:`1px solid ${KDS.border}` }}>
            <button onClick={togglePlay}
              style={{ background: playing ? 'rgba(0,255,0,0.15)' : 'transparent', border:`1px solid ${playing?KDS.accent:KDS.border}`, color: playing?KDS.accent:KDS.muted, borderRadius:3, padding:'5px 14px', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>
              {playing ? '⏸' : '▶'}
            </button>
            <button onClick={() => { interact(); stopPlay(); setPlayT(0); }}
              style={{ background:'transparent', border:`1px solid ${KDS.border}`, color:KDS.muted, borderRadius:3, padding:'5px 10px', fontSize:12, cursor:'pointer', fontFamily:'inherit' }}>
              ⏮
            </button>
            <span style={{ fontFamily:'monospace', fontSize:11, color:KDS.dim }}>{playT.toFixed(2)}s</span>
            <div style={{ flex:1 }}/>
            {selKf !== null && (
              <button onClick={() => { interact(); setKfs(ks => ks.filter((_,i) => i !== selKf)); setSelKf(null); }}
                style={{ background:'transparent', border:`1px solid #5a2a2a`, color:'#cc4444', borderRadius:3, padding:'3px 8px', fontSize:10, cursor:'pointer', fontFamily:'inherit' }}>
                Del KF
              </button>
            )}
          </div>

          {/* Inspector */}
          <div style={{ flex:1, display:'flex', alignItems:'center', padding:'0 14px', gap:12 }}>
            {selKfData ? (
              <>
                <span style={{ fontSize:10, color:KDS.muted }}>KF {selKf} @ {selKfData.t.toFixed(2)}s</span>
                {[
                  { label:'X',   val: Math.round(selKfData.x) },
                  { label:'Y',   val: Math.round(selKfData.y) },
                  { label:'Scale', val: selKfData.s.toFixed(2) },
                  { label:'Opacity', val: selKfData.o.toFixed(2) },
                ].map(f => (
                  <div key={f.label} style={{ background:KDS.surface, border:`1px solid ${KDS.border}`, borderRadius:3, padding:'3px 7px', minWidth:54, textAlign:'center' }}>
                    <div style={{ fontSize:8, color:KDS.muted }}>{f.label}</div>
                    <div style={{ fontSize:11, color:KDS.accent, fontWeight:600 }}>{f.val}</div>
                  </div>
                ))}
              </>
            ) : (
              <span style={{ fontSize:11, color:KDS.muted }}>Select a keyframe to inspect</span>
            )}
          </div>
        </div>

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

  window.KeyframeShowcase = KeyframeShowcase;
})();
