// Screen: Distillation progress — 6 stages streaming
const STAGES = [
  { id:1, title:'Align', sub:'transcript ↔ actions', desc:'Deterministic merge of word timestamps with Playwright trace events.', ai:false, ms:1200 },
  { id:2, title:'Segment', sub:'candidate steps', desc:'Heuristic boundaries: narration pauses, navigation, form submits, idle gaps.', ai:false, ms:1800 },
  { id:3, title:'Match', sub:'directory lookup', desc:'Embedding search + LLM confirm against existing steps. Reuse where possible.', ai:true, ms:3200 },
  { id:4, title:'Propose', sub:'new steps', desc:'LLM generates description, implementation, verifications for unmatched candidates.', ai:true, ms:5400 },
  { id:5, title:'Compose', sub:'test document', desc:'Clean prose narrative, step refs resolved, intent labels assigned.', ai:true, ms:3800 },
  { id:6, title:'Ready', sub:'for your review', desc:'Three-way linked editor: transcript, timeline, test document.', ai:false, ms:800 },
];

const STREAM_FINDS = [
  { at:0.3, kind:'match', text:'Matched "login-as-role@v3" · 94% confidence', icon: '✓' },
  { at:0.35, kind:'new', text:'New step candidate: "open fixture panel"', icon:'＋' },
  { at:0.55, kind:'new', text:'New step candidate: "assign squad number"', icon:'＋' },
  { at:0.62, kind:'match', text:'Matched "confirm submission@v2" · 87%', icon:'✓' },
  { at:0.75, kind:'infer', text:'Inferred verification: "homologation receipt visible"', icon:'⚡' },
  { at:0.82, kind:'infer', text:'Inferred verification: "18 players in roster"', icon:'⚡' },
  { at:0.92, kind:'done', text:'Draft test composed · 6 steps · 4 verifications', icon:'◆' },
];

