// =========================================
// AI CHAT AGENT — Auditcash sales/support assistant
// Powered by window.claude.complete (Claude Haiku)
// =========================================
const { useState: _cs, useEffect: _ce, useRef: _cr } = React;

const AGENT_SYSTEM_PT = `Você é a Lia, agente comercial do Auditcash. Sua missão é AJUDAR o seller a entender se o Auditcash resolve a dor dele e CONVENCÊ-LO a iniciar uma auditoria grátis. Seu tom é caloroso, brasileiro, direto, sem corporativês. Você fala como uma pessoa de São Paulo conversando no WhatsApp: frases curtas, parágrafos pequenos, emoji ocasional sem exagero.

REGRAS DURAS:
- NUNCA invente preços, números, prazos, parceiros ou funcionalidades fora do contexto abaixo.
- Se não souber, diga "deixa eu te conectar com um especialista — me passa um e-mail?"
- Foque em VENDER: cada resposta termina com uma micro-CTA (pergunta, próximo passo, "quer ver?").
- Se a pessoa der sinais de objeção (preço, ML, banco, segurança), responda com o BENEFÍCIO, não a feature.
- Use números do contexto pra criar urgência: "2,3% do GMV, R$ X/mês".
- Resposta MÁX 4 parágrafos curtos. Idealmente 2-3.

CONTEXTO DO PRODUTO:
- Auditcash é SaaS B2B brasileiro de conciliação financeira ponta-a-ponta para sellers de marketplace (R$ 200k a R$ 5M/mês de GMV).
- Detecta automaticamente: comissão cobrada a mais, frete inflado, payout sumido, estorno duplicado.
- Conecta via OAuth: Mercado Livre, Shopee, Amazon, Magalu, Americanas, Shein, Casas Bahia, VTEX, Olist, Carrefour.
- Open Finance regulamentado pelo BCB para cruzar com extrato bancário (Itaú, Bradesco, Santander, Nubank, BTG, BB, Caixa, Inter, C6).
- Em média recupera 1,8% a 2,3% do GMV. Já recuperou R$ 12M+ pra 400+ sellers.
- 78% de aprovação nas contestações. Resposta média dos canais em <72h.
- Setup em 8 minutos. Conexão leitura-only — nunca movimentamos dinheiro.

PREÇOS:
- Performance: 0,7% sobre o recuperado · mínimo R$ 297/mês (cobre custo operacional). Sem mensalidade fixa. (Recomendado)
- Growth fixo: R$ 997/mês (sellers R$ 500k–3M/mês). Para quem prefere previsibilidade.
- Enterprise: sob consulta (>R$ 3M/mês, multi-CNPJ, gerente dedicado).
- Sem fidelidade. 30 dias de garantia: se não achar nada, devolve 100%.

EMPRESA:
- Sediada em Fortaleza/CE. Fundada em 2026. Time enxuto, remote-first.
- LGPD-compliant, dados criptografados AES-256, TLS 1.3, MFA obrigatório, pentest semestral.

QUANDO USAR ÁUDIO:
- Se a pessoa parece em dúvida ou se a resposta é muito vendedora/emocional (caso de ROI, vantagem competitiva), termine sugerindo: "se quiser eu mando um áudio te explicando rapidão". O sistema sabe interpretar.

OBJETIVOS ESCALONADOS:
1. Coletar GMV mensal (mostra perda estimada)
2. Coletar e-mail/WhatsApp pra começar auditoria grátis
3. Agendar demo de 15 min

Nunca peça muito de uma vez. Vá conversando.`;

