/* LiveBoard + StateWidget. Stages: storyboard → hook → render. window.LiveBoard, StateWidget */
const fmtMs = (ms) => ms >= 1000 ? `${(ms/1000).toFixed(2)}s` : `${Math.round(ms)}ms`;

function StageNode({ status }) {
  const I = window.Icon;
  return (
    <div className="w-7 h-7 rounded-full grid place-items-center transition-all duration-300 z-10 shrink-0"
      style={{ background: status==='done'?'rgba(47,163,124,.14)':status==='active'?'#FFE600':'#16161C',
        border:`1.5px solid ${status==='done'?'#2FA37C':status==='active'?'#FFE600':'#2C2C36'}`,
        boxShadow: status==='active'?'0 0 0 5px rgba(255,230,0,.14)':'none' }}>
      {status==='done' ? <span className="text-success"><I.Check size={15}/></span>
        : status==='active' ? <span className="text-black"><I.Bolt size={14}/></span>
        : <span className="w-1.5 h-1.5 rounded-full bg-faint"/>}
    </div>
  );
}

function HookGauge({ value }) {
  const r=50, C=2*Math.PI*r, arc=C*0.75, f=Math.max(0,Math.min(1,value/100));
  const col = value>=86?'#2FA37C':value>=70?'#FFE600':'#8A8A95';
  return (
    <div className="relative w-[116px] h-[116px] sm:w-[128px] sm:h-[128px] shrink-0">
      <svg viewBox="0 0 120 120" className="w-full h-full -rotate-[225deg]">
        <circle cx="60" cy="60" r={r} fill="none" stroke="#23232B" strokeWidth="9" strokeLinecap="round" strokeDasharray={`${arc} ${C}`}/>
        <circle cx="60" cy="60" r={r} fill="none" stroke={col} strokeWidth="9" strokeLinecap="round" strokeDasharray={`${arc} ${C}`} strokeDashoffset={arc*(1-f)} style={{ transition:'stroke-dashoffset .2s linear, stroke .4s' }}/>
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <div className="font-heavy tnum leading-none" style={{ fontSize:36, color:col }}>{Math.round(value)}</div>
        <div className="text-[10px] text-faint font-mono mt-0.5">/100</div>
      </div>
    </div>
  );
}
window.HookGauge = HookGauge;

function VariantCard({ hook, selected, onClick, animDelay=0 }) {
  const I = window.Icon;
  const col = hook.score>=86?'#2FA37C':'#FFE600';
  return (
    <button onClick={onClick} className={`anim-slidein text-left w-full rounded-xl p-3 border transition-all ${selected?'border-accent bg-accent/[0.05] shadow-[0_0_0_1px_rgba(255,230,0,.3)]':'border-border bg-surface hover:border-borders'}`} style={{ animationDelay:`${animDelay}s` }}>
      <div className="flex items-start gap-3">
        <div className="shrink-0 w-10 h-10 rounded-lg grid place-items-center font-heavy text-[15px] tnum" style={{ background:`${col}1a`, color:col }}>{hook.score}</div>
        <div className="flex-1 min-w-0">
          <div className="flex items-start gap-1.5 flex-wrap">
            <span className="text-[13.5px] sm:text-[14px] font-semibold leading-snug">{hook.text}</span>
            {hook.best && <span className="shrink-0 text-[9px] font-mono uppercase tracking-wide px-1.5 py-0.5 rounded bg-success/15 text-success mt-0.5">Best</span>}
          </div>
          <div className="text-[12px] text-muted mt-1 leading-snug">{hook.reason}</div>
        </div>
        <div className={`shrink-0 w-5 h-5 rounded-full grid place-items-center border transition-all ${selected?'bg-accent border-accent':'border-borders'}`}>
          {selected && <I.Check size={13} className="text-black"/>}
        </div>
      </div>
    </button>
  );
}
window.VariantCard = VariantCard;

function StageBody({ stage, gen, K, style, scenes, onSelectHook }) {
  const I = window.Icon;
  if (stage.id === 'storyboard') {
    return (
      <div className="grid grid-cols-3 sm:grid-cols-5 gap-2">
        {scenes.slice(0, gen.scenesShown).map((sc,i)=>(
          <div key={sc.id} className="anim-popin rounded-lg overflow-hidden border border-border">
            <window.MiniTreatment scene={sc} style={style}/>
            <div className="text-[9px] font-mono text-faint text-center py-1 bg-surface truncate px-1">{K.TREATMENTS[sc.treatment].label}</div>
          </div>
        ))}
        {gen.scenesShown < scenes.length && (
          <div className="rounded-lg border border-dashed border-border grid place-items-center text-faint" style={{ aspectRatio:'9/13' }}>
            <I.Bolt size={14} className="animate-spin" style={{ animationDuration:'1.4s' }}/>
          </div>
        )}
      </div>
    );
  }
  if (stage.id === 'hook') {
    return (
      <div className="flex flex-col gap-4">
        <div className="flex items-center gap-3 sm:gap-4">
          <HookGauge value={gen.hookValue}/>
          <div className="flex-1 min-w-0">
            <div className="text-[11px] font-mono text-faint uppercase tracking-wide mb-1">Original hook</div>
            <div className="text-[14px] sm:text-[15px] font-semibold leading-snug">“{K.BASE_HOOK.text}”</div>
            <div className="text-[12px] text-muted mt-1.5">{gen.hooksShown?'3 sharper options — best auto-selected.':'Scoring the opener…'}</div>
          </div>
        </div>
        {gen.hooksShown && (
          <div className="flex flex-col gap-2">
            {K.HOOKS.map((h,i)=><VariantCard key={i} hook={h} selected={gen.selectedHook===i} onClick={()=>onSelectHook(i)} animDelay={i*0.1}/>)}
          </div>
        )}
      </div>
    );
  }
  if (stage.id === 'render') {
    return (
      <div className="flex flex-col gap-2">
        <div className="flex items-center justify-between text-[12px]">
          <span className="text-muted">Compositing · 9:16 · 30fps</span>
          <span className="font-mono tnum text-accent">{Math.round(gen.renderPct)}%</span>
        </div>
        <div className="h-2 rounded-full bg-hi overflow-hidden">
          <div className="h-full rounded-full transition-[width] duration-200" style={{ width:`${gen.renderPct}%`, background:'linear-gradient(90deg,#FFE600,#fff3)' }}/>
        </div>
      </div>
    );
  }
  return null;
}

