import { Switch, Route } from "wouter";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { AuthProvider } from "@/hooks/use-auth";
import { CartProvider } from "@/hooks/use-cart";
import MobileBottomNav from "@/components/layout/mobile-bottom-nav";
import CartSidebar from "@/components/cart/cart-sidebar";
import { useState } from "react";
import ErrorBoundary from "@/components/common/error-boundary";

import Home from "@/pages/home";
import Auth from "@/pages/auth";
import ProductDetail from "@/pages/product-detail";
import StoreDetail from "@/pages/store-detail";
import Cart from "@/pages/cart";
import Checkout from "@/pages/checkout";
import Profile from "@/pages/profile";
import Orders from "@/pages/orders";
import AdminDev from "@/pages/admin-dev";
import AdminSeller from "@/pages/admin-seller";
import SearchResults from "@/pages/search-results";
import NotFound from "@/pages/not-found";

function Router() {
  return (
    <Switch>
      <Route path="/" component={Home} />
      <Route path="/auth" component={Auth} />
      <Route path="/product/:id" component={ProductDetail} />
      <Route path="/store/:id" component={StoreDetail} />
      <Route path="/cart" component={Cart} />
      <Route path="/checkout" component={Checkout} />
      <Route path="/profile" component={Profile} />
      <Route path="/orders" component={Orders} />
      <Route path="/search" component={SearchResults} />
      <Route path="/admin-prospective=dev" component={AdminDev} />
      <Route path="/admin-prospective=seller" component={AdminSeller} />
      <Route component={NotFound} />
    </Switch>
  );
}

function App() {
  const [isCartOpen, setIsCartOpen] = useState(false);

  // Make cart open/close globally accessible
  if (typeof window !== 'undefined') {
    (window as any).openCart = () => setIsCartOpen(true);
    (window as any).closeCart = () => setIsCartOpen(false);
  }

  return (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <AuthProvider>
          <CartProvider>
            <TooltipProvider>
              <Toaster />
              <Router />
              <MobileBottomNav />
              <CartSidebar isOpen={isCartOpen} onClose={() => setIsCartOpen(false)} />
            </TooltipProvider>
          </CartProvider>
        </AuthProvider>
      </QueryClientProvider>
    </ErrorBoundary>
  );
}

export default App;
