// Clube da Luz — Coraline (Chakra) chatbot FAB
// Botão flutuante sutil + painel de chat com window.claude.complete

const { useState: useStateChat, useRef: useRefChat, useEffect: useEffectChat } = React;

const CORALINE_SYSTEM = `
Você é Coraline, anfitriã digital do Clube da Luz — um círculo privado de mentoria criativa
conduzido por Adriano Ribeiro. Você fala em português do Brasil, num tom acolhedor, breve e
um pouco poético, sempre objetivo. Suas funções:

— Apresentar o Clube em poucas palavras quando perguntarem.
— Explicar as trilhas (Jeito Criativo de Ser, Régua Criativa, Laboratório de Obra, Mentoria de Marca),
  o método (Régua Criativa com 8 dimensões) e como funciona a aplicação por convite.
— Ajudar quem está em dúvida sobre se faz sentido aplicar, fazendo perguntas curtas.
— Encaminhar para o formulário de aplicação quando houver interesse.
— NUNCA citar valores, preços, "high-ticket" ou comparações comerciais. Diga apenas que o investimento
  é apresentado após a entrevista de encaixe, se houver convite.
— Suas respostas devem caber em 2-4 frases, no máximo. Use travessões com elegância.
— Se perguntarem quem é você, diga: "Sou a Coraline, anfitriã do círculo — versão Chakra."

Não invente datas, números ou nomes. Se não souber algo específico, sugira agendar pela aplicação.
`.trim();

