function Chatbot({ open, onClose }) {
  const [messages, setMessages] = useState([
    { role: "assistant", content: "Hi Rachel — I'm your SASA assistant. Ask me about the platform, a specific training, or for help finding the right resource for a student-athlete situation.", suggested: true },
  ]);
  const [input, setInput] = useState("");
  const [typing, setTyping] = useState(false);
  const scrollRef = useRef();

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

  const suggestions = [
    "How do I share a resource with my student-athletes?",
    "What's new in NCAA eligibility for 2026?",
    "Where's the burnout screening checklist?",
    "How do I export my engagement report?",
  ];

  const send = async (text) => {
    const msg = (text || input).trim();
    if (!msg) return;
    setInput("");
    setMessages(m => [...m, { role: "user", content: msg }]);
    setTyping(true);

    try {
      const systemContext = `You are the AI support assistant for the Student-Athlete Success Academy (SASA) counselor portal. Counselors use this platform to access monthly training videos, a resource hub organized by four pillars (Recruiting, Mental Health, Academic Planning, NCAA Eligibility), and track their engagement. Be warm, concise (2-4 short sentences or a short list), and practical. If a question is about how to use the platform, give clear steps. If it's about a student-athlete situation, suggest specific SASA resources by pillar. Never give clinical diagnoses — for mental health urgency recommend the warm handoff script and crisis line resources. Today's user is Rachel Kim, a counselor at Westbrook High.`;

      const history = [...messages, { role: "user", content: msg }]
        .filter(m => !m.suggested)
        .map(m => ({ role: m.role, content: m.content }));

      const reply = await window.claude.complete({
        messages: [
          { role: "user", content: systemContext + "\n\n---\n\nConversation so far, then respond to the last user message:\n" + history.map(h => `${h.role.toUpperCase()}: ${h.content}`).join("\n") + "\n\nASSISTANT:" },
        ],
      });

      setMessages(m => [...m, { role: "assistant", content: reply.trim() }]);
    } catch (e) {
      setMessages(m => [...m, { role: "assistant", content: "I'm having trouble reaching the server. Try again, or email support@sasa.edu for human help." }]);
    } finally {
      setTyping(false);
    }
  };

  if (!open) return null;

  return (
    <div style={{
      position: "fixed", bottom: 24, right: 24, width: 400, height: 600, zIndex: 50,
      background: "var(--card)", borderRadius: 14,
      border: "1px solid var(--line-2)",
      boxShadow: "0 20px 50px -12px rgba(27,61,47,0.25)",
      display: "flex", flexDirection: "column", overflow: "hidden",
      animation: "slideUp 260ms cubic-bezier(0.2, 0.8, 0.2, 1)",
    }}>
      {/* Header */}
      <div style={{
        padding: "14px 16px",
        background: "linear-gradient(135deg, #1B3D2F 0%, #2C5C44 100%)",
        color: "white",
        display: "flex", alignItems: "center", gap: 10,
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 9,
          background: "rgba(255,255,255,0.15)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <window.I.Sparkles size={16} stroke="#E8A020" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 500, letterSpacing: -0.005 }}>Ask SASA</div>
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.6)", display: "inline-flex", alignItems: "center", gap: 5 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "#44B89A" }} />
            AI assistant · online
          </div>
        </div>
        <button onClick={onClose} style={{ width: 28, height: 28, borderRadius: 7, background: "rgba(255,255,255,0.1)", color: "white", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
          <window.I.X size={14} />
        </button>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            display: "flex", gap: 8,
            justifyContent: m.role === "user" ? "flex-end" : "flex-start",
          }}>
            {m.role === "assistant" && (
              <div style={{
                width: 26, height: 26, borderRadius: 999,
                background: "linear-gradient(135deg, #1B3D2F 0%, #2C5C44 100%)",
                display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
              }}>
                <window.I.Sparkles size={12} stroke="white" />
              </div>
            )}
            <div style={{
              maxWidth: "82%",
              padding: "9px 13px",
              borderRadius: m.role === "user" ? "14px 14px 3px 14px" : "14px 14px 14px 3px",
              background: m.role === "user" ? "var(--ink)" : "var(--bg-2)",
              color: m.role === "user" ? "white" : "var(--ink)",
              fontSize: 13, lineHeight: 1.5,
              whiteSpace: "pre-wrap",
              border: m.role === "user" ? "none" : "1px solid var(--line)",
            }}>
              {m.content}
            </div>
          </div>
        ))}
        {typing && (
          <div style={{ display: "flex", gap: 8 }}>
            <div style={{
              width: 26, height: 26, borderRadius: 999,
              background: "linear-gradient(135deg, #2B8C8C, #1f6666)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <window.I.Sparkles size={12} stroke="white" />
            </div>
            <div style={{ padding: "11px 14px", background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "14px 14px 14px 3px", display: "inline-flex", gap: 4 }}>
              {[0, 1, 2].map(i => (
                <div key={i} style={{
                  width: 5, height: 5, borderRadius: 999, background: "var(--ink-3)",
                  animation: `pulse 1.2s ${i * 0.15}s infinite`,
                }} />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Suggestions */}
      {messages.length <= 1 && (
        <div style={{ padding: "0 14px 10px", display: "flex", flexDirection: "column", gap: 6 }}>
          {suggestions.map((s, i) => (
            <button
              key={i}
              onClick={() => send(s)}
              style={{
                padding: "8px 12px", border: "1px solid var(--line)", borderRadius: 8,
                background: "var(--card)", color: "var(--ink-2)",
                fontSize: 12.5, textAlign: "left", letterSpacing: -0.005,
              }}
              className="nav-item"
            >
              {s}
            </button>
          ))}
        </div>
      )}

      {/* Input */}
      <form
        onSubmit={(e) => { e.preventDefault(); send(); }}
        style={{
          padding: 12, borderTop: "1px solid var(--line)",
          display: "flex", gap: 8, background: "var(--card)",
        }}
      >
        <input
          value={input}
          onChange={e => setInput(e.target.value)}
          placeholder="Type your question…"
          style={{
            flex: 1, padding: "10px 13px", border: "1px solid var(--line-2)", borderRadius: 8,
            fontSize: 13, background: "var(--bg-2)",
          }}
        />
        <button
          type="submit"
          disabled={!input.trim() || typing}
          style={{
            padding: "0 14px", background: "var(--ink)", color: "white", borderRadius: 8,
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            opacity: !input.trim() || typing ? 0.4 : 1,
          }}
        >
          <window.I.Send size={14} />
        </button>
      </form>
    </div>
  );
}

window.Chatbot = Chatbot;
