import React from 'react';
import ReactDOM from 'react-dom/client';
import { createBrowserRouter, RouterProvider, Outlet, Navigate } from 'react-router-dom';
import RootApp from '@/App'; 
import AdminPage from '@/pages/AdminPage';
import LoginPage from '@/pages/LoginPage';
import ManageProfilePage from '@/pages/ManageProfilePage';
import AuthCallbackPage from '@/pages/AuthCallbackPage';
import { AuthProvider, useAuth } from '@/contexts/AuthContext';
import { DataProvider, useData as useDataContextData } from '@/contexts/DataContext'; // Import useData directly
import '@/index.css';
// Toaster is rendered within RootApp, so no need to import here unless specifically needed outside
// import { Toaster } from '@/components/ui/toaster'; 
import { SearchSection } from '@/components/SearchSection'; 
import { useState as ReactUseState, useEffect as ReactUseEffect } from 'react'; 
import { Loader2 } from 'lucide-react';


function HomePageContent() {
  const { barbershops, barbers, loadingData } = useDataContextData(); 
  const [currentUserPosition, setCurrentUserPosition] = ReactUseState(null); 

  ReactUseEffect(() => { 
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setCurrentUserPosition({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          });
        },
        (error) => {
          console.error("Error getting user location:", error);
        }
      );
    }
  }, []);

  if (loadingData && (barbershops.length === 0 && barbers.length === 0) ) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[calc(100vh-200px)] text-white">
        <Loader2 className="h-12 w-12 animate-spin text-yellow-400 mb-4" />
        <p className="text-xl">Carregando barbearias e barbeiros...</p>
      </div>
    );
  }
  
  if (!loadingData && barbershops.length === 0 && barbers.length === 0) {
    return (
      <div className="text-center py-10 text-white">
        <h2 className="text-2xl font-semibold mb-4">Nenhum resultado encontrado</h2>
        <p>Ainda não há barbearias ou barbeiros cadastrados. Seja o primeiro!</p>
      </div>
    );
  }


  return (
    <SearchSection 
      barbershops={barbershops}
      barbers={barbers}
      currentUserPosition={currentUserPosition}
    />
  );
}


const ProtectedRoute = ({ children }) => {
  const { session, loading } = useAuth(); 
  
  if (loading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-gray-900 to-gray-800 text-white p-4">
        <Loader2 className="h-16 w-16 animate-spin text-yellow-400 mb-6" />
        <h1 className="text-3xl font-semibold mb-2">Verificando Autenticação...</h1>
        <p className="text-gray-400">Aguarde um momento.</p>
      </div>
    );
  }

  if (!session) {
    return <Navigate to="/login" replace />;
  }
  return children;
};

const router = createBrowserRouter([
  {
    path: "/",
    element: <RootApp />, 
    children: [ 
      {
        index: true, 
        element: <HomePageContent />,
      }
    ]
  },
  {
    path: "/login",
    element: <LoginPage />,
  },
  {
    path: "/auth/callback",
    element: <AuthCallbackPage />,
  },
  {
    path: "/admin",
    element: (
      <ProtectedRoute>
        <AdminPage /> 
      </ProtectedRoute>
    ),
    children: [
      {
        index: true,
        element: <Navigate to="profile" replace />,
      },
      {
        path: "profile",
        element: <ManageProfilePage />,
      }
    ],
  },
  {
    path: "*",
    element: <Navigate to="/" replace /> 
  }
]);


ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <AuthProvider>
      <DataProvider>
        <RouterProvider router={router} />
      </DataProvider>
    </AuthProvider>
  </React.StrictMode>
);