import { useEffect, Suspense, lazy } from "react";
import { Switch, Route, useLocation } from "wouter";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { PageLoader } from "@/components/page-loader";
import { useAuth } from "@/hooks/use-auth";
import { isSafeInvitePath, readPendingInvitePath } from "@/lib/invite-return";
import {
  isSafeDebriefPath,
  legacySongPerformancePath,
  loginPathForDebrief,
  rememberPendingDebriefPath,
} from "@/lib/debrief-return";
import { mayRenderMarketingHomepage } from "@/lib/root-surface";
import { usePersistBrowserTimezone } from "@/hooks/use-persist-browser-timezone";
import { PostHogIdentify, usePostHogIdentify } from "@/hooks/use-posthog-identify";
import { FinanceCacheGuard } from "@/components/finance-cache-guard";
import { BandProvider } from "@/contexts/BandContext";
import { initGA } from "./lib/analytics";
import { useAnalytics } from "./hooks/use-analytics";

// Critical pages loaded immediately (landing, login, not-found)
import Landing from "@/pages/landing";
import Login from "@/pages/login";
import NotFound from "@/pages/not-found";

// Lazy load the authenticated app shell (keeps it out of the public landing bundle)
const AppLayout = lazy(() =>
  import("@/components/layout/app-layout").then((m) => ({ default: m.AppLayout }))
);

// Lazy load authenticated pages (loaded only when needed)
const Dashboard = lazy(() => import("@/pages/dashboard"));
const GettingStarted = lazy(() => import("@/pages/getting-started"));
const OnboardingRedirect = lazy(() => import("@/components/onboarding-redirect"));
const Calendar = lazy(() => import("@/pages/calendar"));
const GigHistory = lazy(() => import("@/pages/gig-history"));
const Setlists = lazy(() => import("@/pages/setlists"));
const SetlistEditor = lazy(() => import("@/pages/setlist-editor"));
const Rehearsal = lazy(() => import("@/pages/rehearsal"));
const AiSetlistCoach = lazy(() => import("@/pages/ai-setlist-coach"));
const CoachFeedbackPreview = import.meta.env.DEV
  ? lazy(() => import("@/pages/dev/coach-feedback-preview"))
  : null;
const CoachReviewPreview = import.meta.env.DEV
  ? lazy(() => import("@/pages/dev/coach-review-preview"))
  : null;
const CoachEvalReview = import.meta.env.DEV
  ? lazy(() => import("@/pages/dev/coach-eval-review"))
  : null;
const Songs = lazy(() => import("@/pages/songs"));
const SongDetails = lazy(() => import("@/pages/song-details"));
const Members = lazy(() => import("@/pages/members"));
const Finances = lazy(() => import("@/pages/finances"));
const Settings = lazy(() => import("@/pages/settings"));
const SettingsDeleteAccount = lazy(
  () => import("@/pages/settings-delete-account"),
);
const DeleteAccountPublic = lazy(
  () => import("@/pages/delete-account-public"),
);
const Subscription = lazy(() => import("@/pages/subscription"));
const EventDetails = lazy(() => import("@/pages/event-details"));
const GigDebriefPage = lazy(() => import("@/pages/gig-debrief"));
const Venues = lazy(() => import("@/pages/venues"));
const VenueDetail = lazy(() => import("@/pages/venue-detail"));
const Todos = lazy(() => import("@/pages/todos"));

// Lazy load admin pages (heavy components)
const AdminDashboard = lazy(() => import("@/pages/admin"));

