const chatStyles = {
  fab: {
    position: "fixed", bottom: 24, right: 24, zIndex: 70,
    display: "flex", flexDirection: "column", gap: 12, alignItems: "flex-end"
  },
  fabBtn: {
    width: 58, height: 58, borderRadius: "50%",
    display: "grid", placeItems: "center",
    boxShadow: "0 12px 28px -8px rgba(0,0,0,0.3)",
    transition: "transform 0.2s",
    color: "white"
  },
  whatsFab: { background: "#1A9E4A", boxShadow: "0 0 20px rgba(26,158,74,0.5), 0 8px 24px -8px rgba(0,0,0,0.4)" },
  aiFab: { background: "var(--sage-700)" },
  panel: {
    position: "fixed", bottom: 24, right: 24, zIndex: 75,
    width: "min(400px, calc(100vw - 32px))",
    height: "min(620px, calc(100vh - 100px))",
    background: "var(--cream-50)",
    borderRadius: 22, overflow: "hidden",
    display: "flex", flexDirection: "column",
    boxShadow: "0 30px 60px -20px rgba(30,42,27,0.35)",
    border: "1px solid rgba(42,37,32,0.08)",
    animation: "chatSlideUp 0.3s cubic-bezier(.2,.8,.2,1)"
  },
  header: {
    padding: "18px 20px",
    background: "var(--sage-700)", color: "var(--cream-50)",
    display: "flex", alignItems: "center", gap: 12
  },
  headerAvatar: {
    width: 42, height: 42, borderRadius: "50%",
    background: "linear-gradient(135deg, #c9d5bf, #6b8762)",
    display: "grid", placeItems: "center", color: "var(--sage-900)",
    fontFamily: "'Fraunces', serif", fontWeight: 500, fontSize: 18,
    position: "relative"
  },
  dot: {
    position: "absolute", bottom: 0, right: 0,
    width: 12, height: 12, borderRadius: "50%",
    background: "#4ade80", border: "2px solid var(--sage-700)"
  },
  title: { fontWeight: 600, fontSize: 15 },
  sub: { fontSize: 12, color: "rgba(251,248,242,0.75)" },
  closeBtn: {
    marginLeft: "auto", width: 32, height: 32, borderRadius: "50%",
    background: "rgba(251,248,242,0.1)", color: "var(--cream-50)",
    display: "grid", placeItems: "center"
  },
  body: {
    flex: 1, overflow: "auto",
    padding: 20, display: "flex", flexDirection: "column", gap: 14,
    background: "var(--cream-50)"
  },
  msg: { maxWidth: "85%", padding: "12px 16px", borderRadius: 16, fontSize: 14.5, lineHeight: 1.5, whiteSpace: "pre-wrap" },
  msgA: { background: "var(--sage-100)", color: "var(--sage-900)", alignSelf: "flex-start", borderBottomLeftRadius: 4 },
  msgU: { background: "var(--warm-900)", color: "var(--cream-50)", alignSelf: "flex-end", borderBottomRightRadius: 4 },
  typing: { display: "flex", gap: 4, padding: "14px 16px", background: "var(--sage-100)", borderRadius: 16, borderBottomLeftRadius: 4, alignSelf: "flex-start" },
  dotT: { width: 7, height: 7, borderRadius: "50%", background: "var(--sage-600)", animation: "bounce 1.4s infinite" },
  suggest: { display: "flex", flexWrap: "wrap", gap: 8, padding: "0 20px 12px" },
  suggestBtn: {
    padding: "8px 14px", borderRadius: 999,
    background: "var(--cream-100)", border: "1px solid rgba(42,37,32,0.1)",
    fontSize: 13, color: "var(--warm-700)", cursor: "pointer",
    transition: "background 0.15s"
  },
  footer: {
    padding: 14, borderTop: "1px solid rgba(42,37,32,0.08)",
    display: "flex", gap: 10, alignItems: "flex-end",
    background: "var(--cream-50)"
  },
  input: {
    flex: 1, padding: "12px 14px",
    borderRadius: 14, border: "1.5px solid rgba(42,37,32,0.1)",
    fontSize: 14, outline: "none", resize: "none",
    fontFamily: "inherit", maxHeight: 100, background: "white"
  },
  send: {
    width: 42, height: 42, borderRadius: "50%",
    background: "var(--sage-700)", color: "white",
    display: "grid", placeItems: "center", flexShrink: 0,
    transition: "background 0.15s, transform 0.15s"
  },
  sendDisabled: { opacity: 0.4, cursor: "not-allowed" },
  captureCard: {
    background: "var(--cream-100)", border: "1px solid var(--sage-200)",
    borderRadius: 14, padding: 14, alignSelf: "stretch", marginTop: 4
  }
};

