import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { ProtectedRoute } from './components/layout/ProtectedRoute';
import Landing from './pages/Landing';
import Login from './pages/auth/Login';
import Register from './pages/auth/Register';
import InfluencerDashboard from './pages/influencer/InfluencerDashboard';
import BusinessDashboard from './pages/business/BusinessDashboard';

function AppRoutes() {
  const { isAuthenticated, user } = useAuth();

  const homeFallback =
    isAuthenticated && user
      ? user.is_influencer
        ? '/influencer/dashboard'
        : '/business/dashboard'
      : undefined;

  return (
    <Routes>
      <Route
        path="/"
        element={homeFallback ? <Navigate to={homeFallback} replace /> : <Landing />}
      />
      <Route path="/login" element={<Login />} />
      <Route path="/register" element={<Register />} />
      <Route
        path="/influencer/dashboard"
        element={
          <ProtectedRoute requiredRole="INFLUENCER">
            <InfluencerDashboard />
          </ProtectedRoute>
        }
      />
      <Route
        path="/business/dashboard"
        element={
          <ProtectedRoute requiredRole="BUSINESS">
            <BusinessDashboard />
          </ProtectedRoute>
        }
      />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthProvider>
        <AppRoutes />
      </AuthProvider>
    </BrowserRouter>
  );
}