function ScreenDistilling({ onDone, onBack }) {
  const [t, setT] = useState(0); // 0..1 progress
  const totalMs = STAGES.reduce((s,x) => s + x.ms, 0);

  useEffect(() => {
    const start = Date.now();
    const id = setInterval(() => {
      const p = Math.min(1, (Date.now() - start) / totalMs);
      setT(p);
      if (p >= 1) clearInterval(id);
    }, 60);
    return () => clearInterval(id);
  }, []);

  // Per-stage state
  const stageState = useMemo(() => {
    let acc = 0;
    return STAGES.map(s => {
      const start = acc / totalMs;
      const end = (acc + s.ms) / totalMs;
      acc += s.ms;
      let state = 'idle';
      let pct = 0;
      if (t > end) { state = 'done'; pct = 1; }
      else if (t > start) { state = 'active'; pct = (t - start) / (end - start); }
      return { ...s, state, pct, start, end };
    });
  }, [t]);

  const visibleFinds = STREAM_FINDS.filter(f => t >= f.at);

  return (
    <>
      <Crumb path={[{label:'Isyfoot workspace', onClick:onBack}, {label:'Tests', onClick:onBack}, {label:'Submit match-sheet · J14'}, {label:'Distilling'}]}
        right={<><span>Pipeline · active</span><span className="ft-mono">{Math.round(t*100)}%</span></>}/>
      <div className="ft-scroll">
        <div className="ft-screen ft-fadein" style={{maxWidth:1100}}>
          <div className="ft-pagehead">
            <div className="kicker">Distilling · 1m 24s recording</div>
            <h1>Six stages. Each one narrows the input for the next.</h1>
            <p>You don't need to watch. We'll open the review when it's ready — or you can peek at intermediate results as they stream in.</p>
          </div>

          <div style={{display:'grid', gridTemplateColumns:'1.3fr 1fr', gap:20}}>
            {/* Stages column */}
            <div style={{display:'flex', flexDirection:'column', gap:8}}>
              {stageState.map((s, i) => (
                <div key={s.id} style={{
                  display:'flex', gap:14, padding:'14px 16px',
                  background: s.state === 'active' ? 'var(--accent-dim)' : 'var(--surface)',
                  border: '1px solid',
                  borderColor: s.state === 'active' ? 'var(--accent)' : 'var(--border)',
                  borderRadius:10,
                  transition:'all 300ms var(--motion-ease-organic)',
                  boxShadow: s.state === 'active' ? 'var(--glow-primary)' : 'none',
                }}>
                  <div style={{flexShrink:0, width:28, height:28, borderRadius:'50%', border:'1px solid', borderColor: s.state==='idle' ? 'var(--border)' : 'var(--accent)', display:'grid', placeItems:'center', background: s.state==='done' ? 'var(--accent)' : 'transparent', color: s.state==='done' ? 'var(--bg)' : 'var(--accent)', fontFamily:'var(--mono)', fontSize:11, position:'relative'}}>
                    {s.state === 'done' ? <IconCheck size={12}/> : s.id}
                    {s.state === 'active' && (
                      <svg style={{position:'absolute', inset:-4}} width="36" height="36" viewBox="0 0 36 36">
                        <circle cx="18" cy="18" r="15" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray={`${s.pct * 94} 100`} transform="rotate(-90 18 18)" opacity="0.8"/>
                      </svg>
                    )}
                  </div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{display:'flex', alignItems:'baseline', gap:10}}>
                      <span style={{fontFamily:'var(--sans)', fontSize:14, fontWeight:500, color: s.state==='idle' ? 'var(--text-muted)' : 'var(--text-primary)', letterSpacing:'-0.01em'}}>{s.title}</span>
                      <span className="ft-mono" style={{fontSize:10, letterSpacing:'0.12em', color:'var(--text-muted)', textTransform:'uppercase'}}>{s.sub}</span>
                      <span style={{marginLeft:'auto', display:'flex', gap:6, alignItems:'center'}}>
                        {s.ai
                          ? <span className="ft-tag ft-tag--accent ft-mono" style={{fontSize:8, padding:'2px 8px'}}>LLM</span>
                          : <span className="ft-tag ft-tag--muted ft-mono" style={{fontSize:8, padding:'2px 8px'}}>deterministic</span>}
                      </span>
                    </div>
                    <div style={{fontSize:12, color: s.state==='idle' ? 'var(--text-muted)' : 'var(--text-tertiary)', marginTop:3, lineHeight:1.5}}>{s.desc}</div>
                    {s.state === 'active' && (
                      <div style={{height:2, background:'var(--border)', borderRadius:2, marginTop:10, overflow:'hidden'}}>
                        <div style={{height:'100%', background:'var(--accent)', width: `${s.pct*100}%`, transition:'width 120ms linear', boxShadow:'0 0 6px var(--accent-glow)'}}/>
                      </div>
                    )}
                  </div>
                </div>
              ))}

              {t >= 1 && (
                <button className="ft-btn ft-btn--primary ft-btn--lg ft-fadein" onClick={onDone} style={{marginTop:8, alignSelf:'flex-start'}}>
                  Open review <IconChevron size={12}/>
                </button>
              )}
            </div>

            {/* Stream column */}
            <div>
              <div className="ft-panel" style={{padding:'16px 16px 12px'}}>
                <div className="ft-panel-hd" style={{marginBottom:12}}>
                  <h3 style={{fontSize:13}}>Streaming results</h3>
                  <span className="ft-tag ft-tag--live ft-mono" style={{fontSize:9}}>live</span>
                </div>
                <div style={{display:'flex', flexDirection:'column', gap:8, minHeight:300}}>
                  {visibleFinds.length === 0 && (
                    <div className="ft-mono" style={{fontSize:11, color:'var(--text-muted)', padding:'20px 0', textAlign:'center', letterSpacing:'0.08em'}}>
                      WAITING FOR FIRST RESULT…
                    </div>
                  )}
                  {visibleFinds.map((f,i) => (
                    <div key={i} className="ft-fadein" style={{display:'flex', gap:10, padding:'10px 12px', background:'var(--bg2)', border:'1px solid var(--border)', borderRadius:8, alignItems:'flex-start'}}>
                      <span style={{fontFamily:'var(--mono)', fontSize:12, color: f.kind==='match' ? 'var(--accent)' : f.kind==='new' ? 'var(--phen-glory)' : f.kind==='done' ? 'var(--accent)' : 'var(--text-secondary)', flexShrink:0, marginTop:1}}>{f.icon}</span>
                      <div style={{flex:1, minWidth:0}}>
                        <div className="ft-mono" style={{fontSize:9, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--text-muted)', marginBottom:2}}>{f.kind}</div>
                        <div style={{fontSize:12, color:'var(--text-secondary)', lineHeight:1.5}}>{f.text}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div style={{marginTop:12, padding:'12px 14px', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:10}}>
                <div className="ft-mono" style={{fontSize:9, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--text-muted)', marginBottom:8}}>Cost · this run</div>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
                  {[['Tokens in', (Math.round(t*18400)).toLocaleString()],['Tokens out', (Math.round(t*3120)).toLocaleString()],['LLM calls', Math.round(t*7)],['~USD', `$${(t*0.08).toFixed(3)}`]].map(([k,v]) => (
                    <div key={k}>
                      <div className="ft-mono" style={{fontSize:9, color:'var(--text-muted)', letterSpacing:'0.1em'}}>{k}</div>
                      <div className="ft-mono" style={{fontSize:13, color:'var(--text-secondary)', marginTop:1}}>{v}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

window.ScreenDistilling = ScreenDistilling;
