"use client";

import { useEffect, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { ChatWindow } from '@/components/features/chat/chat-window';
import { ChatInput } from '@/components/features/chat/chat-input';
import { ThinkingOverlay } from '@/components/features/chat/thinking-overlay';
import { DraftSheet } from '@/components/features/journal/draft-sheet';
import { useChatStore } from '@/store/use-chat';
import { Loader2 } from "lucide-react";
import { AppHeader } from '@/components/layout';

function ChatPageContent() {
    const { resetSession, phase } = useChatStore();
    const searchParams = useSearchParams();
    const router = useRouter();

    // Check for "new" param to force fresh session
    useEffect(() => {
        if (searchParams.get('new') === 'true') {
            resetSession();
            // Clean URL
            router.replace('/chat');
        }
    }, [searchParams, router, resetSession]);

    return (
        <div className="flex flex-col h-dvh bg-background relative">
            {/* Header */}
            <AppHeader />

            {/* Drafting Overlay */}
            {phase === 'drafting' && <ThinkingOverlay />}

            {/* Chat Messages - Scrollable Area */}
            <div className="flex-1 flex flex-col min-h-0 overflow-hidden relative">
                <ChatWindow />
            </div>

            <DraftSheet />

            {/* Chat Input - Fixed at Bottom */}
            <div className="shrink-0">
                <ChatInput />
            </div>
        </div>
    );
}

export default function ChatPage() {
    return (
        <Suspense fallback={
            <div className="flex flex-col h-dvh bg-background items-center justify-center">
                <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
            </div>
        }>
            <ChatPageContent />
        </Suspense>
    );
}
