import React, { useState, useEffect } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { RegistrationProvider, useRegistration } from '../context/RegistrationContext';
import Shell from '../components/Shell';
import ProgressStepper from '../components/ProgressStepper';
import SignInStep from '../components/steps/SignInStep';
import ContactStep from '../components/steps/ContactStep';
import BusinessStep from '../components/steps/BusinessStep';
import ReviewStep from '../components/steps/ReviewStep';
import ConfirmationStep from '../components/steps/ConfirmationStep';

// Step renderer — selects component based on current step
function WizardContent() {
    const { isSignedIn } = useAuth();
    const { currentStep, onSignInComplete } = useRegistration();

    // When auth completes, advance past sign-in step
    useEffect(() => {
        if (isSignedIn && currentStep === 0) {
            onSignInComplete();
        }
    }, [isSignedIn, currentStep, onSignInComplete]);

    const steps = [SignInStep, ContactStep, BusinessStep, ReviewStep, ConfirmationStep];
    const StepComponent = steps[currentStep] || SignInStep;

    return (
        <div className="wizard-container">
            <ProgressStepper currentStep={currentStep} />
            <StepComponent />
        </div>
    );
}

export default function App() {
    const { isLoading } = useAuth();
    const [minWait, setMinWait] = useState(true);

    // Brief minimum wait prevents flash while MSAL hydrates cache
    useEffect(() => {
        const t = setTimeout(() => setMinWait(false), 400);
        return () => clearTimeout(t);
    }, []);

    if (isLoading || minWait) {
        return (
            <Shell>
                <div className="loading-container">
                    <div className="spinner"></div>
                    <p>Loading...</p>
                </div>
            </Shell>
        );
    }

    return (
        <Shell>
            <RegistrationProvider>
                <WizardContent />
            </RegistrationProvider>
        </Shell>
    );
}