function ChatbotFAB() {
  const [open, setOpen] = useStateChat(false);
  const [msgs, setMsgs] = useStateChat([
    { role: "assistant", content: "Olá. Sou a Coraline — anfitriã do círculo. Posso ajudar a entender se o Clube faz sentido para o seu momento. O que te trouxe aqui?" },
  ]);
  const [input, setInput] = useStateChat("");
  const [busy, setBusy] = useStateChat(false);
  const [unread, setUnread] = useStateChat(false);
  const scrollRef = useRefChat(null);

  useEffectChat(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [msgs, open]);

  const send = async () => {
    const text = input.trim();
    if (!text || busy) return;
    const history = [...msgs, { role: "user", content: text }];
    setMsgs(history);
    setInput("");
    setBusy(true);
    try {
      const reply = await window.claude.complete({
        messages: [
          { role: "user", content: `${CORALINE_SYSTEM}\n\n— Conversa até aqui —\n` +
            history.map(m => (m.role === "user" ? "Visitante: " : "Coraline: ") + m.content).join("\n") +
            `\n\nResponda como Coraline, em português do Brasil, 2-4 frases.` },
        ],
      });
      setMsgs(h => [...h, { role: "assistant", content: (reply || "").trim() || "Posso te ajudar a entender o caminho. Pode contar um pouco mais do seu momento?" }]);
      if (!open) setUnread(true);
    } catch (e) {
      setMsgs(h => [...h, { role: "assistant", content: "Tive um instante de silêncio aqui. Pode repetir, por favor?" }]);
    } finally {
      setBusy(false);
    }
  };

  const onKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  return (
    <>
      {/* Floating button */}
      {!open && (
        <button
          onClick={() => { setOpen(true); setUnread(false); }}
          aria-label="Conversar com Coraline"
          style={{
            position: "fixed",
            right: 24, bottom: 24,
            zIndex: 90,
            width: 60, height: 60,
            borderRadius: "50%",
            background: "linear-gradient(135deg, #E8C079 0%, #C99848 65%, #8A6428 100%)",
            border: "1px solid rgba(255,255,255,0.18)",
            color: "#241a08",
            display: "flex", alignItems: "center", justifyContent: "center",
            cursor: "pointer",
            boxShadow: "0 12px 40px -10px rgba(0,0,0,0.6), 0 0 0 1px rgba(0,0,0,0.4)",
            animation: "chatPulse 3.6s ease-in-out infinite",
            transition: "transform .25s ease",
          }}
          onMouseEnter={(e) => e.currentTarget.style.transform = "scale(1.06)"}
          onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path
              d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H9l-4 4v-4H6a2 2 0 0 1-2-2V6z"
              stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" fill="none"
            />
            <circle cx="9" cy="10.5" r="1" fill="currentColor" />
            <circle cx="12" cy="10.5" r="1" fill="currentColor" />
            <circle cx="15" cy="10.5" r="1" fill="currentColor" />
          </svg>
          {unread && (
            <span style={{
              position: "absolute", top: 4, right: 4,
              width: 10, height: 10, borderRadius: "50%",
              background: "var(--aqua)", border: "1.5px solid #060912",
            }} />
          )}
        </button>
      )}

      {/* Chat panel */}
      {open && (
        <div
          style={{
            position: "fixed",
            right: 24, bottom: 24,
            zIndex: 90,
            width: "min(380px, calc(100vw - 32px))",
            height: "min(540px, calc(100vh - 100px))",
            background: "rgba(10,15,28,0.88)",
            backdropFilter: "blur(20px) saturate(140%)",
            WebkitBackdropFilter: "blur(20px) saturate(140%)",
            border: "1px solid var(--line-strong)",
            borderRadius: 12,
            display: "flex", flexDirection: "column",
            boxShadow: "0 30px 80px -20px rgba(0,0,0,0.8), 0 0 60px -20px rgba(232,192,121,0.25)",
            animation: "chatRise .3s cubic-bezier(.2,.7,.2,1)",
            overflow: "hidden",
          }}
        >
          {/* header */}
          <div style={{
            padding: "16px 18px",
            borderBottom: "1px solid var(--line)",
            display: "flex", alignItems: "center", gap: 12,
            background: "linear-gradient(180deg, rgba(232,192,121,0.06) 0%, transparent 100%)",
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: "50%",
              background: "linear-gradient(135deg, #E8C079 0%, #C99848 100%)",
              display: "flex", alignItems: "center", justifyContent: "center",
              color: "#241a08", fontFamily: "var(--f-display)", fontStyle: "italic", fontSize: 18,
              boxShadow: "0 0 14px rgba(232,192,121,0.3)",
            }}>
              C
            </div>
            <div style={{ flex: 1, lineHeight: 1.2 }}>
              <div style={{ fontSize: 14.5, color: "var(--ivory)", fontFamily: "var(--f-display)", fontStyle: "italic" }}>
                Coraline
              </div>
              <div className="serial" style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{
                  width: 6, height: 6, borderRadius: "50%", background: "var(--gold)",
                  boxShadow: "0 0 6px var(--gold)"
                }} />
                Anfitriã · online
              </div>
            </div>
            <button
              onClick={() => setOpen(false)}
              aria-label="Fechar"
              style={{
                width: 28, height: 28, borderRadius: 8,
                background: "rgba(255,255,255,0.04)",
                color: "var(--ivory-dim)",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <path d="M6 6l12 12M18 6l-12 12" stroke="currentColor" strokeWidth="1.4" />
              </svg>
            </button>
          </div>

          {/* messages */}
          <div
            ref={scrollRef}
            style={{
              flex: 1, overflowY: "auto",
              padding: "20px 18px",
              display: "flex", flexDirection: "column", gap: 12,
            }}
          >
            {msgs.map((m, i) => (
              <div
                key={i}
                style={{
                  alignSelf: m.role === "user" ? "flex-end" : "flex-start",
                  maxWidth: "85%",
                  padding: "11px 14px",
                  borderRadius: m.role === "user" ? "14px 14px 4px 14px" : "14px 14px 14px 4px",
                  fontSize: 14,
                  lineHeight: 1.55,
                  background: m.role === "user"
                    ? "linear-gradient(135deg, rgba(122,215,232,0.18), rgba(40,144,176,0.10))"
                    : "rgba(255,255,255,0.04)",
                  border: m.role === "user"
                    ? "1px solid rgba(122,215,232,0.2)"
                    : "1px solid var(--line)",
                  color: "var(--ivory)",
                  animation: "msgIn .3s cubic-bezier(.2,.7,.2,1)",
                }}
              >
                {m.content}
              </div>
            ))}
            {busy && (
              <div style={{
                alignSelf: "flex-start",
                padding: "11px 14px",
                borderRadius: "14px 14px 14px 4px",
                background: "rgba(255,255,255,0.04)",
                border: "1px solid var(--line)",
                display: "flex", alignItems: "center", gap: 6,
              }}>
                <Dot d={0} /><Dot d={0.15} /><Dot d={0.3} />
              </div>
            )}
          </div>

          {/* input */}
          <div style={{
            padding: 14, borderTop: "1px solid var(--line)",
            display: "flex", gap: 8, alignItems: "flex-end",
            background: "rgba(6,9,18,0.4)",
          }}>
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={onKeyDown}
              placeholder="Escreva sua mensagem…"
              rows={1}
              style={{
                flex: 1,
                resize: "none",
                background: "rgba(255,255,255,0.04)",
                border: "1px solid var(--line)",
                borderRadius: 8,
                padding: "10px 12px",
                color: "var(--ivory)",
                fontSize: 14,
                fontFamily: "var(--f-ui)",
                outline: "none",
                maxHeight: 100,
                lineHeight: 1.45,
              }}
              onFocus={(e) => e.currentTarget.style.borderColor = "var(--gold)"}
              onBlur={(e) => e.currentTarget.style.borderColor = "var(--line)"}
            />
            <button
              onClick={send}
              disabled={busy || !input.trim()}
              aria-label="Enviar"
              style={{
                width: 38, height: 38, borderRadius: 8,
                background: !input.trim() || busy
                  ? "rgba(255,255,255,0.06)"
                  : "linear-gradient(135deg, #E8C079, #C99848)",
                color: !input.trim() || busy ? "var(--muted)" : "#241a08",
                display: "flex", alignItems: "center", justifyContent: "center",
                transition: "all .25s",
                cursor: busy || !input.trim() ? "default" : "pointer",
                flexShrink: 0,
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>

          <div style={{
            padding: "8px 14px 10px",
            fontFamily: "var(--f-mono)",
            fontSize: 9.5, letterSpacing: "0.12em", textTransform: "uppercase",
            color: "var(--muted-2)", textAlign: "center",
            borderTop: "1px solid var(--line)",
          }}>
            Coraline · Chakra · IA acompanhada por humanos
          </div>
        </div>
      )}

      <style>{`
        @keyframes chatRise {
          from { opacity: 0; transform: translateY(16px) scale(.96); }
          to   { opacity: 1; transform: translateY(0)  scale(1); }
        }
        @keyframes msgIn {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes dotBlink {
          0%, 80%, 100% { opacity: .3; transform: scale(.85); }
          40%           { opacity: 1;  transform: scale(1); }
        }
      `}</style>
    </>
  );
}

function Dot({ d }) {
  return (
    <span style={{
      width: 6, height: 6, borderRadius: "50%",
      background: "var(--gold)",
      display: "inline-block",
      animation: `dotBlink 1.2s ${d}s ease-in-out infinite`,
    }} />
  );
}

Object.assign(window, { ChatbotFAB });