const AGENT_SYSTEM_EN = `You are Lia, an Auditcash sales agent. Your mission is to help the seller understand if Auditcash solves their pain and CONVINCE them to start a free audit. Tone: warm, direct, conversational — like a person chatting on WhatsApp. Short sentences, short paragraphs.

HARD RULES:
- Never invent prices, numbers, deadlines, partners, or features beyond the context.
- If you don't know: "let me connect you with a specialist — what's your email?"
- Focus on selling: end each reply with a micro-CTA.
- Address objections with BENEFITS, not features.
- Use context numbers to create urgency.
- Max 4 short paragraphs. Ideally 2-3.

PRODUCT:
- Auditcash is a Brazilian B2B SaaS for end-to-end financial reconciliation for marketplace sellers ($40k–$1M/mo GMV).
- Detects: overcharged commission, inflated shipping, missing payout, duplicated refunds.
- OAuth connects to: Mercado Livre, Shopee, Amazon, Magalu, Americanas, Shein, Casas Bahia, VTEX, Olist, Carrefour.
- Brazilian Open Finance (regulated by Central Bank) to cross-reference bank statements.
- Recovers 1.8%–2.3% of GMV on average. Recovered R$12M+ for 400+ sellers. 78% dispute approval rate. Avg channel response <72h.
- 8-min setup. Read-only access.

PRICING:
- Performance: 0.7% of recovered amount · min R$ 297/month (covers operational cost). No fixed monthly fee. (Recommended)
- Growth fixed: R$997/mo. R$500k–3M/mo GMV. Predictable.
- Enterprise: custom (>R$3M/mo).
- No lock-in. 30-day guarantee.

COMPANY: Fortaleza/Brazil. Founded 2026. LGPD-compliant. AES-256, TLS 1.3, MFA, semi-annual pentest.

VOICE: When the answer is emotional/persuasive (ROI, advantage), suggest "want me to send you a voice note explaining it?". The system handles audio.

GOALS:
1. Collect monthly GMV (show estimated loss)
2. Collect email/phone for free audit
3. Book a 15-min demo

Don't ask too much at once.`;

function LiaAvatar({ size = 36, talking = false, listening = false }) {
  return (
    <div className={`lia-avatar ${talking ? 'talking' : ''} ${listening ? 'listening' : ''}`} style={{width:size,height:size}}>
      <img
        src={(window.__resources && window.__resources.liaAvatar) || "public/lia-avatar.png"}
        alt="Lia"
        width={size}
        height={size}
        loading="lazy"
      />
      {(talking || listening) && (
        <span className={`lia-pulse-ring ${listening ? 'red' : ''}`}></span>
      )}
      <span className="lia-online-dot"></span>
    </div>
  );
}

window.LiaAvatar = LiaAvatar;

// =========================================
// Audio routing — match a response to a pre-rendered VibeVoice MP3
// =========================================
// Cada key tem 1 arquivo por lang: audio/lia-<key>-<lang>.mp3
// Match leve por keyword na resposta do agente. Se nada bater, cai pra
// Web Speech API (robótico, mas zero dep).
const VOICE_PATTERNS = {
  pricing:   /pre[çc]o|custa|mensalidade|paga(r)?|cobr[ao]|performance|0,?7%|0\.7%|20%|price|fee|cost|floor|piso|m[íi]nimo/i,
  security:  /seguro|seguran[çc]a|lgpd|dados|criptograf|leitura.?s[óo]|read.?only|security|encrypt/i,
  roi:       /recupera|recuper[áa]vel|gmv|retorno|de volta|back in your|recover|return/i,
  setup:     /setup|configur|instala|conect[ao]|oito minutos|8 min|eight minutes/i,
  guarantee: /garantia|devolve|refund|se n[ãa]o achar|guarantee|no questions|sem letra/i,
};

function matchAudioKey(text) {
  if (!text) return null;
  for (const [key, re] of Object.entries(VOICE_PATTERNS)) {
    if (re.test(text)) return key;
  }
  return null;
}

function audioSrcFor(key, lang) {
  if (!key) return null;
  return `audio/lia-${key}-${lang === 'en' ? 'en' : 'pt'}.mp3`;
}

window.__liaMatchAudioKey = matchAudioKey;

