"use client";

import { useEffect, useState } from 'react';
import { useAuth } from '@/contexts/auth-context';
import { Onboarding } from '@/components/onboarding';
import { Recovery } from '@/components/recovery';
import { ChatInterface } from '@/components/chat-interface';
import { LoadingScreen } from './loading-screen';
import { PreparationScreen } from './preparation-screen';

const PREPARATION_FLAG = 'isAppPrepared_v4';


export const AuthWrapper = () => {
    const authContext = useAuth();
    const [isClient, setIsClient] = useState(false);
    const [isPrepared, setIsPrepared] = useState(true); // Default to true to avoid flash

    useEffect(() => {
        setIsClient(true);
        // Check preparation flag from localStorage only on the client
        if (localStorage.getItem(PREPARATION_FLAG) !== 'true') {
            setIsPrepared(false);
        }
    }, []);
    
    const handlePreparationComplete = () => {
        localStorage.setItem(PREPARATION_FLAG, 'true');
        window.location.reload();
    };

    if (!isClient) {
        return <LoadingScreen />;
    }

    if (!isPrepared) {
        return <PreparationScreen onPrepared={handlePreparationComplete} />;
    }
    
    if (!authContext) {
        return <LoadingScreen />;
    }
    
    const { authStatus } = authContext;

    if (authStatus === 'loading') {
        return <LoadingScreen />;
    }

    if (authStatus === 'onboarding') {
        return <Onboarding />;
    }

    if (authStatus === 'recovery') {
        return <Recovery />;
    }

    if (authStatus === 'authenticated') {
        return <ChatInterface />;
    }

    return null; 
};
