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 { LanguageProvider } from "@/components/language-provider";
import { OnboardingProvider } from "@/components/onboarding/onboarding-provider";
import { OnboardingTooltip } from "@/components/onboarding/onboarding-tooltip";
import { useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useAdminAuth } from "@/hooks/useAdminAuth";

import NotFound from "@/pages/not-found";
import Landing from "@/pages/landing";
import AboutPage from "@/pages/about";
import ServicesPage from "@/pages/services";
import ContactPage from "@/pages/contact";
import AuthPage from "@/pages/auth";
import Dashboard from "@/pages/dashboard";
import Teams from "@/pages/teams";
import TeamDetailPage from "@/pages/team-detail-working";
import Players from "@/pages/players";
import PlayerRegistrationFixed from "@/pages/player-registration-fixed";
import Onboarding from "@/pages/onboarding";
import Help from "@/pages/help";
import Coaches from "@/pages/coaches";
import CoachDetail from "@/pages/coach-detail";
import LanguageSettings from "@/pages/language-settings";
import SecurityPage from "@/pages/security";
import Calendar from "@/pages/calendar";
import SettingsPage from "@/pages/Settings";

import ProfilePage from "@/pages/profile";
import Admin from "@/pages/admin";
import AdminLogin from "@/pages/admin-login";
import AdminUsers from "@/pages/admin-users";

import Tournaments from "@/pages/tournaments";
import Training from "@/pages/training";
import Leagues from "@/pages/leagues";
import Fixtures from "@/pages/fixtures";
import Venues from "@/pages/venues";
import Transfers from "@/pages/transfers";

import ChallengesPage from "@/pages/challenges";
import SubscriptionsPage from "@/pages/subscriptions";
import CoachingFeedbackPage from "@/pages/coaching-feedback";
import Payments from "@/pages/payments";
import SuperAdminPage from "@/pages/superadmin";
import CpanelInstallation from "@/pages/cpanel-installation";

import SystemDebug from "@/pages/system-debug";
import RosterPage from "@/pages/roster-fixed";
import VerifyEmail from "@/pages/verify-email";

import ThemeSettings from "@/pages/theme-settings";
import FormBuilder from "@/pages/form-builder";
import PaymentGateways from "@/pages/payment-gateways";
import BrandingSettingsPage from "@/pages/branding-settings";

import Proposal from "@/pages/proposal";
import NotificationsPage from "@/pages/notifications";
import { Reports } from "@/pages/Reports";
import { AuditLogs } from "@/pages/AuditLogs";
import ModuleManagement from "@/pages/module-management";
import InstallationPage from "@/pages/installation";

