// Step 3 — Live agentic research view
function StepResearch({ product, onComplete, onBack }) {
  const totalSteps = product.timeline.length;
  const [stepIdx, setStepIdx] = useState(0);
  const [playing, setPlaying] = useState(true);
  const [elapsed, setElapsed] = useState(0);

  useEffect(() => {
    if (!playing) return;
    const iv = setInterval(() => {
      setStepIdx(i => {
        if (i >= totalSteps - 1) { clearInterval(iv); return i; }
        return i + 1;
      });
      setElapsed(e => e + 1);
    }, 700);
    return () => clearInterval(iv);
  }, [playing, totalSteps]);

  const doneSources = {
    shopee:  stepIdx >= 4,
    lazada:  stepIdx >= 5,
    tiktok:  stepIdx >= 6,
    a1688:   stepIdx >= 7,
    alibaba: stepIdx >= 8,
    priceza: stepIdx >= 9,
  };
  const isComplete = stepIdx >= totalSteps - 1;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <Chip tone="red">STEP 03</Chip>
        <Label>AGENTIC MARKET RESEARCH · LIVE</Label>
        <span style={{ display:'inline-flex', alignItems:'center', gap: 6 }}>
          <span className="blink" style={{ width: 10, height: 10, background: 'var(--red)', borderRadius: '50%', display: 'inline-block' }}></span>
          <span className="mono" style={{ fontSize: 11, fontWeight: 700 }}>{isComplete ? 'COMPLETE' : 'LIVE'}</span>
        </span>
        <Chip>HAIKU-4.5 · PROMPT-CACHED</Chip>
        <Chip tone="ink">PLAYWRIGHT · STEALTH</Chip>
        <Chip tone="yellow">TH RESIDENTIAL PROXY</Chip>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <Btn size="sm" variant="ghost" onClick={() => setPlaying(p => !p)}>{playing ? '⏸ PAUSE' : '▶ RESUME'}</Btn>
          {isComplete && <Btn size="sm" variant="primary" onClick={onComplete}>VIEW RESULTS →</Btn>}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16 }}>
        {/* LEFT: agents grid */}
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            {SOURCES_META.map(s => {
              const done = doneSources[s.key];
              const hit = product.competitors.find(c => c.source.toLowerCase().includes(s.label.split(' ')[0].toLowerCase()))
                       || product.china.find(c => c.source.toLowerCase().includes(s.label.split('.')[0].toLowerCase()));
              const noMatch = done && s.key === 'tiktok' && product.id === 'mugen';
              return (
                <div key={s.key} className="brut" style={{
                  padding: 12, position: 'relative', overflow: 'hidden',
                  background: done ? 'var(--paper)' : 'var(--paper-2)',
                  minHeight: 120,
                }}>
                  {!done && <div className="scanline" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} />}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                    <div style={{ width: 10, height: 10, background: s.color, border: '2px solid var(--ink)' }} />
                    <div style={{ fontWeight: 800, fontSize: 13 }}>{s.label}</div>
                    {done
                      ? <Chip tone={noMatch ? 'red' : 'green'} className="mono" style={{ marginLeft: 'auto' }}>{noMatch ? 'NO MATCH' : 'DONE'}</Chip>
                      : <Chip tone="yellow" style={{ marginLeft: 'auto' }}>
                          <span className="blink">●</span> FETCH
                        </Chip>
                    }
                  </div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 8 }}>{s.role}</div>

                  {!done && (
                    <div style={{ height: 8, border: '2px solid var(--ink)', background: 'var(--paper)', position: 'relative', overflow: 'hidden' }}>
                      <div className="stripe-anim" style={{ position: 'absolute', inset: 0, color: s.color }} />
                    </div>
                  )}

                  {done && !noMatch && (
                    <div>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 6 }}>
                        {s.key === 'a1688' || s.key === 'alibaba'
                          ? product.china.filter(c => c.source.toLowerCase().includes(s.label.split('.')[0].toLowerCase())).slice(0, 2).map((c, i) => (
                              <div key={i} className="mono" style={{ fontSize: 11 }}>¥{c.price_cny}</div>
                          ))
                          : product.competitors.filter(c => c.source === s.label).slice(0, 2).map((c, i) => (
                              <div key={i} className="mono" style={{ fontSize: 11 }}>฿{c.price_thb?.toLocaleString()}</div>
                          ))
                        }
                      </div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>
                        {s.key === 'shopee' && `${product.competitors.filter(c=>c.source==='Shopee TH').length} listings · official + resellers`}
                        {s.key === 'lazada' && `${product.competitors.filter(c=>c.source==='Lazada TH').length} listings`}
                        {s.key === 'tiktok' && 'via Apify actor'}
                        {s.key === 'a1688' && `${product.china.filter(c=>c.source==='1688.com').length} suppliers · FOB locked`}
                        {s.key === 'alibaba' && `fallback · global export`}
                        {s.key === 'priceza' && `aggregated median`}
                      </div>
                    </div>
                  )}
                  {noMatch && (
                    <div className="mono" style={{ fontSize: 11, marginTop: 4 }}>
                      ⚠ Apify actor returned 0 results<br/>
                      <span style={{ color: 'var(--muted)' }}>warning logged to synthesis</span>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* Synthesis */}
          <div className="brut" style={{ marginTop: 14, padding: 14, background: stepIdx >= 10 ? 'var(--paper)' : 'var(--paper-2)', position: 'relative' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <Chip tone="ink">SONNET 4.5</Chip>
              <div style={{ fontWeight: 800, fontSize: 14 }}>SYNTHESIS &nbsp;·&nbsp; landed cost + band + confidence</div>
              {stepIdx >= 10 ? <Chip tone="green" style={{ marginLeft: 'auto' }}>DONE</Chip>
                : <Chip tone="yellow" style={{ marginLeft: 'auto' }}><span className="blink">●</span> WAITING</Chip>}
            </div>
            {stepIdx < 10 ? (
              <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
                Awaiting 6/6 source agents · aggregation + reasoning step will consume ~4.2k input / 1.1k output tokens
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                <div><Label>LANDED COST</Label><div className="big-num mono" style={{ fontSize: 22 }}>฿{product.landed.landed_thb}</div></div>
                <div><Label>COMP MEDIAN</Label><div className="big-num mono" style={{ fontSize: 22 }}>฿{Math.round(product.competitors.filter(c=>c.price_thb).reduce((a,b)=>a+b.price_thb,0)/product.competitors.filter(c=>c.price_thb).length)}</div></div>
                <div><Label>RECOMMEND</Label><div className="big-num mono" style={{ fontSize: 22 }}>฿{product.recommended[0]}–{product.recommended[1]}</div></div>
              </div>
            )}
          </div>
        </div>

        {/* RIGHT: timeline + cost meter */}
        <div>
          <div className="brut" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Label style={{ color: 'var(--paper)' }}>EXECUTION TRACE</Label>
              <span className="mono" style={{ fontSize: 11, marginLeft: 'auto' }}>
                {stepIdx + 1}/{totalSteps}
              </span>
            </div>
            <div style={{ maxHeight: 440, overflowY: 'auto' }}>
              {product.timeline.map((t, i) => {
                const active = i === stepIdx;
                const done = i < stepIdx;
                return (
                  <div key={i} className={active ? 'on-bright' : ''} style={{
                    display: 'grid', gridTemplateColumns: '60px 80px 1fr', gap: 8,
                    padding: '8px 12px', borderBottom: '2px solid var(--ink)',
                    background: active ? 'var(--yellow)' : 'var(--paper)',
                    opacity: !done && !active ? 0.35 : 1,
                  }}>
                    <span className="mono" style={{ fontSize: 10, fontWeight: 700 }}>{t.t}</span>
                    <span style={{ fontWeight: 800, fontSize: 11 }}>{t.step}</span>
                    <span className="mono" style={{ fontSize: 11 }}>{t.detail}</span>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="brut" style={{ marginTop: 12, padding: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Label>LIVE COST</Label>
              <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>target ≤ ฿40</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
              <div className="big-num mono" style={{ fontSize: 30 }}>฿{(product.cost.total_thb * Math.min(1, (stepIdx+1)/totalSteps)).toFixed(2)}</div>
              <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>/ ฿{product.cost.total_thb} budgeted</span>
            </div>
            <div style={{ height: 10, border: '3px solid var(--ink)', marginTop: 8, background: 'var(--paper)' }}>
              <div style={{ height: '100%', width: `${(product.cost.total_thb/40)*100}%`, background: 'var(--green)' }} />
            </div>
            <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4, fontSize: 11 }} className="mono">
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>haiku-4.5</span><span>฿{product.cost.haiku_thb}</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>sonnet-4.5</span><span>฿{product.cost.sonnet_thb}</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>proxy</span><span>฿{product.cost.proxy_thb}</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>apify</span><span>฿{product.cost.apify_thb}</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>searxng</span><span>฿{product.cost.search_thb}</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 800 }}><span>TOTAL</span><span>฿{product.cost.total_thb}</span></div>
            </div>
          </div>
        </div>
      </div>

      <div style={{ marginTop: 14, display: 'flex', gap: 10 }}>
        <Btn variant="ghost" onClick={onBack}>← BACK</Btn>
        <Btn variant="primary" onClick={onComplete} disabled={!isComplete}>VIEW RESULTS →</Btn>
        {!isComplete && <Btn variant="ghost" onClick={() => setStepIdx(totalSteps - 1)}>SKIP ANIMATION ⤵</Btn>}
      </div>
    </div>
  );
}

window.StepResearch = StepResearch;