function VoiceBubble({ text, lang, audioKey, onDone }) {
  const [playing, setPlaying] = _cs(false);
  const [progress, setProgress] = _cs(0);
  const audioRef = _cr(null);
  const utterRef = _cr(null);

  const src = audioSrcFor(audioKey, lang);

  const stop = () => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
    if ('speechSynthesis' in window) speechSynthesis.cancel();
    setPlaying(false);
  };

  // Prefer VibeVoice MP3 if matched; fallback to browser TTS.
  const playFromFile = () => {
    const a = new Audio(src);
    audioRef.current = a;
    a.addEventListener('play', () => setPlaying(true));
    a.addEventListener('ended', () => { setPlaying(false); setProgress(100); onDone && onDone(); });
    a.addEventListener('error', () => { playFromSpeech(); });
    a.addEventListener('timeupdate', () => {
      if (a.duration > 0) setProgress((a.currentTime / a.duration) * 100);
    });
    a.play().catch(() => playFromSpeech());
  };

  const playFromSpeech = () => {
    if (!('speechSynthesis' in window)) { onDone && onDone(); return; }
    speechSynthesis.cancel();
    const u = new SpeechSynthesisUtterance(text);
    u.lang = lang === 'en' ? 'en-US' : 'pt-BR';
    u.rate = 1.0;
    u.pitch = 1.05;
    const voices = speechSynthesis.getVoices();
    const target = lang === 'en' ? 'en' : 'pt';
    const ranked = voices
      .filter(v => v.lang.toLowerCase().startsWith(target))
      .sort((a, b) => {
        const score = (v) => {
          let s = 0;
          if (/google|microsoft|apple|premium|enhanced|neural|natural/i.test(v.name)) s += 10;
          if (/female|fem|maria|luciana|joana|samantha|raquel|ines|francisca|camila/i.test(v.name)) s += 5;
          if (!v.localService) s += 3;
          return -s;
        };
        return score(a) - score(b);
      });
    if (ranked[0]) u.voice = ranked[0];
    u.onstart = () => setPlaying(true);
    u.onend = () => { setPlaying(false); setProgress(100); onDone && onDone(); };
    u.onerror = () => { setPlaying(false); onDone && onDone(); };
    let elapsed = 0;
    const dur = Math.max(2000, text.length * 65);
    const tick = setInterval(() => {
      if (!speechSynthesis.speaking) { clearInterval(tick); return; }
      elapsed += 100;
      setProgress(Math.min(100, (elapsed / dur) * 100));
    }, 100);
    utterRef.current = u;
    speechSynthesis.speak(u);
  };

  const play = () => (src ? playFromFile() : playFromSpeech());

  const bars = Array.from({length: 28}, (_, i) => 30 + Math.abs(Math.sin(i * 0.7) * 60 + Math.cos(i * 1.3) * 30));

  return (
    <div className="voice-bubble" data-source={src ? 'vibevoice' : 'browser-tts'}>
      <button className="voice-play" onClick={playing ? stop : play} aria-label={playing ? 'Pausar' : 'Reproduzir áudio'}>
        {playing
          ? <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
          : <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="6 4 20 12 6 20"/></svg>
        }
      </button>
      <div className="voice-wave">
        {bars.map((h, i) => (
          <span key={i} className={`voice-bar ${(i / bars.length * 100) <= progress ? 'past' : ''} ${playing ? 'playing' : ''}`} style={{height: h+'%'}}></span>
        ))}
      </div>
      <span className="voice-duration">0:{String(Math.max(2, Math.round(text.length/14))).padStart(2,'0')}</span>
    </div>
  );
}

// =========================================
// Voice input — record user speech via SpeechRecognition
// =========================================
function useVoiceInput(lang, onResult) {
  const [recording, setRecording] = _cs(false);
  const [supported, setSupported] = _cs(true);
  const recRef = _cr(null);

  const start = () => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) { setSupported(false); return; }
    const r = new SR();
    r.lang = lang === 'en' ? 'en-US' : 'pt-BR';
    r.continuous = false;
    r.interimResults = false;
    r.maxAlternatives = 1;
    r.onstart = () => setRecording(true);
    r.onresult = (e) => {
      const txt = e.results[0][0].transcript;
      onResult(txt);
    };
    r.onerror = () => setRecording(false);
    r.onend = () => setRecording(false);
    recRef.current = r;
    try { r.start(); } catch { setRecording(false); }
  };

  const stop = () => {
    try { recRef.current && recRef.current.stop(); } catch {}
    setRecording(false);
  };

  return { recording, supported, start, stop };
}