import Header from "@/components/layout/header";
import Sidebar from "@/components/layout/sidebar";
import { BackToTop } from "@/components/ui/back-to-top";
import Footer from "@/components/layout/footer";
import { TutorialLauncher } from "@/components/tutorials/tutorial-launcher";
function AppLayoutWithSidebar() {
  const { isAuthenticated } = useAuth();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);

  const handleSidebarToggle = () => {
    setIsSidebarCollapsed(!isSidebarCollapsed);
  };

  return (
    <>
      <div className="min-h-screen bg-background">
        <Header />
        <Sidebar 
          isOpen={true} 
          isCollapsed={isSidebarCollapsed}
          onToggle={handleSidebarToggle}
        />
        <main className={`pt-20 min-h-screen transition-all duration-300 ${isSidebarCollapsed ? 'ml-16' : 'ml-64'}`}>
          <Switch>
            <Route path="/" component={Dashboard} />
            <Route path="/dashboard" component={Dashboard} />
            <Route path="/teams" component={Teams} />
            <Route path="/teams/:id" component={TeamDetailPage} />
            <Route path="/players" component={Players} />
            <Route path="/players/register" component={PlayerRegistrationFixed} />
            <Route path="/coaches" component={Coaches} />
            <Route path="/coaches/:id" component={CoachDetail} />
            <Route path="/roster" component={RosterPage} />

            <Route path="/language-settings" component={LanguageSettings} />
            <Route path="/security" component={SecurityPage} />
            <Route path="/branding-settings" component={BrandingSettingsPage} />
            <Route path="/theme-settings" component={ThemeSettings} />
            <Route path="/form-builder" component={FormBuilder} />
            <Route path="/payment-gateways" component={PaymentGateways} />
            <Route path="/calendar" component={Calendar} />
            <Route path="/settings" component={SettingsPage} />
            <Route path="/profile" component={ProfilePage} />
            <Route path="/admin" component={Admin} />
            <Route path="/admin-users" component={AdminUsers} />
            <Route path="/tournaments" component={Tournaments} />
            <Route path="/leagues" component={Leagues} />
            <Route path="/fixtures" component={Fixtures} />
            <Route path="/venues" component={Venues} />
            <Route path="/transfers" component={Transfers} />
            <Route path="/training" component={Training} />


            <Route path="/challenges" component={ChallengesPage} />
            <Route path="/subscriptions" component={SubscriptionsPage} />
            <Route path="/payments" component={Payments} />
            <Route path="/coaching-feedback" component={CoachingFeedbackPage} />
            <Route path="/superadmin" component={SuperAdminPage} />
            <Route path="/module-management" component={ModuleManagement} />
            <Route path="/cpanel-installation" component={CpanelInstallation} />
            <Route path="/system-debug" component={SystemDebug} />
            <Route path="/onboarding" component={Onboarding} />

            <Route path="/help" component={Help} />
            <Route path="/proposal" component={Proposal} />
            <Route path="/verify-email" component={VerifyEmail} />
            
            <Route path="/notifications" component={NotificationsPage} />
            <Route path="/reports" component={Reports} />
            <Route path="/audit-logs" component={AuditLogs} />
            
            <Route component={NotFound} />
          </Switch>
        </main>
        <div className={`transition-all duration-300 ${isSidebarCollapsed ? 'ml-16' : 'ml-64'}`}>
          <Footer />
        </div>
        <BackToTop />
      </div>
      
      {/* Onboarding Tooltip */}
      <OnboardingTooltip />
      
      {/* Interactive Tutorial Launcher */}
      {isAuthenticated && <TutorialLauncher />}
    </>
  );
}

function Router() {
  const { isAuthenticated, isLoading } = useAuth();
  const { isAdminAuthenticated, isLoading: isAdminLoading } = useAdminAuth();

  // Debug mode: temporarily bypass authentication for development
  const isDevelopment = import.meta.env.DEV;
  const forceAuthenticated = isDevelopment && (
    window.location.pathname.includes('/tournaments') ||
    window.location.pathname.includes('/subscriptions')
  );

  if (isLoading && !forceAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <Switch>
      {/* Installation route - accessible without authentication */}
      <Route path="/installation" component={InstallationPage} />

      {/* Admin login route - separate from main app */}
      <Route path="/admin-login" component={AdminLogin} />

      {/* Main app routes with local authentication */}
      {!isAuthenticated && !forceAuthenticated ? (
        <>
          <Route path="/" component={Landing} />
          <Route path="/about" component={AboutPage} />
          <Route path="/services" component={ServicesPage} />
          <Route path="/contact" component={ContactPage} />
          <Route path="/proposal" component={Proposal} />
          <Route path="/auth" component={AuthPage} />
          <Route component={NotFound} />
        </>
      ) : (
        <>
          <Route path="*" component={AppLayoutWithSidebar} />
        </>
      )}
    </Switch>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <LanguageProvider>
        <TooltipProvider>
          <OnboardingProvider>
            <Router />
            <Toaster />
          </OnboardingProvider>
        </TooltipProvider>
      </LanguageProvider>
    </QueryClientProvider>
  );
}