function StageSummary({ stage, gen, K }) {
  let text='';
  if (stage.id==='storyboard') text = `${gen.scenesShown} scenes laid out`;
  else if (stage.id==='hook') text = `“${K.HOOKS[gen.selectedHook].text}” · ${K.HOOKS[gen.selectedHook].score}`;
  else if (stage.id==='render') text = `0:09 · 1080×1920 · 30fps`;
  return <div className="text-[12.5px] text-muted truncate">{text}</div>;
}

function LiveBoard({ K, gen, style, scenes, stages, onSelectHook }) {
  const I = window.Icon;
  const [open, setOpen] = React.useState(null);
  return (
    <div className="flex flex-col">
      {stages.map((stage,i)=>{
        const st = gen.status[stage.id];
        const isActive = st==='active', isDone = st==='done';
        const expanded = isActive || open===stage.id;
        const isLast = i===stages.length-1;
        return (
          <div key={stage.id} className="flex gap-3.5">
            <div className="relative flex flex-col items-center">
              <StageNode status={st}/>
              {!isLast && <div className="w-px flex-1 my-1" style={{ background: st==='done'?'#2FA37C55':'#23232B', transition:'background .4s' }}/>}
            </div>
            <div className={`flex-1 min-w-0 ${expanded?'pb-6':'pb-3'} transition-opacity duration-300 ${st==='pending'?'opacity-40':'opacity-100'}`}>
              <button onClick={()=>isDone && setOpen(o=>o===stage.id?null:stage.id)} className={`w-full flex items-center gap-2.5 min-h-[28px] text-left ${isDone?'cursor-pointer':'cursor-default'}`}>
                <stage.Icon size={16} className={`shrink-0 ${isActive?'text-accent':isDone?'text-text':'text-faint'}`}/>
                <span className={`text-[14.5px] sm:text-[15px] font-semibold whitespace-nowrap ${isActive?'text-accent':''}`}>{stage.label}</span>
                {isActive && <span className="w-1.5 h-1.5 rounded-full bg-accent shrink-0" style={{ animation:'kpulse 1.2s infinite' }}/>}
                <span className="ml-auto text-[11px] font-mono tnum text-faint shrink-0">{isDone?fmtMs(gen.ms[stage.id]):isActive?'running':''}</span>
                {isDone && <I.ChevronDown size={15} className={`text-faint shrink-0 transition-transform ${expanded?'rotate-180':''}`}/>}
              </button>
              {!expanded && !isDone && <div className="text-[12px] text-faint mt-0.5 ml-[26px]">{stage.sub}</div>}
              {!expanded && isDone && <div className="mt-1 ml-[26px]"><StageSummary stage={stage} gen={gen} K={K}/></div>}
              {expanded && (
                <>
                  <div className="text-[12px] text-faint mt-0.5 ml-[26px]">{stage.sub}</div>
                  <div className="mt-3 ml-[26px] anim-floatup"><StageBody stage={stage} gen={gen} K={K} style={style} scenes={scenes} onSelectHook={onSelectHook}/></div>
                </>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function StateWidget({ gen, stages, totalMs, compact }) {
  const I = window.Icon;
  const active = stages.find(s=>gen.status[s.id]==='active');
  const doneCount = stages.filter(s=>gen.status[s.id]==='done').length;
  const finished = doneCount===stages.length;
  const label = finished?'Done':active?active.label:'Starting';
  const detail = finished?'reel ready':active?.id==='render'?`${Math.round(gen.renderPct)}%`:`step ${Math.min(doneCount+1,stages.length)}/${stages.length}`;
  const fmtT = (ms)=>`${(ms/1000).toFixed(1)}s`;
  return (
    <div className={`shrink-0 flex items-center gap-2.5 rounded-full ${compact?'pl-2 pr-3 py-1.5':'pl-2.5 pr-4 py-2'} bg-raised/90 border border-borders backdrop-blur-md shadow-lg`}>
      <div className="relative w-6 h-6 rounded-full grid place-items-center shrink-0" style={{ background: finished?'rgba(47,163,124,.15)':'rgba(255,230,0,.12)' }}>
        {finished ? <I.Check size={13} className="text-success"/>
          : <><span className="absolute inset-0 rounded-full border-2 border-transparent border-t-accent" style={{ animation:'spin .9s linear infinite' }}/><span className="w-1.5 h-1.5 rounded-full bg-accent"/></>}
      </div>
      <div className="leading-tight whitespace-nowrap">
        <div className="text-[12.5px] font-semibold">{label}</div>
        <div className="text-[10px] text-muted font-mono tnum">{detail}</div>
      </div>
      <div className="w-px h-6 bg-borders mx-0.5"/>
      <div className="leading-tight text-right whitespace-nowrap">
        <div className="text-[12.5px] font-mono tnum font-semibold">{fmtT(totalMs)}</div>
        <div className="text-[9px] text-faint uppercase tracking-wide">elapsed</div>
      </div>
    </div>
  );
}

window.LiveBoard = LiveBoard;
window.StateWidget = StateWidget;
