import { useState, useEffect } from 'react';
import { useLocation, Navigate } from 'react-router-dom';
import { Loader2 } from 'lucide-react';
import { Shell } from './Shell';
import { DashboardProvider } from '@/contexts/DashboardContext';
import { PageHeaderProvider } from '@/contexts/PageHeaderContext';
import { FABProvider } from '@/contexts/FABContext';

export function AuthWrapper() {
  const [isAuthenticated, setIsAuthenticated] = useState(
    window.WNW_CONFIG?.isAuthenticated ?? true
  );
  const [isChecking, setIsChecking] = useState(window.WNW_CONFIG?.standaloneMode ?? false);
  const location = useLocation();

  useEffect(() => {
    // In standalone mode, trust the initial PHP auth check
    // PHP uses wp_signon which sets proper WordPress cookies
    const checkAuth = () => {
      if (window.WNW_CONFIG?.standaloneMode) {
        setIsAuthenticated(window.WNW_CONFIG.isAuthenticated ?? false);
        setIsChecking(false);
      } else {
        // In wp-admin mode, always authenticated
        setIsChecking(false);
      }
    };
    checkAuth();
  }, []);

  if (isChecking) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-12 h-12 animate-spin text-primary" />
      </div>
    );
  }

  if (window.WNW_CONFIG?.standaloneMode && !isAuthenticated && location.pathname !== '/login') {
    return <Navigate to="/login" replace />;
  }

  if (location.pathname === '/login' && isAuthenticated) {
    return <Navigate to="/" replace />;
  }

  return (
    <FABProvider>
      <PageHeaderProvider>
        <DashboardProvider>
          <Shell />
        </DashboardProvider>
      </PageHeaderProvider>
    </FABProvider>
  );
}
