"use client";

import { useEffect, useRef } from "react";
import { MessageList } from "./message-list";
import { InputBar } from "./input-bar";
import { useChatStore } from "@/lib/store";
import type { ChatMessage } from "@/lib/types";

export function ChatContainer() {
  const error = useChatStore((s) => s.error);
  const activeId = useChatStore((s) => s.activeConversationId);
  const setMessages = useChatStore((s) => s.setMessages);
  const prevIdRef = useRef<string | null>(null);

  // Load messages from Synap when switching conversations
  useEffect(() => {
    if (!activeId || activeId === prevIdRef.current) return;
    prevIdRef.current = activeId;

    let cancelled = false;

    async function load() {
      try {
        const res = await fetch(`/api/conversations/${activeId}/messages`);
        if (!res.ok || cancelled) return;
        const data: { messages: ChatMessage[] } = await res.json();
        if (!cancelled && data.messages.length > 0) {
          setMessages(data.messages);
        }
      } catch {
        // Silently fail — empty conversation is fine
      }
    }

    load();
    return () => {
      cancelled = true;
    };
  }, [activeId, setMessages]);

  return (
    <div className="flex flex-col flex-1 min-w-0 h-dvh">
      <MessageList />

      {error && (
        <div className="px-4 md:px-8">
          <div className="max-w-2xl mx-auto">
            <p className="text-negative text-sm py-2">{error}</p>
          </div>
        </div>
      )}

      <InputBar />
    </div>
  );
}
