import { Switch, Route, Redirect, useLocation } 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 { useAuth } from "@/hooks/use-auth";
import Dashboard from "@/pages/dashboard";
import { StorageErrorBoundary } from "@/components/storage-error-boundary";
import Login from "@/pages/login";
import Register from "@/pages/register";
import Tracking from "@/pages/tracking";
import Progress from "@/pages/progress";
import Profile from "@/pages/profile";
import CalculatorHistory from "@/pages/calculator-history";
import PeptideCalculatorPage from "@/pages/peptide-calculator";
import PeptideProtocolsPage from "@/pages/peptide-protocols";
import LabTrends from "@/pages/lab-trends-accordion";
import HealthGoals from "@/pages/health-goals";
import Schedules from "@/pages/schedules";
import Insights from "@/pages/insights";
import AnalyticsDashboard from "@/pages/analytics-dashboard";
import AIHealthChat from "@/pages/ai-health-chat";
import HealthRisks from "@/pages/health-risks";
import NotificationSettings from "@/pages/notification-settings";
import NotificationsPage from "@/pages/notifications";
import OfflineSyncManagement from "@/pages/offline-sync-management";
import Activities from "@/pages/activities";
import ConnectedDevices from "@/pages/devices";
import DeviceSync from "@/pages/device-sync";
import Marketplace from "@/pages/marketplace";
import NutritionPage from "@/pages/nutrition";
import WaterIntakePage from "@/pages/water-intake";
import SupplementsPage from "@/pages/supplements";
import { MedicationsPage } from "@/pages/medications";
import { SupplementsAndMedications } from "@/pages/supplements-medications";
import SkippedDosesPage from "@/pages/skipped-doses";
import AdminDashboard from "@/pages/admin-dashboard";
import AdminUserManagement from "@/pages/admin-user-management";
import AdminPHIAuditLogs from "@/pages/admin-phi-audit-logs";
import AdminActivityPage from "@/pages/admin-activity";
import AdminEmailCampaigns from "@/pages/admin-email-campaigns";
import LogoutPage from "@/pages/logout";
import NotFound from "@/pages/not-found";
import Checkout from "@/pages/checkout";
import Subscribe from "@/pages/subscribe";
import PaymentSuccess from "@/pages/payment-success";
import SubscriptionSuccess from "@/pages/subscription-success";
import MarketingPage from "@/pages/marketing";
import PublicPeptideCalculatorPage from "@/pages/public-peptide-calculator";
import PublicProtocolsPage from "@/pages/public-protocols";
import ProtocolDetailPage from "@/pages/protocol-detail";
import BPC157Page from "@/pages/bpc-157";
import PeptideProfilePage from "@/pages/peptide-profile";
import PeptidesHubPage from "@/pages/peptides-hub";
import PeptidesCategoryPage from "@/pages/peptides-category";
import ComparisonPage from "@/pages/comparison-page";
import AffiliateDashboardEnhanced from "@/pages/affiliate-dashboard-enhanced";
import AffiliatePayouts from "@/pages/affiliate-payouts";
import PricingPage from "@/pages/pricing";
import CoachDashboard from "@/pages/CoachDashboard";
import ClinicDashboard from "@/pages/ClinicDashboard";
import B2BOverview from "@/pages/B2BOverview";
import AddClinic from "@/pages/AddClinic";
import AddCoach from "@/pages/AddCoach";
import PrivacyPolicy from "@/pages/privacy-policy";
import TermsOfService from "@/pages/terms-of-service";
import Upgrade from "@/pages/upgrade";
import AccountSettings from "@/pages/account-settings";
import Onboarding from "@/pages/onboarding";
import ResetPasswordPage from "@/pages/reset-password";
import Support from "@/pages/support";
import Inventory from "@/pages/inventory";
import Vendors from "@/pages/vendors";
import PartnersPage from "@/pages/partners";
import AdminPartnerApplications from "@/pages/admin-partner-applications";
import AdminApplications from "@/pages/admin-applications";
import AdminVendors from "@/pages/admin-vendors";
import AdminVendorDetail from "@/pages/admin-vendor-detail";
import AffiliateDisclosure from "@/pages/affiliate-disclosure";
import Achievements from "@/pages/achievements";
import WellnessPostcardsPage from "@/pages/wellness-postcards";
import ProOptimizerPage from "@/pages/pro-optimizer";
import ProShareLinksPage from "@/pages/pro-share-links";
import SharedViewPage from "@/pages/shared-view";
import LinksPage from "@/pages/links";
import FaqPage from "@/pages/faq";
import FounderCohortPage from "@/pages/founder-cohort";
import { OfflineStatusIndicator } from "@/components/offline-status";
import { NotificationSetupGuide } from "@/components/notification-setup-guide";
import { SimpleContextualInsights } from "@/components/simple-contextual-insights";
import { ConsentVerification } from "@/components/consent-verification";
import { ContextualInsightsProvider } from "@/hooks/use-contextual-insights";
import { PaymentMethodBanner } from "@/components/payment-method-banner";
import { initializeUserTimezone } from "@/lib/timezone";
import { useEffect, useState } from "react";

