/* ReelPreview — the persistent 9:16 player. Cycles storyboard scenes w/ real treatments.
   window.ReelPreview */
const { useState, useEffect, useRef, useCallback } = React;

function ReelStage({ mode, style, scenes, scene, loop, renderPct }) {
  const live = mode === 'idle' || mode === 'render' || mode === 'done';
  const isSkeleton = mode === 'skeleton';
  const Big = window.BigTreatment;
  const sc = scenes[scene] || scenes[0];
  return (
    <div className="relative w-full overflow-hidden rounded-[18px]"
      style={{ aspectRatio:'9 / 16', containerType:'inline-size', background: isSkeleton ? '#101014' : style.bg, transition:'background .5s ease' }}>

      {/* progress segments (done) */}
      {mode === 'done' && (
        <div className="absolute top-3 left-3 right-3 z-20 flex gap-1.5">
          {scenes.map((s,i)=>(
            <div key={i} className="h-[3px] flex-1 rounded-full overflow-hidden" style={{ background:'rgba(127,127,140,.32)' }}>
              <div style={{ height:'100%', background:style.accent, width: i<scene?'100%':i===scene?'60%':'0%' }} />
            </div>
          ))}
        </div>
      )}

      {live && <Big scene={sc} style={style} loopKey={`${loop}-${scene}`} />}

      {isSkeleton && (
        <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 px-[12%]">
          {[60,88,44].map((w,i)=><div key={i} className="shimmer-track h-7 rounded-lg bg-white/[0.05]" style={{ width:`${w}%` }}/>)}
        </div>
      )}

      {mode === 'render' && (
        <>
          <div className="absolute inset-0 pointer-events-none mix-blend-overlay"
            style={{ background:`linear-gradient(180deg, transparent ${Math.max(0,renderPct-12)}%, rgba(255,255,255,.5) ${renderPct}%, transparent ${Math.min(100,renderPct+12)}%)` }}/>
          <div className="absolute inset-0 pointer-events-none"
            style={{ background:`linear-gradient(180deg, rgba(0,0,0,0) ${renderPct}%, rgba(0,0,0,.45) ${renderPct}%)` }}/>
          <div className="absolute bottom-3 left-3 right-3 z-20">
            <div className="h-1.5 rounded-full bg-black/40 overflow-hidden">
              <div className="h-full rounded-full transition-[width] duration-200" style={{ width:`${renderPct}%`, background:'#FFE600' }}/>
            </div>
          </div>
        </>
      )}

      {mode === 'done' && (
        <div className="absolute bottom-3 left-0 right-0 z-20 flex justify-center">
          <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-medium tracking-wide"
            style={{ background:'rgba(0,0,0,.32)', color:'rgba(255,255,255,.82)', backdropFilter:'blur(4px)' }}>
            <span style={{ color:style.accent }}>◆</span> made with Kinetic
          </div>
        </div>
      )}

      {mode === 'idle' && (
        <div className="absolute top-3 left-3 z-20 flex items-center gap-1.5 px-2 py-1 rounded-full text-[10px] font-medium"
          style={{ background:'rgba(0,0,0,.28)', color:'rgba(255,255,255,.8)', backdropFilter:'blur(4px)' }}>
          <span className="w-1.5 h-1.5 rounded-full" style={{ background:style.accent, animation:'kpulse 1.6s infinite' }}/> live
        </div>
      )}
    </div>
  );
}

