// Chat (secondary surface) — LINE-style mobile, rendered inside a phone frame in the dashboard
function ChatView({ demoKey }) {
  const product = DEMO_PRODUCTS[demoKey];
  const [messages, setMessages] = useState([]);
  const [phase, setPhase] = useState(0);
  const scrollRef = useRef(null);

  useEffect(() => {
    setMessages([]);
    setPhase(0);
  }, [demoKey]);

  const script = useMemo(() => ([
    { who: 'bot', t: "Hi 👋 I'm the Kineteq pricing agent. Paste a product name, brand or SKU (EN / TH / ZH all fine)." },
    { who: 'me',  t: product.query },
    { who: 'bot', t: `Got it. Running pre-flight (~฿1) to disambiguate…`, mono: true },
    { who: 'bot', kind: 'candidates', product },
    { who: 'me',  t: `Use #1 — ${product.candidates[0].name}` },
    { who: 'bot', t: `Deep research dispatched. 6 sources in parallel. Budget ~฿40, ETA ~42s.`, mono: true },
    { who: 'bot', kind: 'progress' },
    { who: 'bot', kind: 'result', product },
  ]), [demoKey]);

  useEffect(() => {
    if (phase >= script.length) return;
    const delay = script[phase].who === 'me' ? 1100 : 900;
    const t = setTimeout(() => {
      setMessages(m => [...m, script[phase]]);
      setPhase(p => p + 1);
    }, delay);
    return () => clearTimeout(t);
  }, [phase, script]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <Chip tone="red">SURFACE · CHAT</Chip>
        <Label>LINE / MOBILE · SECONDARY</Label>
        <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
          same backend, thinner UI — for buyers walking a convention floor
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '360px 1fr', gap: 20, alignItems: 'start' }}>
        {/* Phone frame */}
        <div className="brut" style={{ padding: 12, background: 'var(--paper-2)' }}>
          <div style={{
            border: '4px solid var(--ink)', background: 'var(--paper)',
            height: 640, display: 'flex', flexDirection: 'column', overflow: 'hidden',
          }}>
            {/* Status bar */}
            <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '4px 10px', display: 'flex', justifyContent: 'space-between', fontFamily: 'JetBrains Mono, monospace', fontSize: 10 }}>
              <span>9:41</span><span>Kineteq Pricing Bot</span><span>■■■</span>
            </div>
            {/* Header */}
            <div style={{ padding: '10px 12px', borderBottom: '3px solid var(--ink)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 28, height: 28, background: 'var(--red)', border: '2px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 13 }}>K</div>
              <div>
                <div style={{ fontWeight: 800, fontSize: 13 }}>Kineteq Agent</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>online · ~฿40/query</div>
              </div>
              <Chip tone="green" style={{ marginLeft: 'auto' }}>LIVE</Chip>
            </div>

            <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 10, background: 'var(--paper-2)' }}>
              {messages.map((m, i) => (
                <ChatBubble key={i} m={m} />
              ))}
              {phase < script.length && <div style={{ display: 'flex', gap: 4, marginLeft: 6 }}>
                <Dot/><Dot delay={0.2}/><Dot delay={0.4}/>
              </div>}
            </div>

            <div style={{ borderTop: '3px solid var(--ink)', padding: 8, display: 'flex', gap: 6, background: 'var(--paper)' }}>
              <input className="input" style={{ padding: '8px 10px', fontSize: 12 }} placeholder="Type a product…" disabled />
              <button className="btn btn-primary btn-sm">SEND</button>
            </div>
          </div>
        </div>

        {/* Right side — context / callout */}
        <div>
          <div className="brut" style={{ padding: 16 }}>
            <Label>WHY A CHAT SURFACE?</Label>
            <div className="big-num" style={{ fontSize: 22, marginTop: 6 }}>Convention-floor reality</div>
            <div style={{ fontSize: 13, marginTop: 8, lineHeight: 1.55 }}>
              At a Chinese trade convention, the buyer has a phone in one hand and a supplier's brochure in the other.
              The chat surface is a LINE bot: same Resolve → Disambiguate → Research → Synthesize pipeline,
              but rendered as messages and an interactive candidate card.
            </div>
            <hr className="divider-dashed" style={{ margin: '14px 0' }} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12 }} className="mono">
              <div style={{ padding: 8, border: '2px solid var(--ink)', background: 'var(--paper-2)' }}>
                <div className="label">SHARED</div>
                <div>• Odoo MCP resolve</div>
                <div>• Same candidate pre-flight</div>
                <div>• Same 6-source research</div>
                <div>• Same Sonnet synthesis</div>
                <div>• Same persist rules</div>
              </div>
              <div style={{ padding: 8, border: '2px solid var(--ink)', background: 'var(--paper-2)' }}>
                <div className="label">CHAT-ONLY</div>
                <div>• Candidate carousel</div>
                <div>• Shorter result card</div>
                <div>• "Send to reviewer" quick action</div>
                <div>• LINE push on ready</div>
              </div>
            </div>
          </div>

          <div className="brut on-bright" style={{ padding: 14, marginTop: 12, background: 'var(--yellow)' }}>
            <Label>NOTE</Label>
            <div style={{ marginTop: 6, fontSize: 13 }}>
              Chat result card always surfaces <b>confidence</b> first. A 42% answer still ships — with reasoning, not silence.
              "No TH comps — first-mover, investigate manually" is a valid and useful reply.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ChatBubble({ m }) {
  const isMe = m.who === 'me';
  const wrap = {
    display: 'flex',
    justifyContent: isMe ? 'flex-end' : 'flex-start',
    margin: '6px 0',
  };
  const bubble = {
    maxWidth: '82%',
    padding: '8px 10px',
    border: '2px solid var(--ink)',
    background: isMe ? 'var(--yellow)' : 'var(--paper)',
    boxShadow: '3px 3px 0 var(--ink)',
    fontSize: 12,
    lineHeight: 1.4,
    fontFamily: m.mono ? 'JetBrains Mono, monospace' : 'inherit',
  };

  if (m.kind === 'candidates') {
    return (
      <div style={wrap}>
        <div style={{ ...bubble, padding: 8, width: '92%' }}>
          <div className="label" style={{ marginBottom: 6 }}>3 CANDIDATES</div>
          {m.product.candidates.map((c, i) => (
            <div key={i} style={{ padding: 6, border: '2px solid var(--ink)', marginBottom: 4, background: i === 0 ? 'var(--yellow)' : 'var(--paper-2)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 12 }}>
                <span>#{i+1} · {c.name.slice(0, 28)}{c.name.length > 28 ? '…' : ''}</span>
                <span className="mono">{(c.match*100).toFixed(0)}%</span>
              </div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{c.variant}</div>
            </div>
          ))}
          <div className="mono" style={{ fontSize: 10, marginTop: 4 }}>Reply with #1, #2, or #3 →</div>
        </div>
      </div>
    );
  }
  if (m.kind === 'progress') {
    return (
      <div style={wrap}>
        <div style={{ ...bubble, padding: 8, width: '86%' }}>
          <div className="label" style={{ marginBottom: 6 }}>RESEARCHING · 6/6</div>
          {['Shopee','Lazada','TikTok','1688','Alibaba','Priceza'].map((s,i)=>(
            <div key={s} style={{ display: 'flex', alignItems:'center', gap: 6, fontSize: 11, margin: '2px 0' }} className="mono">
              <span style={{ width: 8, height: 8, background: 'var(--green)', border: '1px solid var(--ink)' }}></span>
              {s}
              <span style={{ marginLeft: 'auto', color: 'var(--muted)' }}>done</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (m.kind === 'result') {
    const p = m.product;
    const auto = p.confidence.overall >= 0.75;
    return (
      <div style={wrap}>
        <div style={{ ...bubble, padding: 10, width: '92%' }}>
          <div className="label">RECOMMENDATION</div>
          <div className="big-num" style={{ fontSize: 20, marginTop: 4 }}>฿{p.recommended[0]}–{p.recommended[1]}</div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{p.sku} · landed ฿{p.landed.landed_thb}</div>
          <div style={{ marginTop: 6 }}>
            <ConfidenceViz data={p.confidence} />
          </div>
          <div style={{ marginTop: 8, display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {p.warnings.slice(0, 2).map((w,i)=>(<Chip key={i} tone="yellow">⚠ {w.slice(0,26)}{w.length>26?'…':''}</Chip>))}
          </div>
          <div style={{ marginTop: 8, display:'flex', gap: 6 }}>
            <button className="btn btn-sm btn-primary">{auto ? 'SEND TO REVIEWER' : 'LOG'}</button>
            <button className="btn btn-sm btn-ghost">FULL REPORT</button>
          </div>
        </div>
      </div>
    );
  }
  return <div style={wrap}><div style={bubble}>{m.t}</div></div>;
}

function Dot({ delay = 0 }) {
  return (
    <div className="blink" style={{
      width: 6, height: 6, background: 'var(--ink)', borderRadius: '50%',
      animationDelay: `${delay}s`,
    }} />
  );
}

window.ChatView = ChatView;
