// Scripted demo of a WhatsApp conversation with Detetive Capi
const { useState, useRef, useEffect } = React;

/* ============ pre-loaded cases ============ */
const CASES = [
  {
    id: 'fralda',
    chip: '👶 Fralda Huggies',
    intro: 'Tô precisando de fralda da Huggies pra praia',
    followup: 'Vê aí o melhor preço, Capi 🙏',
    product: {
      title: 'Fralda Descartável Infantil Praia & Piscina Huggies Little',
      emoji: '👶',
      bg: '#7dd3fc',
      price: 'R$ 11,50',
      store: 'Mercado Livre',
      link: 'https://meli.la/1Dz42ba',
    },
  },
  {
    id: 'airfryer',
    chip: '🍟 Air Fryer Ninja',
    intro: 'Quero comprar uma air fryer Ninja AF150',
    followup: 'me avisa quando estiver com bom preço',
    product: {
      title: 'Fritadeira Sem Óleo Ninja Air Fryer AF150 5,5L',
      emoji: '🍟',
      bg: '#f59e0b',
      price: 'R$ 685,90',
      store: 'Amazon',
      link: 'https://amzn.to/promo-airfryer',
    },
  },
  {
    id: 'tenis',
    chip: '👟 Tênis Nike Pegasus',
    intro: 'Acompanha o tênis Nike Pegasus 41 pra mim',
    followup: 'tamanho 42, cor azul',
    product: {
      title: 'Tênis Nike Pegasus 41 Masculino · Azul',
      emoji: '👟',
      bg: '#60a5fa',
      price: 'R$ 519,90',
      store: 'Nike.com.br',
      link: 'https://nike.com.br/pegasus41',
    },
  },
];

const WA_REAL_LINK = "https://wa.me/5511936236342?text=Oi%20detetive%20Capi%21%20Quero%20investigar%20promos...";

function TypingDots() {
  return (
    <div className="msg bot typing">
      Capi tá digitando<span>.</span><span>.</span><span>.</span>
    </div>
  );
}

function ProductAlertMsg({ product }) {
  return (
    <div className="msg bot alert-product">
      <div className="alert-headline">🚨 <b>O faro da Detetive Capi não falha!</b></div>
      <div className="alert-product-card">
        <div className="alert-product-img" style={{background: product.bg || '#1a2625'}}>
          <span className="alert-emoji">{product.emoji}</span>
        </div>
        <div className="alert-product-info">
          <div className="alert-product-title">{product.title}</div>
          <div className="alert-product-price">
            Por <b>{product.price}</b>
            <span className="alert-product-tag">melhor preço no momento</span>
          </div>
          <div className="alert-product-store">🛒 Achado no <b>{product.store}</b></div>
          <a className="alert-product-link" href={product.link} target="_blank" rel="noopener">
            👉 ver oferta
          </a>
        </div>
      </div>
      <span className="time">{nowHM()}</span>
    </div>
  );
}

function KapiChat() {
  const [messages, setMessages] = useState([
    { role: 'bot', text: '🕵️‍♀️ Oi! Sou a Detetive Capi.', time: '09:42' },
    { role: 'bot', text: 'Escolhe um dos casos abaixo pra ver como eu trabalho 👇', time: '09:42' },
  ]);
  const [phase, setPhase] = useState('idle'); // idle | running | done
  const [typing, setTyping] = useState(false);
  const bodyRef = useRef(null);

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

  const runCase = async (caseId) => {
    const c = CASES.find(x => x.id === caseId);
    if (!c || phase === 'running') return;
    setPhase('running');

    // user message 1
    await sleep(250);
    setMessages(prev => [...prev, { role: 'user', text: c.intro, time: nowHM() }]);

    // capi typing → ack
    await sleep(900);
    setTyping(true);
    await sleep(1100);
    setTyping(false);
    setMessages(prev => [...prev, { role: 'bot', text: '🔎 Anotado! Já tô investigando esse caso...', time: nowHM() }]);

    // user follow-up
    await sleep(700);
    setMessages(prev => [...prev, { role: 'user', text: c.followup, time: nowHM() }]);

    // capi typing → status
    await sleep(700);
    setTyping(true);
    await sleep(1400);
    setTyping(false);
    setMessages(prev => [...prev, { role: 'bot', text: '🕵️‍♀️ Vigiando 24h. Te aviso assim que o preço cair.', time: nowHM() }]);

    // ... time skip
    await sleep(900);
    setMessages(prev => [...prev, { role: 'sys', text: '— 2 dias depois —', time: '' }]);

    // alert
    await sleep(700);
    setTyping(true);
    await sleep(1200);
    setTyping(false);
    setMessages(prev => [...prev, { role: 'alert', product: c.product, time: nowHM() }]);

    setPhase('done');
  };

  const reset = () => {
    setPhase('idle');
    setTyping(false);
    setMessages([
      { role: 'bot', text: '🕵️‍♀️ Pronto pra outro caso?', time: nowHM() },
      { role: 'bot', text: 'Escolhe um dos casos abaixo 👇', time: nowHM() },
    ]);
  };

  return (
    <div className="chat-card" role="region" aria-label="Conversa com Detetive Capi">
      <div className="chat-head">
        <div className="av">
          <img src="assets/capi-mascot-192.png" alt="" />
        </div>
        <div>
          <div className="name">Detetive Capi</div>
          <div className="status"><span className="dot"></span>online · em campo</div>
        </div>
      </div>

      <div className="chat-body" ref={bodyRef}>
        {messages.map((m, i) => {
          if (m.role === 'alert') return <ProductAlertMsg key={i} product={m.product} />;
          if (m.role === 'sys') return (
            <div key={i} className="msg sys">{m.text}</div>
          );
          return (
            <div key={i} className={`msg ${m.role}`}>
              {m.text}
              {m.time && <span className="time">{m.time}</span>}
            </div>
          );
        })}
        {typing && <TypingDots />}
      </div>

      {phase === 'idle' && (
        <div className="chat-suggest stacked">
          <div className="chat-suggest-label">escolha um caso pra simular:</div>
          {CASES.map(c => (
            <button key={c.id} className="case-chip" onClick={() => runCase(c.id)}>
              {c.chip}
            </button>
          ))}
        </div>
      )}

      {phase === 'done' && (
        <div className="chat-suggest stacked">
          <a className="case-chip primary" href={WA_REAL_LINK} target="_blank" rel="noopener">
            💬 Abrir caso real no Zap
          </a>
          <button className="case-chip ghost" onClick={reset}>↻ simular outro</button>
        </div>
      )}
    </div>
  );
}

function nowHM() {
  const d = new Date();
  return String(d.getHours()).padStart(2,'0') + ':' + String(d.getMinutes()).padStart(2,'0');
}
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

window.KapiChat = KapiChat;