function ChatAgent() {
  const sys = useSystem();
  const lang = sys.lang;
  const [open, setOpen] = _cs(false);
  const [unread, setUnread] = _cs(true);
  const [msgs, setMsgs] = _cs(() => [
    lang === 'en'
      ? { role: 'assistant', text: 'Hey! 👋 I\'m Lia from Auditcash. Quick question: what\'s your monthly GMV across marketplaces? I\'ll show you how much is leaking right now.', audioKey: 'intro' }
      : { role: 'assistant', text: 'Opa! 👋 Sou a Lia, do Auditcash. Pergunta rápida: quanto você fatura por mês nos marketplaces? Eu te mostro quanto tá escapando agora.', audioKey: 'intro' }
  ]);
  const [input, setInput] = _cs('');
  const [loading, setLoading] = _cs(false);
  const [quickReplies, setQuickReplies] = _cs(
    lang === 'en'
      ? ['How much can I recover?', 'How secure is it?', 'Why not a spreadsheet?']
      : ['Quanto consigo recuperar?', 'É seguro pra meu negócio?', 'Por que não planilha?']
  );
  const listRef = _cr(null);
  const [isTalking, setIsTalking] = _cs(false);
  const voice = useVoiceInput(lang, (txt) => { setInput(txt); setTimeout(() => send(txt), 200); });

  _ce(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [msgs, loading]);

  _ce(() => {
    if (!open) return;
    setUnread(false);
  }, [open]);

  const send = async (text) => {
    const trimmed = text.trim();
    if (!trimmed || loading) return;
    const userMsg = { role: 'user', text: trimmed };
    const next = [...msgs, userMsg];
    setMsgs(next);
    setInput('');
    setLoading(true);
    setQuickReplies([]);

    try {
      const history = next.map(m => ({ role: m.role, content: m.text }));
      // System prompt fica fixo no servidor — passamos só `lang` pra escolha.
      const reply = await window.claude.complete({
        lang: lang,
        messages: history,
      });
      // Detect if model offered audio
      const wantsAudio = /áudio|audio|voice note|mando um audio|mando um áudio/i.test(reply) && Math.random() < 0.5;
      // Match reply to a pre-rendered VibeVoice MP3 (null = falls back to browser TTS)
      const audioKey = matchAudioKey(reply);
      setMsgs(m => [...m, { role: 'assistant', text: reply, audioHint: wantsAudio, audioKey }]);

      // Suggest 2-3 quick replies based on context (simple heuristic)
      if (next.length < 8) {
        setQuickReplies(
          lang === 'en'
            ? ['Schedule a demo', 'Send me to pricing', 'How long is setup?']
            : ['Agendar demo', 'Quero ver os preços', 'Quanto tempo de setup?']
        );
      }
    } catch (e) {
      setMsgs(m => [...m, { role: 'assistant', text: lang === 'en' ? 'Connection hiccup — try again in a sec?' : 'Tive um problema de conexão. Tenta de novo daqui a pouco?' }]);
    } finally {
      setLoading(false);
    }
  };

  const playAudio = (text) => {
    setMsgs(m => m.map(msg =>
      msg.text === text ? { ...msg, asVoice: true } : msg
    ));
  };

  return (
    <>
      {!open && (
        <button className="chat-trigger" onClick={() => setOpen(true)} aria-label={lang === 'en' ? 'Open chat' : 'Abrir chat'}>
          <LiaAvatar size={32}/>
          <div className="chat-trigger-text">
            <div className="chat-trigger-name">Lia</div>
            <div className="chat-trigger-sub">Online</div>
          </div>
          {unread && <span className="chat-trigger-badge">1</span>}
        </button>
      )}
      {open && (
        <div className="chat-panel" role="dialog" aria-label={lang === 'en' ? 'Chat with Lia' : 'Chat com Lia'}>
          <div className="chat-head">
            <div className="chat-head-left">
              <LiaAvatar size={32} talking={isTalking}/>
              <div>
                <div className="chat-head-name">Lia <span className="chat-head-tag">{lang === 'en' ? 'Sales' : 'Comercial'}</span></div>
                <div className="chat-head-sub">{lang === 'en' ? 'Auditcash · online now' : 'Auditcash · online agora'}</div>
              </div>
            </div>
            <button className="chat-close" onClick={() => setOpen(false)} aria-label={lang === 'en' ? 'Close' : 'Fechar'}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
            </button>
          </div>
          <div className="chat-list" ref={listRef}>
            {msgs.map((m, i) => (
              <div key={i} className={`chat-msg chat-msg-${m.role}`}>
                {m.role === 'assistant' && <LiaAvatar size={22}/>}
                <div className="chat-msg-body">
                  {m.asVoice
                    ? <VoiceBubble text={m.text} lang={lang} audioKey={m.audioKey}/>
                    : <div className="chat-msg-bubble">{m.text}</div>
                  }
                  {m.role === 'assistant' && !m.asVoice && (
                    <button className="chat-msg-audio" onClick={() => playAudio(m.text)} aria-label={lang === 'en' ? 'Listen as audio' : 'Ouvir como áudio'}>
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 12v3a1 1 0 0 0 1 1h3l3.5 3.5a1 1 0 0 0 1.5-.87V5.37a1 1 0 0 0-1.5-.87L7 8H4a1 1 0 0 0-1 1z"/><path d="M16 9a3 3 0 0 1 0 6"/></svg>
                      {lang === 'en' ? 'Listen' : 'Ouvir'}
                    </button>
                  )}
                </div>
              </div>
            ))}
            {loading && (
              <div className="chat-msg chat-msg-assistant">
                <LiaAvatar size={22} talking/>
                <div className="chat-msg-bubble chat-typing">
                  <span></span><span></span><span></span>
                </div>
              </div>
            )}
          </div>
          {quickReplies.length > 0 && (
            <div className="chat-quick">
              {quickReplies.map((q, i) => (
                <button key={i} className="chat-quick-chip" onClick={() => send(q)}>{q}</button>
              ))}
            </div>
          )}
          <form className="chat-input-row" onSubmit={(e) => { e.preventDefault(); send(input); }}>
            <input
              className="chat-input"
              placeholder={voice.recording ? (lang === 'en' ? 'Listening…' : 'Te ouvindo…') : (lang === 'en' ? 'Type a message…' : 'Escreva uma mensagem…')}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              aria-label={lang === 'en' ? 'Type a message' : 'Escreva uma mensagem'}
              disabled={loading || voice.recording}
            />
            {voice.supported && (
              <button
                type="button"
                className={`chat-mic ${voice.recording ? 'recording' : ''}`}
                onClick={voice.recording ? voice.stop : voice.start}
                disabled={loading}
                aria-label={voice.recording ? (lang === 'en' ? 'Stop' : 'Parar') : (lang === 'en' ? 'Voice message' : 'Mensagem de voz')}
                title={voice.recording ? (lang === 'en' ? 'Stop recording' : 'Parar gravação') : (lang === 'en' ? 'Send voice message' : 'Enviar mensagem de voz')}
              >
                {voice.recording
                  ? <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><rect x="7" y="7" width="10" height="10" rx="2"/></svg>
                  : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
                }
              </button>
            )}
            <button type="submit" className="chat-send" disabled={loading || !input.trim()} aria-label={lang === 'en' ? 'Send' : 'Enviar'}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
            </button>
          </form>
          <div className="chat-foot">{lang === 'en' ? 'AI · voice powered by VibeVoice (natural) with browser TTS fallback' : 'IA · voz natural via VibeVoice (fallback síntese do navegador)'}</div>
        </div>
      )}
    </>
  );
}

window.ChatAgent = ChatAgent;
