/* ============================================================
   ChatWidget.jsx — ARIA · Assistente AR
   Fluxo: captura de lead → confirmação → conversa com agente
   conectado ao n8n via webhook. Suporta anexos e áudio.
   ============================================================ */

/* ⚠️ SUBSTITUA pela sua URL real de webhook do n8n.
   Exemplo de produção: https://n8n.suaempresa.com.br/webhook/agente-ar
   O site envia um POST JSON para esta URL com o lead e cada mensagem,
   e usa a resposta (campo "reply" / "output" / "message") como fala do agente. */
const AR_WEBHOOK_URL = "https://SEU-N8N.exemplo.com/webhook/agente-ar";

async function arPostWebhook(payload) {
  try {
    const res = await fetch(AR_WEBHOOK_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error("status " + res.status);
    const data = await res.json().catch(() => ({}));
    return data.reply || data.output || data.message || data.text || null;
  } catch (e) {
    return null; // webhook fictício / offline → usa resposta de fallback
  }
}

const ChatWidget = () => {
  const [open, setOpen] = React.useState(false);
  const [stage, setStage] = React.useState("form"); // 'form' | 'chat'
  const [lead, setLead] = React.useState({ nome: "", empresa: "", whatsapp: "", email: "" });
  const [errors, setErrors] = React.useState({});
  const [msgs, setMsgs] = React.useState([]);
  const [draft, setDraft] = React.useState("");
  const [typing, setTyping] = React.useState(false);

  // audio
  const [recording, setRecording] = React.useState(false);
  const [recSecs, setRecSecs] = React.useState(0);
  const recRef = React.useRef(null);
  const chunksRef = React.useRef([]);
  const recTimer = React.useRef(null);

  const feedRef = React.useRef(null);
  const fileRef = React.useRef(null);

  React.useEffect(() => { if (feedRef.current) feedRef.current.scrollTop = feedRef.current.scrollHeight; }, [msgs, typing, open, stage]);
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const fallbackReplies = [
    "Perfeito. Posso qualificar seus leads, responder dúvidas e encaminhar oportunidades para sua equipe.",
    "Conseguimos integrar com WhatsApp, Instagram, site, CRM, Telegram e outros sistemas.",
    "Posso te mostrar como funciona uma automação aplicada ao seu caso. Qual canal você mais usa hoje?",
    "Ótimo! Vou registrar isso e um especialista da AR dá sequência com você.",
  ];
  const replyIdx = React.useRef(0);

  const pushAgent = async (userText) => {
    setTyping(true);
    const reply = await arPostWebhook({ tipo: "mensagem", lead, mensagem: userText, historico: msgs });
    const wait = reply ? 200 : 900; // simula latência quando offline
    setTimeout(() => {
      setTyping(false);
      const text = reply || fallbackReplies[replyIdx.current++ % fallbackReplies.length];
      setMsgs(m => [...m, { from: "agent", type: "text", text }]);
    }, wait);
  };

  const sendText = (text) => {
    const t = (text ?? draft).trim();
    if (!t) return;
    setMsgs(m => [...m, { from: "user", type: "text", text: t }]);
    setDraft("");
    pushAgent(t);
  };

  const validate = () => {
    const e = {};
    if (!lead.nome.trim()) e.nome = true;
    if (!lead.whatsapp.trim()) e.whatsapp = true;
    if (!lead.email.trim() || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(lead.email)) e.email = true;
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submitForm = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    arPostWebhook({ tipo: "lead", lead }); // registra o lead no n8n
    setStage("chat");
    const nome = lead.nome.split(" ")[0];
    setMsgs([
      { from: "system", type: "text", text: `Dados recebidos: ${lead.nome}${lead.empresa ? " · " + lead.empresa : ""} · ${lead.whatsapp} · ${lead.email}` },
      { from: "agent", type: "text", text: `Prazer, ${nome}! Recebi seus dados e já estamos conectados. Sou a ARIA, agente de IA da Agência AR. Como posso ajudar a sua empresa hoje?` },
    ]);
  };

  const onFile = (ev) => {
    const file = ev.target.files && ev.target.files[0];
    if (!file) return;
    const isImg = file.type.startsWith("image/");
    const url = isImg ? URL.createObjectURL(file) : null;
    setMsgs(m => [...m, { from: "user", type: "file", fileName: file.name, isImg, url, size: file.size }]);
    ev.target.value = "";
    arPostWebhook({ tipo: "anexo", lead, arquivo: file.name });
    pushAgent("[anexo] " + file.name);
  };

  const startRec = async () => {
    if (!navigator.mediaDevices || !window.MediaRecorder) {
      setMsgs(m => [...m, { from: "system", type: "text", text: "Gravação de áudio não suportada neste navegador." }]);
      return;
    }
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mr = new MediaRecorder(stream);
      chunksRef.current = [];
      mr.ondataavailable = e => e.data.size && chunksRef.current.push(e.data);
      mr.onstop = () => {
        const blob = new Blob(chunksRef.current, { type: "audio/webm" });
        const url = URL.createObjectURL(blob);
        setMsgs(m => [...m, { from: "user", type: "audio", url, secs: recSecs }]);
        stream.getTracks().forEach(t => t.stop());
        arPostWebhook({ tipo: "audio", lead });
        pushAgent("[áudio]");
      };
      mr.start();
      recRef.current = mr;
      setRecording(true);
      setRecSecs(0);
      recTimer.current = setInterval(() => setRecSecs(s => s + 1), 1000);
    } catch (e) {
      setMsgs(m => [...m, { from: "system", type: "text", text: "Permissão de microfone negada." }]);
    }
  };
  const stopRec = (save = true) => {
    clearInterval(recTimer.current);
    setRecording(false);
    if (recRef.current) {
      if (!save) recRef.current.onstop = () => recRef.current.stream && null;
      try { recRef.current.stop(); } catch (e) {}
    }
  };

  const downloadTranscript = () => {
    const lines = [
      "Conversa — Agência AR (ARIA)",
      "Data: " + new Date().toLocaleString("pt-BR"),
      "----------------------------------------",
      `Nome: ${lead.nome || "-"}`,
      `Empresa: ${lead.empresa || "-"}`,
      `WhatsApp: ${lead.whatsapp || "-"}`,
      `E-mail: ${lead.email || "-"}`,
      "----------------------------------------",
      "",
    ];
    msgs.forEach(m => {
      const who = m.from === "agent" ? "ARIA" : m.from === "user" ? (lead.nome || "Você") : "Sistema";
      let body = m.text;
      if (m.type === "file") body = "[anexo] " + m.fileName;
      if (m.type === "audio") body = "[áudio enviado]";
      lines.push(`${who}: ${body}`);
    });
    const blob = new Blob([lines.join("\n")], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = "conversa-agencia-ar.txt";
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  const fmt = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;

  const HeaderBtn = ({ icon, onClick, title }) => (
    <button onClick={onClick} title={title} aria-label={title} style={{
      width: 32, height: 32, borderRadius: 9, border: "1px solid rgba(255,255,255,0.16)",
      background: "rgba(255,255,255,0.06)", color: "rgba(255,255,255,0.9)", cursor: "pointer",
      display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
      transition: "background 140ms, border-color 140ms",
    }}
      onMouseEnter={e => { e.currentTarget.style.background = "rgba(255,255,255,0.14)"; }}
      onMouseLeave={e => { e.currentTarget.style.background = "rgba(255,255,255,0.06)"; }}>
      <i data-lucide={icon} style={{ width: 16, height: 16 }}></i>
    </button>
  );

  return (
    <React.Fragment>
      {!open && (
        <button onClick={() => setOpen(true)} aria-label="Abrir chat" className="ar-chat-fab" style={{
          position: "fixed", bottom: 24, right: 24, zIndex: 80,
          width: 64, height: 64, borderRadius: 999,
          background: "linear-gradient(135deg,#005EFF,#00D4FF)", border: "none", cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center", color: "#fff",
        }}>
          <i data-lucide="message-circle" style={{ width: 26, height: 26 }}></i>
          <span className="ar-online-dot" style={{ position: "absolute", top: -3, right: -3, width: 14, height: 14, borderRadius: 999, background: "#1FD17B", border: "2.5px solid #05070D" }} />
        </button>
      )}

      {open && (
        <div style={{
          position: "fixed", bottom: 24, right: 24, zIndex: 80,
          width: "min(384px, calc(100vw - 32px))", height: "min(600px, calc(100vh - 100px))",
          background: "linear-gradient(180deg, #0B1020 0%, #05070D 100%)",
          border: "1px solid rgba(0,212,255,0.20)", borderRadius: 24,
          display: "flex", flexDirection: "column",
          boxShadow: "0 40px 80px -20px rgba(0,0,0,0.7), 0 0 60px -20px rgba(0,94,255,0.4)",
          overflow: "hidden",
        }}>
          {/* Header */}
          <div style={{ background: "linear-gradient(135deg, rgba(0,94,255,0.38), rgba(0,212,255,0.20))", padding: "14px 14px", display: "flex", alignItems: "center", gap: 11, borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
            <div style={{ width: 40, height: 40, borderRadius: 999, background: "linear-gradient(135deg,#005EFF,#00D4FF)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 16px rgba(0,212,255,0.6)", flexShrink: 0 }}>
              <img src="/assets/logo-white.png" alt="AR" style={{ width: 24, height: 24 }} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: "var(--ar-font-title)", fontWeight: 700, fontSize: 15, color: "#fff" }}>ARIA · Assistente AR</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--ar-font-body)", fontSize: 11, color: "#1FD17B" }}>
                <span className="ar-pulse" style={{ width: 6, height: 6, borderRadius: 999, background: "#1FD17B" }} />
                online para ajudar sua empresa
              </div>
            </div>
            {stage === "chat" && <HeaderBtn icon="download" onClick={downloadTranscript} title="Baixar conversa" />}
            <HeaderBtn icon="x" onClick={() => setOpen(false)} title="Fechar chat" />
          </div>

          {/* LEAD FORM */}
          {stage === "form" && (
            <div style={{ flex: 1, overflowY: "auto", padding: "22px 18px" }}>
              <div style={{ fontFamily: "var(--ar-font-body)", fontSize: 13.5, lineHeight: 1.55, color: "var(--ar-text-muted)", marginBottom: 18 }}>
                Antes de começar, deixe seus dados. Assim a ARIA já te atende com contexto e nossa equipe consegue dar sequência.
              </div>
              <form onSubmit={submitForm} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <ChatField label="Nome" value={lead.nome} err={errors.nome} onChange={v => setLead({ ...lead, nome: v })} placeholder="Seu nome" />
                <ChatField label="Empresa" value={lead.empresa} onChange={v => setLead({ ...lead, empresa: v })} placeholder="Nome da empresa (opcional)" />
                <ChatField label="WhatsApp" value={lead.whatsapp} err={errors.whatsapp} onChange={v => setLead({ ...lead, whatsapp: v })} placeholder="(00) 00000-0000" />
                <ChatField label="E-mail" value={lead.email} err={errors.email} onChange={v => setLead({ ...lead, email: v })} placeholder="voce@empresa.com.br" type="email" />
                <button type="submit" style={{
                  marginTop: 6, padding: "13px 16px", borderRadius: 13, border: "none", cursor: "pointer",
                  background: "linear-gradient(135deg,#005EFF,#00D4FF)", color: "#fff",
                  fontFamily: "var(--ar-font-body)", fontWeight: 600, fontSize: 14.5,
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                  boxShadow: "0 0 24px rgba(0,94,255,0.35)",
                }}>
                  Iniciar conversa <i data-lucide="arrow-right" style={{ width: 16, height: 16 }}></i>
                </button>
                <div style={{ display: "flex", alignItems: "center", gap: 7, fontFamily: "var(--ar-font-body)", fontSize: 11, color: "var(--ar-text-dim)", justifyContent: "center" }}>
                  <i data-lucide="lock" style={{ width: 12, height: 12 }}></i> Seus dados são usados apenas para o atendimento.
                </div>
              </form>
            </div>
          )}

          {/* CHAT */}
          {stage === "chat" && (
            <React.Fragment>
              <div ref={feedRef} style={{ flex: 1, padding: "16px 14px", overflowY: "auto", display: "flex", flexDirection: "column", gap: 9, backgroundImage: "radial-gradient(rgba(255,255,255,0.022) 1px, transparent 1px)", backgroundSize: "16px 16px" }}>
                {msgs.map((m, i) => <ChatMessage key={i} m={m} />)}
                {typing && (
                  <div style={{ alignSelf: "flex-start", background: "var(--ar-bg-card)", border: "1px solid rgba(255,255,255,0.06)", borderRadius: "14px 14px 14px 4px", padding: "11px 14px", display: "flex", gap: 4 }}>
                    {[0, 1, 2].map(d => <span key={d} className="ar-typ" style={{ width: 6, height: 6, borderRadius: 999, background: "var(--ar-cyan)", animationDelay: `${d * 0.16}s` }} />)}
                  </div>
                )}
              </div>

              {/* Input bar */}
              {recording ? (
                <div style={{ padding: 12, borderTop: "1px solid rgba(255,255,255,0.06)", display: "flex", alignItems: "center", gap: 10 }}>
                  <button onClick={() => stopRec(false)} title="Cancelar" style={iconBtn("transparent", "var(--ar-text-muted)")}>
                    <i data-lucide="trash-2" style={{ width: 18, height: 18 }}></i>
                  </button>
                  <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 8, color: "#FF4D5E", fontFamily: "var(--ar-font-mono)", fontSize: 13 }}>
                    <span className="ar-rec" style={{ width: 9, height: 9, borderRadius: 999, background: "#FF4D5E" }} />
                    gravando · {fmt(recSecs)}
                  </div>
                  <button onClick={() => stopRec(true)} title="Enviar áudio" style={iconBtn("linear-gradient(135deg,#005EFF,#00D4FF)", "#fff")}>
                    <i data-lucide="check" style={{ width: 18, height: 18 }}></i>
                  </button>
                </div>
              ) : (
                <form onSubmit={(e) => { e.preventDefault(); sendText(); }} style={{ padding: 11, borderTop: "1px solid rgba(255,255,255,0.06)", display: "flex", gap: 7, alignItems: "center" }}>
                  <input ref={fileRef} type="file" accept="image/*,application/pdf,.doc,.docx,.xls,.xlsx,.txt" onChange={onFile} style={{ display: "none" }} />
                  <button type="button" onClick={() => fileRef.current && fileRef.current.click()} title="Anexar arquivo ou foto" style={iconBtn("var(--ar-bg-card)", "var(--ar-text-muted)")}>
                    <i data-lucide="paperclip" style={{ width: 18, height: 18 }}></i>
                  </button>
                  <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Escreva sua mensagem…" style={{
                    flex: 1, minWidth: 0, background: "var(--ar-bg-card)", border: "1px solid rgba(255,255,255,0.10)",
                    borderRadius: 12, padding: "11px 14px", fontFamily: "var(--ar-font-body)", fontSize: 14, color: "var(--ar-text-main)", outline: "none",
                  }} />
                  {draft.trim() ? (
                    <button type="submit" title="Enviar" style={iconBtn("linear-gradient(135deg,#005EFF,#00D4FF)", "#fff")}>
                      <i data-lucide="send" style={{ width: 18, height: 18 }}></i>
                    </button>
                  ) : (
                    <button type="button" onClick={startRec} title="Gravar áudio" style={iconBtn("linear-gradient(135deg,#005EFF,#00D4FF)", "#fff")}>
                      <i data-lucide="mic" style={{ width: 18, height: 18 }}></i>
                    </button>
                  )}
                </form>
              )}
            </React.Fragment>
          )}
        </div>
      )}

      <style>{`
        .ar-typ { display:inline-block; animation: arTyp 1s var(--ar-ease) infinite; }
        @keyframes arTyp { 0%,60%,100%{opacity:.3;transform:translateY(0);} 30%{opacity:1;transform:translateY(-3px);} }
        .ar-rec { animation: arRec 1s ease-in-out infinite; }
        @keyframes arRec { 0%,100%{opacity:1;} 50%{opacity:.3;} }

        /* Botão flutuante: batimento cardíaco duplo.
           !important sobrepõe o reduce-motion global (* { animation-duration: 0.001ms })
           porque é um elemento-chave que deve pulsar de propósito. */
        .ar-chat-fab {
          animation: arFabBeat 2.2s ease-in-out infinite !important;
          transition: box-shadow .25s;
        }
        @keyframes arFabBeat {
          0%   { transform: scale(1);    box-shadow: 0 12px 32px rgba(0,94,255,0.45), 0 0 0 6px rgba(0,212,255,0.14); }
          12%  { transform: scale(1.16); box-shadow: 0 18px 54px rgba(0,94,255,0.85), 0 0 0 9px rgba(0,212,255,0.24); }
          24%  { transform: scale(1);    box-shadow: 0 12px 32px rgba(0,94,255,0.45), 0 0 0 6px rgba(0,212,255,0.14); }
          38%  { transform: scale(1.09); box-shadow: 0 15px 46px rgba(0,94,255,0.64), 0 0 0 7px rgba(0,212,255,0.18); }
          52%  { transform: scale(1);    box-shadow: 0 12px 32px rgba(0,94,255,0.45), 0 0 0 6px rgba(0,212,255,0.14); }
          100% { transform: scale(1);    box-shadow: 0 12px 32px rgba(0,94,255,0.45), 0 0 0 6px rgba(0,212,255,0.14); }
        }

        /* Bolinha online: anel verde que expande e some (padrão ping) */
        .ar-online-dot::after {
          content: '';
          position: absolute;
          inset: -4px;
          border-radius: 50%;
          border: 2px solid #1FD17B;
          animation: arOnlinePing 1.8s ease-out infinite !important;
        }
        @keyframes arOnlinePing {
          0%   { transform: scale(0.6); opacity: 0.8; }
          100% { transform: scale(1.7); opacity: 0; }
        }
      `}</style>
    </React.Fragment>
  );
};