// Lazy load public content pages
const ResetPassword = lazy(() => import("@/pages/reset-password"));
const PrivacyPolicy = lazy(() => import("@/pages/privacy-policy"));
const TermsOfService = lazy(() => import("@/pages/terms-of-service"));
const PricingPage = lazy(() => import("@/pages/pricing"));
const VerificationPending = lazy(() => import("@/pages/verification-pending"));
const AcceptInvitation = lazy(() => import("@/pages/accept-invitation"));
const SmartSongAnalytics = lazy(() => import("@/pages/smart-song-analytics"));
const GreatCoverBandSetlist = lazy(() => import("@/pages/great-cover-band-setlist"));
const WhyEveryBandShouldUseBandMGT = lazy(() => import("@/pages/why-every-band-should-use-bandmgt"));
const Resources = lazy(() => import("@/pages/resources"));
const ResourcesTopicPage = lazy(() => import("@/pages/resources-topic"));
const ResourcesTypeRoute = lazy(() => import("@/pages/resources-type"));
const PreGigChecklistPage = lazy(() => import("@/pages/resources-pre-gig-checklist"));
const GigFeeCalculatorPage = lazy(() => import("@/pages/resources-gig-fee-calculator"));
const PerformanceContractUkPage = lazy(() => import("@/pages/resources-performance-contract-uk"));
const PerformanceContractUsPage = lazy(() => import("@/pages/resources-performance-contract-us"));
const WeddingPlaybookPage = lazy(() => import("@/pages/resources-wedding-playbook"));
const SetlistEnergyPlannerPage = lazy(() => import("@/pages/resources-setlist-energy-planner"));
const AiSetlistCoachGuidePage = lazy(() => import("@/pages/resources-ai-setlist-coach"));
const AiSetlistComparePage = lazy(() => import("@/pages/resources-ai-setlist-compare"));
const VenueFollowUpPackPage = lazy(() => import("@/pages/resources-venue-follow-up"));
const About = lazy(() => import("@/pages/about"));
const AppBeta = lazy(() => import("@/pages/app-beta"));
const AppLanding = lazy(() => import("@/pages/app-landing"));

// Blog pages (accessible to all users)
const Blog = lazy(() => import("@/pages/blog"));
const BlogArticle = lazy(() => import("@/pages/blog-article"));
const WhatsNew = lazy(() => import("@/pages/whats-new"));

// In-app changelog (authenticated only)
const Changelog = lazy(() => import("@/pages/changelog"));

function InviteReturnGate() {
  const [, navigate] = useLocation();
  useEffect(() => {
    const path = readPendingInvitePath();
    if (path) navigate(path, { replace: true });
  }, [navigate]);
  return <PageLoader />;
}

function DebriefLoginRedirect({ path }: { path: string }) {
  const [, navigate] = useLocation();
  useEffect(() => {
    const loginPath = loginPathForDebrief(path);
    if (loginPath) navigate(loginPath, { replace: true });
  }, [navigate, path]);
  return <PageLoader />;
}

