'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';

import OnboardingWizard from '@/components/onboarding/OnboardingWizard';
import { useAuth } from '@/lib/auth/AuthContext';
import { useServices } from '@/lib/services/ServiceProvider';
 
export default function OnboardingPage() {
  const router = useRouter();
  const { session } = useAuth();
  const { driverService } = useServices();
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    // If user is not authenticated, redirect to login
    if (!session) {
      router.replace('/auth/login?returnTo=/onboarding');
      return;
    }

    let cancelled = false;

    const checkOnboarding = async () => {
      try {
        const driver = await driverService.getCurrentDriver();

        if (cancelled) return;

        // If driver profile exists, onboarding is complete – go to dashboard
        if (driver) {
          router.replace('/dashboard');
          return;
        }

        // Otherwise allow onboarding wizard to render
        setChecking(false);
      } catch {
        // On error, allow onboarding to proceed so user isn't blocked
        if (!cancelled) {
          setChecking(false);
        }
      }
    };

    checkOnboarding();

    return () => {
      cancelled = true;
    };
  }, [session, driverService, router]);

  // Show loading while checking auth/onboarding status
  if (checking) {
    return (
      <main className="min-h-screen bg-deep-graphite flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-primary-blue animate-spin" />
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-deep-graphite">
      <OnboardingWizard />
    </main>
  );
}