function AuthenticatedApp() {
  const { user, isCoach } = useAuth();
  const [showConsentVerification, setShowConsentVerification] = useState(false);
  const [viewMode, setViewMode] = useState<'coach' | 'patient'>('patient');

  

  // Check if user needs consent verification
  useEffect(() => {
    if (user && (!user.medicalConsent || !user.researchConsent || !user.termsConsent || !user.consentTimestamp)) {
      setShowConsentVerification(true);
    }
  }, [user]);

  // Auto-set coach view mode if user is a coach
  useEffect(() => {
    if (isCoach) {
      setViewMode('coach');
    }
  }, [isCoach]);

  // Force onboarding for new users — they must complete their profile
  // before reaching the dashboard. Without this, users land on an empty
  // dashboard with no personalization and churn immediately.
  if (user && !user.onboardingComplete) {
    return <Onboarding />;
  }

  if (showConsentVerification) {
    return <ConsentVerification onComplete={() => setShowConsentVerification(false)} />;
  }

  // Determine if user should see coach dashboard (either auto-routing or manual switch)
  const shouldShowCoachDashboard = isCoach && viewMode === 'coach';

  return (
    <>
      <PaymentMethodBanner />
      <Switch>
        <Route path="/" component={() => shouldShowCoachDashboard ? 
          <CoachDashboard onSwitchToPatientView={() => setViewMode('patient')} /> : 
          <StorageErrorBoundary>
            <Dashboard onSwitchToCoachView={isCoach ? () => setViewMode('coach') : undefined} />
          </StorageErrorBoundary>
        } />
        <Route path="/dashboard" component={() => <Dashboard onSwitchToCoachView={isCoach ? () => setViewMode('coach') : undefined} />} />
        <Route path="/tracking" component={Tracking} />
        <Route path="/health" component={Tracking} />
        <Route path="/progress" component={Progress} />
        <Route path="/profile" component={Profile} />
        <Route path="/achievements" component={Achievements} />
        <Route path="/wellness-postcards" component={WellnessPostcardsPage} />
        <Route path="/calculator-history" component={CalculatorHistory} />
        <Route path="/calculator" component={PeptideCalculatorPage} />
        <Route path="/peptide-calculator" component={PeptideCalculatorPage} />
        <Route path="/peptide-protocols" component={PeptideProtocolsPage} />
        {/* Public SEO peptide pages — accessible to authenticated users too
            so the library is reachable from the in-app nav. Same route
            ordering rules as the unauthenticated router below. */}
        <Route path="/peptides" component={PeptidesHubPage} />
        <Route path="/peptides/categories/:category" component={PeptidesCategoryPage} />
        <Route path="/peptides/:slug" component={PeptideProfilePage} />
        <Route path="/compare/:pair" component={ComparisonPage} />
        <Route path="/protocols/:id" component={ProtocolDetailPage} />
        <Route path="/protocols" component={PeptideProtocolsPage} />
        <Route path="/lab-trends" component={LabTrends} />
        <Route path="/health-goals" component={HealthGoals} />
        <Route path="/schedules" component={Schedules} />
        <Route path="/inventory" component={Inventory} />
        <Route path="/vendors" component={Vendors} />
        <Route path="/insights" component={Insights} />
        <Route path="/analytics" component={AnalyticsDashboard} />
        <Route path="/ai-chat" component={AIHealthChat} />
        <Route path="/ai-health-chat" component={AIHealthChat} />
        <Route path="/health-risks" component={HealthRisks} />
        <Route path="/nutrition" component={NutritionPage} />
        <Route path="/water-intake" component={WaterIntakePage} />
        <Route path="/supplements" component={SupplementsPage} />
        <Route path="/medications" component={MedicationsPage} />
        <Route path="/supplements-medications" component={SupplementsAndMedications} />
        <Route path="/skipped-doses" component={SkippedDosesPage} />
        <Route path="/notifications" component={NotificationsPage} />
        <Route path="/notification-settings" component={NotificationSettings} />
        <Route path="/offline-sync-management" component={OfflineSyncManagement} />
        <Route path="/activities" component={Activities} />
        <Route path="/devices" component={ConnectedDevices} />
        <Route path="/device-sync" component={DeviceSync} />
        <Route path="/marketplace" component={Marketplace} />
        <Route path="/admin" component={() => {
          console.log('🔴 [ROUTING DEBUG] Admin route accessed');
          console.log('🔴 [ROUTING DEBUG] Current user:', user);
          console.log('🔴 [ROUTING DEBUG] User role:', user?.role);
          return <AdminDashboard />;
        }} />
        <Route path="/admin/affiliate-payouts" component={AffiliatePayouts} />
        <Route path="/admin/partner-applications" component={AdminPartnerApplications} />
        <Route path="/admin/applications" component={AdminApplications} />
        <Route path="/admin/vendors" component={AdminVendors} />
        <Route path="/admin/vendors/:id" component={AdminVendorDetail} />
        <Route path="/admin/user-management" component={AdminUserManagement} />
        <Route path="/admin/phi-audit-logs" component={AdminPHIAuditLogs} />
        <Route path="/admin/activity" component={AdminActivityPage} />
        <Route path="/admin/email-campaigns" component={AdminEmailCampaigns} />
        <Route path="/admin/add-clinic" component={AddClinic} />
        <Route path="/admin/add-coach" component={AddCoach} />
        <Route path="/checkout" component={Checkout} />
        <Route path="/subscribe" component={Subscribe} />
        <Route path="/upgrade" component={Upgrade} />
        <Route path="/account" component={AccountSettings} />
        <Route path="/account-settings" component={AccountSettings} />
        <Route path="/support" component={Support} />
        <Route path="/payment-success" component={PaymentSuccess} />
        <Route path="/subscription-success" component={SubscriptionSuccess} />
        <Route path="/marketing" component={MarketingPage} />
        <Route path="/pricing" component={PricingPage} />
        <Route path="/affiliate" component={AffiliateDashboardEnhanced} />
        <Route path="/partners" component={PartnersPage} />
        <Route path="/pro/optimizer" component={ProOptimizerPage} />
        <Route path="/pro/share-links" component={ProShareLinksPage} />
        <Route path="/shared/:token" component={SharedViewPage} />
        <Route path="/coach-dashboard" component={() => <CoachDashboard onSwitchToPatientView={() => setViewMode('patient')} />} />
        <Route path="/clinic-dashboard" component={ClinicDashboard} />
        <Route path="/b2b" component={B2BOverview} />
        <Route path="/privacy" component={PrivacyPolicy} />
        <Route path="/privacy-policy" component={PrivacyPolicy} />
        <Route path="/terms" component={TermsOfService} />
        <Route path="/terms-of-service" component={TermsOfService} />
        <Route path="/affiliate-disclosure" component={AffiliateDisclosure} />
        <Route path="/links" component={LinksPage} />
        <Route path="/faq" component={FaqPage} />
        <Route path="/founder-cohort" component={FounderCohortPage} />
        <Route path="/onboarding" component={Onboarding} />
        <Route path="/logout" component={LogoutPage} />
        <Route path="/register"><Redirect to="/dashboard" /></Route>
        <Route path="/login"><Redirect to="/dashboard" /></Route>
        <Route component={NotFound} />
      </Switch>
      <OfflineStatusIndicator />
      <NotificationSetupGuide />
    </>
  );
}