function Router() {
  const { authStatus } = useAuth();
  const [location, navigate] = useLocation();
  const pathname = location.split("?")[0] || "/";
  const legacyDebrief = typeof window === "undefined"
    ? null
    : legacySongPerformancePath(window.location.pathname, window.location.hash);
  usePersistBrowserTimezone();
  useEffect(() => {
    if (!legacyDebrief || authStatus === "pending") return;
    rememberPendingDebriefPath(legacyDebrief);
    const target = authStatus === "authenticated"
      ? legacyDebrief
      : loginPathForDebrief(legacyDebrief);
    if (!target) return;
    window.history.replaceState(null, "", target);
    navigate(target, { replace: true });
  }, [authStatus, legacyDebrief, navigate]);
  
  // Identify users in PostHog when authenticated
  usePostHogIdentify();
  
  // Track page views when routes change
  useAnalytics();

  if (isSafeInvitePath(pathname)) {
    return (
      <Suspense fallback={<PageLoader />}>
        <AcceptInvitation />
      </Suspense>
    );
  }

  if (authStatus === "pending" || legacyDebrief) {
    return <PageLoader />;
  }

  if (authStatus !== "authenticated" && isSafeDebriefPath(pathname)) {
    rememberPendingDebriefPath(pathname);
    return <DebriefLoginRedirect path={pathname} />;
  }

  const pendingInvite = readPendingInvitePath();
  if (!mayRenderMarketingHomepage({
    authStatus,
    pathname,
    pendingInvitePath: pendingInvite,
  }) && pathname === "/" && authStatus === "anonymous") {
    return <InviteReturnGate />;
  }

  if (authStatus !== "authenticated") {
    return (
      <Suspense fallback={<PageLoader />}>
        <Switch>
          <Route path="/" component={Landing} />
          <Route path="/login" component={Login} />
          <Route path="/reset-password" component={ResetPassword} />
          <Route path="/privacy-policy" component={PrivacyPolicy} />
          <Route path="/terms-of-service" component={TermsOfService} />
          <Route path="/delete-account" component={DeleteAccountPublic} />
          <Route path="/verification-pending" component={VerificationPending} />
          <Route path="/blog" component={Blog} />
          <Route path="/blog/:slug" component={BlogArticle} />
          <Route path="/whats-new" component={WhatsNew} />
          <Route path="/resources" component={Resources} />
          <Route path="/resources/topics/:slug" component={ResourcesTopicPage} />
          <Route path="/resources/checklists/pre-gig-checklist" component={PreGigChecklistPage} />
          <Route path="/resources/tools/band-gig-fee-calculator" component={GigFeeCalculatorPage} />
          <Route path="/resources/templates/performance-contract-uk" component={PerformanceContractUkPage} />
          <Route path="/resources/templates/performance-contract-us" component={PerformanceContractUsPage} />
          <Route path="/resources/guides/wedding-booking-playbook" component={WeddingPlaybookPage} />
          <Route path="/resources/tools/setlist-energy-planner" component={SetlistEnergyPlannerPage} />
          <Route path="/resources/guides/ai-setlist-coach" component={AiSetlistCoachGuidePage} />
          <Route path="/resources/compare/ai-setlist-tools" component={AiSetlistComparePage} />
          <Route path="/resources/templates/venue-follow-up-pack" component={VenueFollowUpPackPage} />
          <Route path="/resources/guides" component={ResourcesTypeRoute} />
          <Route path="/resources/templates" component={ResourcesTypeRoute} />
          <Route path="/resources/tools" component={ResourcesTypeRoute} />
          <Route path="/resources/checklists" component={ResourcesTypeRoute} />
          <Route path="/resources/compare" component={ResourcesTypeRoute} />
          <Route path="/resources/analytics/smart-song-analytics" component={SmartSongAnalytics} />
          <Route path="/resources/setlist-strategy/great-cover-band-setlist" component={GreatCoverBandSetlist} />
          <Route path="/resources/band-management/why-every-band-should-use-bandmgt" component={WhyEveryBandShouldUseBandMGT} />
          <Route path="/about" component={About} />
          <Route path="/app" component={AppLanding} />
          <Route path="/pricing" component={PricingPage} />
          <Route path="/app-beta" component={AppBeta} />
          <Route path="/smart-song-analytics" component={() => { window.location.href = '/resources/analytics/smart-song-analytics'; return null; }} />
          <Route path="/what-makes-great-cover-band-setlist" component={() => { window.location.href = '/resources/setlist-strategy/great-cover-band-setlist'; return null; }} />
          {CoachFeedbackPreview ? (
            <Route path="/dev/coach-feedback" component={CoachFeedbackPreview} />
          ) : null}
          {CoachReviewPreview ? (
            <Route path="/dev/coach-review" component={CoachReviewPreview} />
          ) : null}
          {CoachEvalReview ? (
            <Route path="/dev/coach-eval" component={CoachEvalReview} />
          ) : null}
          <Route component={NotFound} />
        </Switch>
      </Suspense>
    );
  }

  return (
    <BandProvider>
      <PostHogIdentify />
      <FinanceCacheGuard />
      <Suspense fallback={<PageLoader />}>
        <Switch>
          {/* Full-screen routes — no app layout */}
          <Route path="/setlists/:id/rehearse" component={Rehearsal} />
          <Route path="/events/:id/debrief" component={GigDebriefPage} />
          <Route path="/setlists/:id/coach" component={AiSetlistCoach} />
          {CoachFeedbackPreview ? (
            <Route path="/dev/coach-feedback" component={CoachFeedbackPreview} />
          ) : null}
          {CoachReviewPreview ? (
            <Route path="/dev/coach-review" component={CoachReviewPreview} />
          ) : null}
          {CoachEvalReview ? (
            <Route path="/dev/coach-eval" component={CoachEvalReview} />
          ) : null}
          <Route path="/delete-account" component={DeleteAccountPublic} />
          <Route path="/privacy-policy" component={PrivacyPolicy} />
          <Route path="/terms-of-service" component={TermsOfService} />
          <Route path="/pricing" component={PricingPage} />
          {/* All other routes get the app layout */}
          <Route>
        <AppLayout>
          <Suspense fallback={<PageLoader />}>
            <Switch>
            <Route path="/" component={OnboardingRedirect} />
            <Route path="/dashboard" component={Dashboard} />
            <Route path="/getting-started" component={GettingStarted} />
            <Route path="/calendar" component={Calendar} />
            <Route path="/gig-history" component={GigHistory} />
            <Route path="/setlists" component={Setlists} />
            <Route path="/setlists/:id" component={SetlistEditor} />
            <Route path="/events/:id" component={EventDetails} />
            <Route path="/songs" component={Songs} />
            <Route path="/songs/:bandSongId" component={SongDetails} />
            <Route path="/bands/:bandId/songs" component={Songs} />
            <Route path="/members" component={Members} />
            <Route path="/todos" component={Todos} />
            <Route path="/venues" component={Venues} />
            <Route path="/venues/:id" component={VenueDetail} />
            <Route path="/finances" component={Finances} />
            <Route path="/settings/delete-account" component={SettingsDeleteAccount} />
            <Route path="/settings" component={Settings} />
            <Route path="/subscription" component={Subscription} />
            <Route path="/blog" component={Blog} />
            <Route path="/blog/:slug" component={BlogArticle} />
            <Route path="/whats-new" component={WhatsNew} />
            <Route path="/resources" component={Resources} />
            <Route path="/resources/topics/:slug" component={ResourcesTopicPage} />
            <Route path="/resources/checklists/pre-gig-checklist" component={PreGigChecklistPage} />
            <Route path="/resources/tools/band-gig-fee-calculator" component={GigFeeCalculatorPage} />
            <Route path="/resources/templates/performance-contract-uk" component={PerformanceContractUkPage} />
            <Route path="/resources/templates/performance-contract-us" component={PerformanceContractUsPage} />
            <Route path="/resources/guides/wedding-booking-playbook" component={WeddingPlaybookPage} />
            <Route path="/resources/tools/setlist-energy-planner" component={SetlistEnergyPlannerPage} />
            <Route path="/resources/guides/ai-setlist-coach" component={AiSetlistCoachGuidePage} />
            <Route path="/resources/compare/ai-setlist-tools" component={AiSetlistComparePage} />
            <Route path="/resources/templates/venue-follow-up-pack" component={VenueFollowUpPackPage} />
            <Route path="/resources/guides" component={ResourcesTypeRoute} />
            <Route path="/resources/templates" component={ResourcesTypeRoute} />
            <Route path="/resources/tools" component={ResourcesTypeRoute} />
            <Route path="/resources/checklists" component={ResourcesTypeRoute} />
            <Route path="/resources/compare" component={ResourcesTypeRoute} />
            <Route path="/resources/analytics/smart-song-analytics" component={SmartSongAnalytics} />
            <Route path="/resources/setlist-strategy/great-cover-band-setlist" component={GreatCoverBandSetlist} />
            <Route path="/resources/band-management/why-every-band-should-use-bandmgt" component={WhyEveryBandShouldUseBandMGT} />
            <Route path="/about" component={About} />
            <Route path="/app" component={AppLanding} />
            <Route path="/app-beta" component={AppBeta} />
            <Route path="/changelog" component={Changelog} />
            <Route path="/admin/overview" component={AdminDashboard} />
            <Route path="/admin/features" component={AdminDashboard} />
            <Route path="/admin/activation" component={AdminDashboard} />
            <Route path="/admin/product-usage" component={AdminDashboard} />
            <Route path="/admin/apps" component={AdminDashboard} />
            <Route path="/admin/bands" component={AdminDashboard} />
            <Route path="/admin/users" component={AdminDashboard} />
            <Route path="/admin/songs" component={AdminDashboard} />
            <Route path="/admin/venues" component={AdminDashboard} />
            <Route path="/admin/catalogue" component={AdminDashboard} />
            <Route path="/admin/website" component={AdminDashboard} />
            <Route path="/admin" component={AdminDashboard} />
            <Route path="/smart-song-analytics" component={SmartSongAnalytics} />
            <Route path="/what-makes-great-cover-band-setlist" component={GreatCoverBandSetlist} />
            <Route path="/reset-password" component={ResetPassword} />
            <Route component={() => { const [, setLocation] = useLocation(); useEffect(() => setLocation('/dashboard'), []); return null; }} />
          </Switch>
          </Suspense>
        </AppLayout>
          </Route>
        </Switch>
      </Suspense>
    </BandProvider>
  );
}

function App() {
  // Defer Google Analytics initialization to improve initial page load  
  useEffect(() => {
    // Defer GA loading until after critical content is rendered
    const timeoutId = setTimeout(() => {
      if (!import.meta.env.VITE_GA_MEASUREMENT_ID) {
        console.warn('Missing required Google Analytics key: VITE_GA_MEASUREMENT_ID');
      } else {
        initGA();
      }
    }, 2000); // Load after 2 seconds to prioritize critical content

    return () => clearTimeout(timeoutId);
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <Toaster />
      <Router />
    </QueryClientProvider>
  );
}

export default App;