const systemPrompt = `Você é a assistente virtual do consultório da Nutricionista Diana Vicente. Seu papel é acolher visitantes do site, entender rapidamente o objetivo delas e direcionar para agendar uma consulta.

INFORMAÇÕES SOBRE A DIANA:
- Diana Vicente, nutricionista esportiva, CRN SC 14264, mais de 4 anos de experiência, +400 mulheres acompanhadas.
- Atendimento online para todo o Brasil e presencial em Florianópolis SC.
- Método: Shape Blindado - acompanhamento estratégico e individualizado de dieta e treino para mulheres que querem reduzir gordura, ganhar massa muscular e construir um shape mais definido e forte.
- Foco em shape feminino: definição corporal, redução de gordura, ganho de massa, melhora de performance e confiança.
- Diferencial: dieta e treino integrados, ajustes baseados na evolução real, sem restrição extrema.

TOM: acolhedor, próximo, direto, informal. Respostas curtas: 2-4 frases. Use 1 emoji ocasional (💪 ✨ 🌿). NÃO invente dados médicos nem prescreva dieta - direcione para consulta.

APÓS 2-3 TROCAS ou quando a usuária mostrar interesse real, SUGIRA agendar a consulta. Se apropriado, termine com:
[AGENDAR] - se fizer sentido abrir o formulário de agendamento
[WHATSAPP] - se for melhor direcionar pro WhatsApp agora
Use os marcadores com moderação - só quando for o próximo passo natural.`;

