"use client";

import { useEffect, useRef, useCallback } from "react";
import { useChatStore } from "@/lib/store";
import { Message } from "./message";

export function MessageList() {
  const messages = useChatStore((s) => s.messages);
  const isStreaming = useChatStore((s) => s.isStreaming);
  const containerRef = useRef<HTMLDivElement>(null);
  const isNearBottomRef = useRef(true);

  const scrollToBottom = useCallback(() => {
    if (!containerRef.current || !isNearBottomRef.current) return;
    containerRef.current.scrollTop = containerRef.current.scrollHeight;
  }, []);

  const handleScroll = useCallback(() => {
    if (!containerRef.current) return;
    const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
    isNearBottomRef.current = scrollHeight - scrollTop - clientHeight < 100;
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, scrollToBottom]);

  if (messages.length === 0) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-center">
          <p className="text-text-muted text-lg">aeries</p>
          <p className="text-text-faint text-sm mt-2">say something</p>
        </div>
      </div>
    );
  }

  return (
    <div
      ref={containerRef}
      onScroll={handleScroll}
      className="flex-1 overflow-y-auto px-4 py-6 md:px-8"
    >
      <div className="max-w-2xl mx-auto space-y-0">
        {messages.map((msg, i) => {
          const next = messages[i + 1];
          const isLastInGroup = !next || next.role !== msg.role;
          const isCurrentlyStreaming =
            isStreaming &&
            msg.role === "assistant" &&
            i === messages.length - 1;

          return (
            <Message
              key={msg.id}
              message={msg}
              isStreaming={isCurrentlyStreaming}
              isLastInGroup={isLastInGroup}
            />
          );
        })}
      </div>
    </div>
  );
}
