import { useState } from "react";
import { sendMessageToBot } from "../api";
import MessageBubble from "./MessageBubble";
import SuggestedQuestions from "./SuggestedQuestions";
import CitationPanel from "./CitationPanel";

export default function ChatWindow() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [citations, setCitations] = useState([]);

  async function handleSend() {
    if (!input.trim()) return;
    const userMsg = { role: "user", content: input };
    setMessages(prev => [...prev, userMsg]);
    setInput("");
    setLoading(true);

    const botResponse = await sendMessageToBot(input, messages);
    setMessages(prev => [...prev, { role: "bot", content: botResponse.answer }]);
    setCitations(botResponse.citations ?? []);
    setLoading(false);
  }

  return (
    <div className="chat-window">
      <div className="chat-body">
        {messages.map((m, i) => <MessageBubble key={i} msg={m} />)}
        {loading && <div className="typing">✍️ HR Assistant is typing...</div>}
      </div>

      <SuggestedQuestions onSelect={txt => setInput(txt)} />

      <div className="chat-input">
        <input
          value={input}
          placeholder="Ask something about HR policy..."
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === "Enter" && handleSend()}
        />
        <button onClick={handleSend}>Send</button>
      </div>

      <CitationPanel citations={citations} />
    </div>
  );
}
