import { Switch, Route, Router as WouterRouter, Redirect } from "wouter";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { LanguageProvider } from "./contexts/LanguageContext";
import { CartProvider } from "./contexts/CartContext";
import { AuthProvider, useAuth } from "./contexts/AuthContext";
import { AppLayout } from "./components/layout/AppLayout";
import { DocumentTitle } from "./hooks/useDocumentTitle";
import NotFound from "@/pages/not-found";
import { ComponentType } from "react";

// Page imports
import Home from "./pages/home";
import About from "./pages/about";
import Waqf from "./pages/waqf";
import Baraem from "./pages/baraem";
import RequestSupport from "./pages/request";
import Opportunities from "./pages/opportunities";
import Donate from "./pages/donate";
import Admin from "./pages/admin";
import Track from "./pages/track";
import ThankYou from "./pages/thank-you";
import WhatsappLog from "./pages/whatsapp-log";
import Login from "./pages/login";
import Cart from "./pages/cart";

const queryClient = new QueryClient();

function Protected({ component: Component }: { component: ComponentType<any> }) {
  const { isAuthenticated } = useAuth();
  if (!isAuthenticated) {
    return <Redirect to="/login" />;
  }
  return <Component />;
}

function Router() {
  return (
    <AppLayout>
      <DocumentTitle />
      <Switch>
        <Route path="/" component={Home} />
        <Route path="/about/:section?" component={About} />
        <Route path="/waqf" component={Waqf} />
        <Route path="/baraem" component={Baraem} />
        <Route path="/request" component={RequestSupport} />
        <Route path="/opportunities" component={Opportunities} />
        <Route path="/donate/:id" component={Donate} />
        <Route path="/cart" component={Cart} />
        <Route path="/login" component={Login} />
        <Route path="/admin">
          <Protected component={Admin} />
        </Route>
        <Route path="/track/:id" component={Track} />
        <Route path="/thank-you/:id" component={ThankYou} />
        <Route path="/whatsapp-log">
          <Protected component={WhatsappLog} />
        </Route>
        <Route component={NotFound} />
      </Switch>
    </AppLayout>
  );
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <LanguageProvider>
        <AuthProvider>
          <CartProvider>
            <TooltipProvider>
              <WouterRouter base={import.meta.env.BASE_URL.replace(/\/$/, "")}>
                <Router />
              </WouterRouter>
              <Toaster />
            </TooltipProvider>
          </CartProvider>
        </AuthProvider>
      </LanguageProvider>
    </QueryClientProvider>
  );
}

export default App;