function ScrollToTop() {
  const [location] = useLocation();
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [location]);
  return null;
}

function UnauthenticatedApp() {
  return (
    <>
    <ScrollToTop />
    <Switch>
      <Route path="/" component={MarketingPage} />
      <Route path="/marketing" component={MarketingPage} />
      <Route path="/pricing" component={PricingPage} />
      <Route path="/calculator" component={PublicPeptideCalculatorPage} />
      <Route path="/peptide-calculator" component={PublicPeptideCalculatorPage} />
      <Route path="/bac-water-calculator" component={PublicPeptideCalculatorPage} />
      <Route path="/peptide-dose-calculator" component={PublicPeptideCalculatorPage} />
      {/*
        Programmatic SEO: /peptides hub, category hubs, and the
        dynamic /peptides/:slug route (86 peptides, one template).
        Order matters — the dynamic route MUST come after /peptides
        itself and after /peptides/categories/:category, otherwise
        wouter's Switch resolves "peptides" or "categories" as a slug
        and never reaches the hub components.

        The legacy /peptides/bpc-157 hardcoded route is intentionally
        NOT registered here — it's handled by the dynamic [slug] route
        below, which resolves "bpc-157" against PEPTIDE_PROTOCOLS_DATA
        and renders the shared PeptideSeoPage template. See
        client/src/pages/bpc-157.tsx for the legacy implementation
        (now unused from public routing but still imported for the
        authenticated flow at line ~230).
      */}
      <Route path="/peptides" component={PeptidesHubPage} />
      <Route path="/peptides/categories/:category" component={PeptidesCategoryPage} />
      <Route path="/peptides/:slug" component={PeptideProfilePage} />
      <Route path="/compare/:pair" component={ComparisonPage} />
      <Route path="/shared/:token" component={SharedViewPage} />
      <Route path="/protocols/:id" component={ProtocolDetailPage} />
      <Route path="/protocols" component={PublicProtocolsPage} />
      <Route path="/affiliate" component={AffiliateDashboardEnhanced} />
      <Route path="/partners" component={PartnersPage} />
      {/*
        /clinic-dashboard and /coach-dashboard are admin CRUD UIs — NOT
        marketing pages. They were previously in the unauthenticated router
        which let any visitor see the "Create New Clinic" form and leaked
        the admin data model. Server-side routes are auth-gated via
        requireAuth so no data could actually be written, but the UX was
        wrong and exposed internal structure. The authenticated router at
        line ~190 still has these routes for logged-in admins/clinicians.
        Unauthenticated visitors who hit these URLs now fall through to
        the marketing page catch-all below.

        /b2b remains public as a marketing page, but its CTAs are rewritten
        to route to a Contact Us mailto rather than to these dashboards —
        see B2BOverview.tsx. Clinic tier is sold via outreach + BAA per
        the pricing strategy doc, not self-serve.
      */}
      <Route path="/b2b" component={B2BOverview} />
      <Route path="/privacy" component={PrivacyPolicy} />
      <Route path="/privacy-policy" component={PrivacyPolicy} />
      <Route path="/terms" component={TermsOfService} />
      <Route path="/terms-of-service" component={TermsOfService} />
      <Route path="/affiliate-disclosure" component={AffiliateDisclosure} />
      <Route path="/links" component={LinksPage} />
      <Route path="/faq" component={FaqPage} />
      <Route path="/founder-cohort" component={FounderCohortPage} />
      <Route path="/login" component={Login} />
      <Route path="/register" component={Register} />
      <Route path="/reset-password" component={ResetPasswordPage} />
      <Route path="/logout" component={LogoutPage} />
      <Route component={MarketingPage} />
    </Switch>
    </>
  );
}

function AppContent() {
  const { user, isAuthenticated, isLoading } = useAuth();
  
  console.log('🔴 [APP DEBUG] Auth state:', { isAuthenticated, isLoading, user: user?.username, role: user?.role });

  // Initialize user timezone detection on app load
  useEffect(() => {
    initializeUserTimezone();
  }, []);

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-neutral-50">
        <div className="animate-pulse flex flex-col items-center">
          <div className="w-12 h-12 bg-primary rounded-full mb-4"></div>
          <div className="text-lg font-medium text-neutral-600">Loading Alethea...</div>
        </div>
      </div>
    );
  }

  return isAuthenticated ? <AuthenticatedApp /> : <UnauthenticatedApp />;
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <TooltipProvider>
        <ContextualInsightsProvider>
          <Toaster />
          <AppContent />
        </ContextualInsightsProvider>
      </TooltipProvider>
    </QueryClientProvider>
  );
}

export default App;
