"use client";

import { useEffect, useRef } from 'react';
import { ChatBubble } from './chat-bubble';
import { TypingIndicator } from './typing-indicator';
import { useChatStore } from '@/store/use-chat';
import { BookOpen, Sparkles } from 'lucide-react';

export function ChatWindow() {
    const { messages, isTyping } = useChatStore();
    const bottomRef = useRef<HTMLDivElement>(null);

    // Auto-scroll to bottom
    useEffect(() => {
        bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages, isTyping]);

    if (!messages || messages.length === 0) {
        return (
            <div className="flex-1 flex flex-col items-center justify-center text-center p-8 space-y-6">
                <div className="relative">
                    <div className="w-32 h-32 bg-gradient-to-br from-secondary to-muted rounded-full flex items-center justify-center">
                        <BookOpen className="w-16 h-16 text-muted-foreground/50" aria-hidden="true" />
                    </div>
                    <Sparkles className="w-8 h-8 text-amber-400 absolute -top-2 -right-2" aria-hidden="true" />
                </div>

                <div className="space-y-2 max-w-md">
                    <h2 className="text-2xl font-bold font-serif text-foreground">
                        What's on your mind?
                    </h2>
                    <p className="text-muted-foreground font-sans">
                        I'm here to listen. Let it all out.
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="h-full flex-1 overflow-y-auto px-4 py-6 scroll-smooth">
            <div className="max-w-3xl mx-auto space-y-4">
                {messages.map((msg) => (
                    <ChatBubble key={msg.id} role={msg.role} content={msg.content} />
                ))}

                {isTyping && (
                    <TypingIndicator />
                )}

                <div ref={bottomRef} className="h-4" />
            </div>
        </div>
    );
}
