// Analyzing state — terminal-style processing log.
// No fake AI probability values: streams plausible log lines while the real
// backend works, then shows a heartbeat until livePayload arrives.
const { useState: useStateAna, useEffect: useEffectAna, useRef: useRefAna } = React;

function AnalyzingScreen({ payload, file, onDone, onCancel }){
  const [lines, setLines] = useStateAna([]);
  const [elapsed, setElapsed] = useStateAna(0);
  const [scriptDone, setScriptDone] = useStateAna(false);
  const logRef = useRefAna(null);

  // Elapsed clock
  useEffectAna(() => {
    const t0 = performance.now();
    const tick = setInterval(() => setElapsed((performance.now() - t0)/1000), 100);
    return () => clearInterval(tick);
  }, []);

  // Streaming log
  useEffectAna(() => {
    const sizeKB = (file.sizeBytes/1024).toFixed(1);
    const ext = (file.name.split('.').pop() || 'bin').toLowerCase();
    const script = [
      ['boot',  `truedetect v0.4.2 — engine cold-start`],
      ['boot',  `loading verdict tiers, layer weights, ensemble config`],
      ['recv',  `received: ${file.name}  ·  ${sizeKB} KB  ·  ${ext}`],
      ['parse', `detecting file type: ${ext}`],
      ['parse', `extracting raw text + metadata`],
      ['parse', `tokenizing sentences (spaCy en_core_web_sm)`],
      ['parse', `splitting paragraphs`],
      ['queue', `dispatching 10 layers in parallel (ThreadPoolExecutor)`],
      ['L1',    `perplexity: scoring sentences via gpt2 (sample cap=150)`],
      ['L2',    `burstiness: computing sentence-length Gini + std`],
      ['L3',    `stylometrics: ttr, ai-phrase density, hedging, passive ratio`],
      ['L4',    `semantic: paragraph embeddings via all-MiniLM-L6-v2`],
      ['L5',    `unicode: scanning for invisible chars + homoglyphs`],
      ['L6',    `metadata: scanning creator, producer, timestamps`],
      ['L7',    `fonts: extracting per-glyph font data`],
      ['L8',    `ensemble: chunking → roberta x2 inference`],
      ['L9',    `hallucination: extracting claims via remote LLM`],
      ['L10',   `revisions: parsing %%EOF count / docx track changes`],
      ['fuse',  `combining weighted scores → verdict tier + confidence`],
      ['synth', `synthesizing narrative + conflict notes`],
      ['pdf',   `rendering report → weasyprint → pdf`],
    ];

    let i = 0;
    const interval = setInterval(() => {
      if (i >= script.length){
        clearInterval(interval);
        setScriptDone(true);
        onDone();
        return;
      }
      const [tag, msg] = script[i++];
      setLines(L => [...L, { t: performance.now(), tag, msg }]);
    }, 280);
    return () => clearInterval(interval);
  }, [file.name, file.sizeBytes, onDone]);

  // Auto-scroll log to bottom
  useEffectAna(() => {
    if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
  }, [lines.length]);

  const tagColor = (tag) => {
    if (tag === 'boot' || tag === 'recv') return 'var(--text-muted)';
    if (tag === 'parse' || tag === 'queue') return 'var(--blue)';
    if (tag === 'fuse' || tag === 'synth') return 'var(--amber)';
    if (tag === 'pdf') return 'var(--green)';
    return 'var(--text)';   // L1..L10
  };

  return (
    <div style={{flex:1, display:'flex', flexDirection:'column', padding:'24px 32px', gap:14, overflow:'hidden', minHeight:0}}>
      {/* Header bar — file info */}
      <div className="surface" style={{padding:'14px 18px', display:'flex', alignItems:'center', gap:14, flexShrink:0}}>
        <div className="mono upper" style={{color:'var(--blue)', fontSize:11}}>analyzing</div>
        <div className="mono" style={{fontSize:13, color:'var(--text)'}}>{file.name}</div>
        <div className="mono" style={{color:'var(--text-dim)'}}>·</div>
        <div className="mono" style={{fontSize:11, color:'var(--text-muted)'}}>{fmtBytes(file.sizeBytes)}</div>
        <div style={{flex:1}}></div>
        <button className="btn" onClick={onCancel} style={{padding:'4px 10px', fontSize:11}}>× cancel</button>
      </div>

      {/* Terminal log */}
      <div className="surface" style={{flex:1, padding:'14px 18px', display:'flex', flexDirection:'column', minHeight:0}}>
        <div className="mono" style={{fontSize:10, color:'var(--text-dim)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:10, display:'flex', justifyContent:'space-between', flexShrink:0}}>
          <span>▸ engine log</span>
          <span>elapsed <span style={{color:'var(--text)'}}>{elapsed.toFixed(1)}s</span></span>
        </div>

        <div ref={logRef} style={{
          flex:1, overflow:'auto', minHeight:0,
          fontFamily:'var(--mono)', fontSize:12, lineHeight:1.55,
          background:'var(--bg)',
          border:'1px solid var(--border)',
          padding:'12px 14px',
        }}>
          {lines.map((l, idx) => {
            const t = ((l.t - lines[0].t)/1000).toFixed(2).padStart(6, '0');
            return (
              <div key={idx} className="fade-in" style={{display:'flex', gap:10, alignItems:'baseline'}}>
                <span style={{color:'var(--text-dim)', fontSize:11}}>[{t}s]</span>
                <span style={{color:tagColor(l.tag), minWidth:48, textTransform:'uppercase', letterSpacing:'0.06em', fontSize:11}}>{l.tag}</span>
                <span style={{color:'var(--text)', flex:1}}>{l.msg}</span>
              </div>
            );
          })}
          {scriptDone && (
            <div className="fade-in" style={{display:'flex', gap:10, alignItems:'baseline', marginTop:8}}>
              <span style={{color:'var(--text-dim)', fontSize:11}}>[{elapsed.toFixed(2)}s]</span>
              <span style={{color:'var(--amber)', minWidth:48, textTransform:'uppercase', letterSpacing:'0.06em', fontSize:11}}>wait</span>
              <span style={{color:'var(--text-muted)', flex:1}}>
                awaiting engine response<span className="cursor"></span>
              </span>
            </div>
          )}
        </div>

        <div className="mono" style={{display:'flex', justifyContent:'space-between', marginTop:10, fontSize:11, color:'var(--text-muted)', flexShrink:0}}>
          <span>worker: <span style={{color:'var(--text)'}}>uvicorn-1</span> · gpu: <span style={{color:'var(--text-dim)'}}>cpu</span></span>
          <span style={{color:'var(--text-dim)'}}>typical: 15–60s · large docs may take longer</span>
        </div>
      </div>
    </div>
  );
}

window.AnalyzingScreen = AnalyzingScreen;