function ReelPreview({ mode='idle', style, scenes, renderPct=0, controls=false, framed=true, videoSrc=null }) {
  const SC = scenes && scenes.length ? scenes : window.K.SCENES;
  const REEL_MS = SC.reduce((a,s)=>a+s.dur,0);
  const [scene, setScene] = useState(0);
  const [loop, setLoop] = useState(0);
  const [pct, setPct] = useState(0);
  const [playing, setPlaying] = useState(true);
  const playRef = useRef(0);
  const live = mode === 'idle' || mode === 'render' || mode === 'done';

  useEffect(() => {
    if (!playing || !live) return;
    let raf, last = performance.now();
    const step = (now) => {
      const dt = Math.min(now-last,60); last = now; playRef.current += dt;
      if (playRef.current >= REEL_MS) { playRef.current -= REEL_MS; setLoop(l=>l+1); }
      let acc=0, si=0;
      for (let i=0;i<SC.length;i++){ if (playRef.current>=acc && playRef.current<acc+SC[i].dur){ si=i; break; } acc+=SC[i].dur; }
      setScene(p=>p===si?p:si); setPct(playRef.current/REEL_MS);
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [playing, live, REEL_MS, SC.length]);

  const seek = useCallback((clientX, el) => {
    const rect = el.getBoundingClientRect();
    const p = Math.max(0, Math.min(1, (clientX-rect.left)/rect.width));
    playRef.current = p*REEL_MS; setPct(p);
    let acc=0, si=0;
    for (let i=0;i<SC.length;i++){ if (playRef.current>=acc && playRef.current<acc+SC[i].dur){ si=i; break; } acc+=SC[i].dur; }
    setScene(si);
  }, [REEL_MS, SC.length]);

  const dragging = useRef(false);
  const onTrackDown = (e) => { dragging.current=true; setPlaying(false); seek(e.clientX, e.currentTarget);
    const move = (ev)=>dragging.current&&seek(ev.clientX,e.currentTarget);
    const up = ()=>{ dragging.current=false; window.removeEventListener('pointermove',move); window.removeEventListener('pointerup',up); };
    window.addEventListener('pointermove',move); window.addEventListener('pointerup',up);
  };
  const fmt = (p)=>`0:0${Math.floor((p*REEL_MS)/1000)}`.slice(-3);
  const totalLabel = `0:0${Math.round(REEL_MS/1000)}`.slice(-3);

  // when the real rendered MP4 is available (result view), play it directly
  const realVideo = mode==='done' && !!videoSrc;
  const stage = realVideo
    ? <div className="relative w-full overflow-hidden rounded-[18px] bg-black" style={{ aspectRatio:'9 / 16' }}>
        <video key={videoSrc} src={videoSrc} autoPlay loop muted playsInline controls className="w-full h-full object-cover" onLoadedData={e=>{ try{ e.currentTarget.play(); }catch{} }}/>
      </div>
    : <ReelStage mode={mode} style={style} scenes={SC} scene={scene} loop={loop} renderPct={renderPct} />;

  return (
    <div className="w-full flex flex-col items-center gap-3 select-none">
      {framed ? (
        <div className="relative w-full rounded-[24px] p-[6px] bg-gradient-to-b from-[#32323c] to-[#0E0E14] shadow-[0_30px_80px_-22px_rgba(0,0,0,.9)] ring-1 ring-white/[0.06]">
          {realVideo ? stage : (
          <button onClick={()=>controls && setPlaying(p=>!p)} className={`relative w-full block ${controls?'group':''}`}>
            {stage}
            {mode==='done' && controls && (
              <span className="absolute inset-0 z-10 grid place-items-center">
                <span className="opacity-0 group-active:opacity-100 transition-opacity w-14 h-14 rounded-full grid place-items-center" style={{ background:'rgba(0,0,0,.4)' }}>
                  {playing ? <window.Icon.Pause size={22}/> : <window.Icon.Play size={22}/>}
                </span>
              </span>
            )}
          </button>
          )}
        </div>
      ) : stage}

      {controls && mode==='done' && !realVideo && (
        <div className="w-full flex items-center gap-3 px-1">
          <button onClick={()=>setPlaying(p=>!p)} className="w-9 h-9 shrink-0 rounded-full grid place-items-center bg-hi hover:bg-[#26262f] border border-borders transition-colors">
            {playing ? <window.Icon.Pause size={15}/> : <window.Icon.Play size={14}/>}
          </button>
          <div className="text-[11px] font-mono tnum text-muted w-9">{fmt(pct)}</div>
          <div className="relative flex-1 h-6 flex items-center cursor-pointer group" onPointerDown={onTrackDown}>
            <div className="h-1 w-full rounded-full bg-hi overflow-hidden"><div className="h-full rounded-full" style={{ width:`${pct*100}%`, background:'#FFE600' }}/></div>
            <div className="absolute w-3 h-3 rounded-full bg-white shadow -ml-1.5 opacity-0 group-hover:opacity-100 transition-opacity" style={{ left:`${pct*100}%` }}/>
          </div>
          <div className="text-[11px] font-mono tnum text-faint w-9 text-right">{totalLabel}</div>
        </div>
      )}
    </div>
  );
}

window.ReelPreview = ReelPreview;
