"use client";

import { useEffect, useRef } from "react";

import { ChatMessage } from "@/components/chat/chat-message";
import type { Conversation } from "@/lib/chat/types";

type ChatMessageListProps = {
  canRetryLast: boolean;
  conversation: Conversation;
  isGenerating: boolean;
  onRetry: () => void;
};

export function ChatMessageList({
  canRetryLast,
  conversation,
  isGenerating,
  onRetry,
}: ChatMessageListProps) {
  const endRef = useRef<HTMLDivElement>(null);
  const latest = conversation.messages.at(-1);

  useEffect(() => {
    if (typeof endRef.current?.scrollIntoView === "function") {
      endRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
    }
  }, [conversation.id, latest?.content, latest?.status]);

  return (
    <section
      aria-busy={isGenerating}
      aria-label="Сообщения чата"
      className="chat-readable mx-auto w-full flex-1 px-5 pb-6 pt-4"
    >
      {conversation.messages.map((message, index) => (
        <ChatMessage
          canRetry={
            index === conversation.messages.length - 1 &&
            canRetryLast &&
            (message.status === "error" || message.status === "stopped")
          }
          key={message.id}
          message={message}
          onRetry={onRetry}
        />
      ))}
      <div aria-hidden="true" ref={endRef} />
    </section>
  );
}