const AIChat = ({ open, onClose, onOpenForm, onWhatsApp }) => {
  const [messages, setMessages] = React.useState([
    { role: "assistant", content: "Oi! ✨ Sou a assistente da Diana. Me conta: o que te trouxe aqui hoje? Qual é o seu objetivo?" }
  ]);
  const [input, setInput] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const bodyRef = React.useRef(null);

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

  const suggestions = messages.length <= 1
    ? ["Quero definir o corpo", "Como funciona o método?", "Atende presencial?"]
    : [];

  const send = async (text) => {
    const content = (text || input).trim();
    if (!content || loading) return;

    const userMsg = { role: "user", content };
    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput("");
    setLoading(true);

    try {
      const convo = newMessages.map(m => ({ role: m.role, content: m.content }));
      const reply = await window.claude.complete({
        system: systemPrompt,
        messages: convo
      });

      let clean = reply;
      let action = null;
      if (reply.includes("[AGENDAR]")) { action = "form"; clean = reply.replace("[AGENDAR]", "").trim(); }
      else if (reply.includes("[WHATSAPP]")) { action = "whats"; clean = reply.replace("[WHATSAPP]", "").trim(); }

      setMessages(m => [...m, { role: "assistant", content: clean, action }]);
    } catch (err) {
      setMessages(m => [...m, {
        role: "assistant",
        content: "Deu um errinho aqui do meu lado. Se preferir, clica no WhatsApp que a Diana responde direto!",
        action: "whats"
      }]);
    } finally {
      setLoading(false);
    }
  };

  if (!open) return null;

  return (
    <div style={chatStyles.panel}>
      <div style={chatStyles.header}>
        <div style={chatStyles.headerAvatar}>
          D
          <span style={chatStyles.dot}></span>
        </div>
        <div>
          <div style={chatStyles.title}>Assistente da Diana</div>
          <div style={chatStyles.sub}>Online • responde em segundos</div>
        </div>
        <button style={chatStyles.closeBtn} onClick={onClose}><IconClose size={16} /></button>
      </div>

      <div style={chatStyles.body} ref={bodyRef}>
        {messages.map((m, i) => (
          <React.Fragment key={i}>
            <div style={{ ...chatStyles.msg, ...(m.role === "user" ? chatStyles.msgU : chatStyles.msgA) }}>
              {m.content}
            </div>
            {m.action === "form" && (
              <div style={chatStyles.captureCard}>
                <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 6, color: "var(--sage-900)" }}>Agendar consulta</div>
                <div style={{ fontSize: 13, color: "var(--warm-500)", marginBottom: 12 }}>Responda algumas perguntas rápidas e a Diana entra em contato.</div>
                <button style={{
                  padding: "10px 16px", borderRadius: 999,
                  background: "var(--sage-700)", color: "white",
                  fontSize: 14, fontWeight: 500,
                  display: "inline-flex", alignItems: "center", gap: 8
                }} onClick={onOpenForm}>
                  Começar <IconArrowRight size={14} />
                </button>
              </div>
            )}
            {m.action === "whats" && (
              <div style={chatStyles.captureCard}>
                <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 6, color: "var(--sage-900)" }}>Falar com a Diana</div>
                <div style={{ fontSize: 13, color: "var(--warm-500)", marginBottom: 12 }}>Te levo para uma conversa direto no WhatsApp.</div>
                <button style={{
                  padding: "10px 16px", borderRadius: 999,
                  background: "#1A9E4A", color: "white",
                  fontSize: 14, fontWeight: 500,
                  display: "inline-flex", alignItems: "center", gap: 8
                }} onClick={onWhatsApp}>
                  <IconWhatsApp size={14} color="white" /> Abrir WhatsApp
                </button>
              </div>
            )}
          </React.Fragment>
        ))}
        {loading && (
          <div style={chatStyles.typing}>
            <span style={{ ...chatStyles.dotT, animationDelay: "0s" }}></span>
            <span style={{ ...chatStyles.dotT, animationDelay: "0.2s" }}></span>
            <span style={{ ...chatStyles.dotT, animationDelay: "0.4s" }}></span>
          </div>
        )}
      </div>

      {suggestions.length > 0 && !loading && (
        <div style={chatStyles.suggest}>
          {suggestions.map(s => (
            <button key={s} style={chatStyles.suggestBtn}
              onMouseEnter={e => e.currentTarget.style.background = "var(--sage-100)"}
              onMouseLeave={e => e.currentTarget.style.background = "var(--cream-100)"}
              onClick={() => send(s)}>{s}</button>
          ))}
        </div>
      )}

      <div style={chatStyles.footer}>
        <textarea
          style={chatStyles.input}
          placeholder="Escreva sua dúvida..."
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
          rows={1}
          onFocus={e => e.target.style.borderColor = "var(--sage-600)"}
          onBlur={e => e.target.style.borderColor = "rgba(42,37,32,0.1)"}
        />
        <button
          style={{ ...chatStyles.send, ...((!input.trim() || loading) ? chatStyles.sendDisabled : {}) }}
          onClick={() => send()}
          disabled={!input.trim() || loading}
        >
          <IconSend size={18} />
        </button>
      </div>

      <style>{`
        @keyframes chatSlideUp { from { opacity: 0; transform: translateY(20px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
        @keyframes bounce { 0%, 60%, 100% { transform: translateY(0); opacity: 0.6; } 30% { transform: translateY(-6px); opacity: 1; } }
        @keyframes fabGlow { 0%,100% { box-shadow: 0 0 16px rgba(26,158,74,0.4), 0 8px 24px -8px rgba(0,0,0,0.4); } 50% { box-shadow: 0 0 32px rgba(26,158,74,0.7), 0 8px 24px -8px rgba(0,0,0,0.4); } }
        .whats-fab { animation: fabGlow 2.5s ease-in-out infinite !important; }
      `}</style>
    </div>
  );
};

const FloatingActions = ({ onWhatsApp }) => {
  return (
    <div className="floating-fab" style={chatStyles.fab}>
      <button
        className="whats-fab"
        style={{ ...chatStyles.fabBtn, ...chatStyles.whatsFab }}
        onClick={onWhatsApp}
        onMouseEnter={e => e.currentTarget.style.transform = "translateY(-3px)"}
        onMouseLeave={e => e.currentTarget.style.transform = "translateY(0)"}
        aria-label="Agendar pelo WhatsApp"
        title="Agendar pelo WhatsApp"
      >
        <IconWhatsApp size={28} color="white" />
      </button>
      <style>{`
        @media (max-width: 768px) {
          .floating-fab {
            right: 16px !important;
            bottom: 74px !important;
          }
          .floating-fab button {
            width: 52px !important;
            height: 52px !important;
          }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { AIChat, FloatingActions });