const iconBtn = (bg, color) => ({
  width: 42, height: 42, borderRadius: 12, border: "none", cursor: "pointer", flexShrink: 0,
  background: bg, color, display: "flex", alignItems: "center", justifyContent: "center",
});

const ChatField = ({ label, value, onChange, placeholder, err, type = "text" }) => {
  const [focus, setFocus] = React.useState(false);
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
      <span style={{ fontFamily: "var(--ar-font-body)", fontSize: 12, fontWeight: 500, color: err ? "#FF4D5E" : (focus ? "#00D4FF" : "var(--ar-text-muted)") }}>{label}</span>
      <input type={type} value={value} placeholder={placeholder}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        onChange={(e) => onChange(e.target.value)}
        style={{
          width: "100%", boxSizing: "border-box", background: "rgba(5,7,13,0.55)",
          border: `1px solid ${err ? "#FF4D5E" : (focus ? "#00D4FF" : "rgba(255,255,255,0.10)")}`,
          borderRadius: 11, padding: "11px 13px", fontFamily: "var(--ar-font-body)", fontSize: 14,
          color: "var(--ar-text-main)", outline: "none",
          boxShadow: focus ? "0 0 0 4px rgba(0,212,255,0.12)" : "none", transition: "all 140ms var(--ar-ease)",
        }} />
    </label>
  );
};

