// Chat sidebar — RAG-style Q&A backed by window.claude.complete + a hardcoded
// knowledge base string in data.js. Conversation lives in component state only;
// no persistence.

const { useState, useRef, useEffect } = React;

const SUGGESTED_PROMPTS = [
  "What does Carlos work on day-to-day?",
  "What's their strongest detection tool?",
  "Tell me about their CTF team.",
];

function ChatSidebar() {
  const { PERSON, KNOWLEDGE_BASE } = window.PORTFOLIO_DATA;
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const logRef = useRef(null);
  const inputRef = useRef(null);

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

  const send = async (textOverride) => {
    const text = (textOverride ?? input).trim();
    if (!text || busy) return;
    const next = [...messages, { role: "user", content: text }];
    setMessages(next);
    setInput("");
    setBusy(true);
    try {
      // Build a single prompt with KB as system context and recent turns inline.
      const history = next
        .slice(-8)
        .map(
          (m) =>
            `${m.role === "user" ? "Visitor" : "Assistant"}: ${m.content}`
        )
        .join("\n");
      const prompt = `${KNOWLEDGE_BASE}\n\n=== CONVERSATION ===\n${history}\nAssistant:`;
      const reply = await window.chatBackend(prompt);
      setMessages((m) => [...m, { role: "assistant", content: reply.trim() }]);
    } catch (e) {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content:
            "Sorry — I couldn't reach the model just now. Try again in a moment.",
        },
      ]);
    } finally {
      setBusy(false);
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  };

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

  // Auto-resize textarea
  const onInput = (e) => {
    setInput(e.target.value);
    const ta = e.target;
    ta.style.height = "auto";
    ta.style.height = Math.min(ta.scrollHeight, 120) + "px";
  };

  return (
    <aside className="sidebar">
      <div className="sidebar-header">
        <div className="sidebar-brand">
          <div className="sidebar-brand-mark">CF</div>
          <div>
            <div className="sidebar-name">{PERSON.name}</div>
            <div className="sidebar-role">{PERSON.role}</div>
          </div>
        </div>
      </div>

      <div className="sidebar-section-title">Ask about me</div>

      <div className="chat-log" ref={logRef}>
        {messages.length === 0 && (
          <div className="chat-empty">
            This sidebar is a small RAG agent with context on Carlos's work,
            experience, and projects. Ask anything — or open a file on the
            right.
            <div className="chat-empty-prompts">
              {SUGGESTED_PROMPTS.map((p) => (
                <button
                  key={p}
                  className="chat-prompt-suggest"
                  onClick={() => send(p)}
                >
                  {p}
                </button>
              ))}
            </div>
          </div>
        )}

        {messages.map((m, i) => (
          <div key={i} className={`chat-msg ${m.role}`}>
            <div className={`chat-msg-role ${m.role}`}>
              {m.role === "user" ? "You" : "About Carlos"}
            </div>
            <div className="chat-msg-body">{m.content}</div>
          </div>
        ))}

        {busy && (
          <div className="chat-msg assistant">
            <div className="chat-msg-role">About Carlos</div>
            <div className="chat-typing">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        )}
      </div>

      <div className="chat-input-wrap">
        <div className="chat-input-shell">
          <textarea
            ref={inputRef}
            className="chat-input"
            rows={1}
            placeholder="Ask about Carlos…"
            value={input}
            onInput={onInput}
            onKeyDown={onKey}
            disabled={busy}
          />
          <button
            className="chat-send"
            onClick={() => send()}
            disabled={busy || !input.trim()}
            aria-label="Send"
          >
            <window.Icons.Send size={14} />
          </button>
        </div>
        <div className="chat-hint">⏎ to send · ⇧⏎ for newline</div>
      </div>
    </aside>
  );
}

window.ChatSidebar = ChatSidebar;