const ChatMessage = ({ m }) => {
  if (m.from === "system") {
    return (
      <div style={{ alignSelf: "center", maxWidth: "92%", textAlign: "center", background: "rgba(31,209,123,0.08)", border: "1px solid rgba(31,209,123,0.25)", borderRadius: 10, padding: "7px 12px", fontFamily: "var(--ar-font-body)", fontSize: 11.5, lineHeight: 1.45, color: "#9fe9c4", display: "flex", gap: 6, alignItems: "center" }}>
        <i data-lucide="check-circle-2" style={{ width: 13, height: 13, flexShrink: 0 }}></i>
        <span>{m.text}</span>
      </div>
    );
  }
  const agent = m.from === "agent";
  const base = {
    alignSelf: agent ? "flex-start" : "flex-end", maxWidth: "84%",
    background: agent ? "var(--ar-bg-card)" : "linear-gradient(135deg,#005EFF,#00D4FF)",
    border: agent ? "1px solid rgba(255,255,255,0.06)" : "none",
    color: agent ? "var(--ar-text-main)" : "#fff",
    borderRadius: agent ? "14px 14px 14px 4px" : "14px 14px 4px 14px",
    padding: "10px 13px", fontFamily: "var(--ar-font-body)", fontSize: 13.5, lineHeight: 1.5,
    boxShadow: agent ? "none" : "0 4px 16px rgba(0,94,255,0.3)",
  };
  if (m.type === "file") {
    return (
      <div style={base}>
        {m.isImg && m.url
          ? <img src={m.url} alt={m.fileName} style={{ maxWidth: "100%", borderRadius: 8, display: "block", marginBottom: 6 }} />
          : null}
        <span style={{ display: "flex", alignItems: "center", gap: 7 }}>
          <i data-lucide={m.isImg ? "image" : "file-text"} style={{ width: 15, height: 15 }}></i>
          {m.fileName}
        </span>
      </div>
    );
  }
  if (m.type === "audio") {
    return (
      <div style={{ ...base, padding: "8px 10px" }}>
        <audio controls src={m.url} style={{ height: 34, maxWidth: 220 }} />
      </div>
    );
  }
  return <div style={base}>{m.text}</div>;
};

window.ChatWidget = ChatWidget;
