import { Suspense, lazy, useEffect } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import { HelmetProvider } from "react-helmet-async";
import AppLayout from "./layout/AppLayout";
import { ScrollToTop } from "./components/common/ScrollToTop";
import ProtectedRoute from "./components/auth/ProtectedRoute";
import ModuleGuard from "./components/common/ModuleGuard";
import { AwsAdminGuard } from "./components/auth/AwsAdminGuard";
import GlobalErrorDisplay from "./components/common/GlobalErrorDisplay";
import LoadingStateMonitor from "./components/common/LoadingStateMonitor";
import { useAuthStore } from "./store/authStore";
import { useModuleStore } from "./store/moduleStore";

// Auth pages - loaded immediately (needed for login)
import SignIn from "./pages/AuthPages/SignIn";
import SignUp from "./pages/AuthPages/SignUp";
import Payment from "./pages/Payment";
import NotFound from "./pages/OtherPage/NotFound";

// Lazy load all other pages - only loads when navigated to
const Home = lazy(() => import("./pages/Dashboard/Home"));

// Planner Module - Lazy loaded
const PlannerDashboard = lazy(() => import("./pages/Planner/Dashboard"));
const Keywords = lazy(() => import("./pages/Planner/Keywords"));
const Clusters = lazy(() => import("./pages/Planner/Clusters"));
const ClusterDetail = lazy(() => import("./pages/Planner/ClusterDetail"));
const Ideas = lazy(() => import("./pages/Planner/Ideas"));
const KeywordOpportunities = lazy(() => import("./pages/Planner/KeywordOpportunities"));

// Writer Module - Lazy loaded
const WriterDashboard = lazy(() => import("./pages/Writer/Dashboard"));
const Tasks = lazy(() => import("./pages/Writer/Tasks"));
const Content = lazy(() => import("./pages/Writer/Content"));
const ContentView = lazy(() => import("./pages/Writer/ContentView"));
const Drafts = lazy(() => import("./pages/Writer/Drafts"));
const Images = lazy(() => import("./pages/Writer/Images"));
const Review = lazy(() => import("./pages/Writer/Review"));
const Published = lazy(() => import("./pages/Writer/Published"));

// Automation Module - Lazy loaded
const AutomationPage = lazy(() => import("./pages/Automation/AutomationPage"));

// Linker Module - Lazy loaded
const LinkerDashboard = lazy(() => import("./pages/Linker/Dashboard"));
const LinkerContentList = lazy(() => import("./pages/Linker/ContentList"));

// Optimizer Module - Lazy loaded
const OptimizerDashboard = lazy(() => import("./pages/Optimizer/Dashboard"));
const OptimizerContentSelector = lazy(() => import("./pages/Optimizer/ContentSelector"));
const AnalysisPreview = lazy(() => import("./pages/Optimizer/AnalysisPreview"));

// Thinker Module - Lazy loaded
const ThinkerDashboard = lazy(() => import("./pages/Thinker/Dashboard"));
const Prompts = lazy(() => import("./pages/Thinker/Prompts"));
const AuthorProfiles = lazy(() => import("./pages/Thinker/AuthorProfiles"));
const ThinkerProfile = lazy(() => import("./pages/Thinker/Profile"));
const Strategies = lazy(() => import("./pages/Thinker/Strategies"));
const ImageTesting = lazy(() => import("./pages/Thinker/ImageTesting"));

// Billing Module - Lazy loaded
const Credits = lazy(() => import("./pages/Billing/Credits"));
const Transactions = lazy(() => import("./pages/Billing/Transactions"));
const Usage = lazy(() => import("./pages/Billing/Usage"));
const CreditsAndBilling = lazy(() => import("./pages/Settings/CreditsAndBilling"));
const PurchaseCreditsPage = lazy(() => import("./pages/account/PurchaseCreditsPage"));
const PlansAndBillingPage = lazy(() => import("./pages/account/PlansAndBillingPage"));
const AccountSettingsPage = lazy(() => import("./pages/account/AccountSettingsPage"));
const TeamManagementPage = lazy(() => import("./pages/account/TeamManagementPage"));
const UsageAnalyticsPage = lazy(() => import("./pages/account/UsageAnalyticsPage"));

// Admin Module - Only dashboard for aws-admin users
const AdminSystemDashboard = lazy(() => import("./pages/admin/AdminSystemDashboard"));

// Reference Data - Lazy loaded
const SeedKeywords = lazy(() => import("./pages/Reference/SeedKeywords"));
const ReferenceIndustries = lazy(() => import("./pages/Reference/Industries"));

// Setup Pages - Lazy loaded
const IndustriesSectorsKeywords = lazy(() => import("./pages/Setup/IndustriesSectorsKeywords"));

// Settings - Lazy loaded
const GeneralSettings = lazy(() => import("./pages/Settings/General"));
const ProfileSettingsPage = lazy(() => import("./pages/settings/ProfileSettingsPage"));
const Users = lazy(() => import("./pages/Settings/Users"));
const Subscriptions = lazy(() => import("./pages/Settings/Subscriptions"));
const SystemSettings = lazy(() => import("./pages/Settings/System"));
const AccountSettings = lazy(() => import("./pages/Settings/Account"));
const ModuleSettings = lazy(() => import("./pages/Settings/Modules"));
const AISettings = lazy(() => import("./pages/Settings/AI"));
const Plans = lazy(() => import("./pages/Settings/Plans"));
const Industries = lazy(() => import("./pages/Settings/Industries"));
const Integration = lazy(() => import("./pages/Settings/Integration"));
const Publishing = lazy(() => import("./pages/Settings/Publishing"));
const Sites = lazy(() => import("./pages/Settings/Sites"));
const ImportExport = lazy(() => import("./pages/Settings/ImportExport"));

// Sites - Lazy loaded
const SiteList = lazy(() => import("./pages/Sites/List"));
const SiteManage = lazy(() => import("./pages/Sites/Manage"));
const SiteDashboard = lazy(() => import("./pages/Sites/Dashboard"));
const SiteContent = lazy(() => import("./pages/Sites/Content"));
const PageManager = lazy(() => import("./pages/Sites/PageManager"));
const PostEditor = lazy(() => import("./pages/Sites/PostEditor"));
const SiteSettings = lazy(() => import("./pages/Sites/Settings"));
const SyncDashboard = lazy(() => import("./pages/Sites/SyncDashboard"));
const DeploymentPanel = lazy(() => import("./pages/Sites/DeploymentPanel"));

// Help - Lazy loaded
const Help = lazy(() => import("./pages/Help/Help"));
const Docs = lazy(() => import("./pages/Help/Docs"));
const SystemTesting = lazy(() => import("./pages/Help/SystemTesting"));
const FunctionTesting = lazy(() => import("./pages/Help/FunctionTesting"));

// Components - Lazy loaded
const Components = lazy(() => import("./pages/Components"));



export default function App() {
  const { isAuthenticated } = useAuthStore();
  const { loadModuleSettings } = useModuleStore();

  // Load global module settings immediately on mount (public endpoint, no auth required)
  useEffect(() => {
    loadModuleSettings();
  }, [loadModuleSettings]);

  return (
    <>
      <GlobalErrorDisplay />
      <LoadingStateMonitor />
      <HelmetProvider>
        <ScrollToTop />
        {/* CRITICAL FIX: Move Suspense OUTSIDE Routes to prevent Router context loss during HMR */}
        <Suspense fallback={<div className="flex items-center justify-center min-h-screen"><div className="text-lg">Loading...</div></div>}>
        <Routes>
          {/* Auth Routes - Public */}
          <Route path="/signin" element={<SignIn />} />
          <Route path="/signup" element={<SignUp />} />
          <Route path="/payment" element={<Payment />} />

          {/* Protected Routes - Require Authentication */}
          <Route
            element={
              <ProtectedRoute>
                <AppLayout />
              </ProtectedRoute>
            }
          >
            {/* Dashboard */}
            <Route index path="/" element={<Home />} />

            {/* Planner Module - Redirect dashboard to keywords */}
            <Route path="/planner" element={<Navigate to="/planner/keywords" replace />} />
            <Route path="/planner/keywords" element={
              <ModuleGuard module="planner">
                <Keywords />
              </ModuleGuard>
            } />
            <Route path="/planner/clusters" element={
              <ModuleGuard module="planner">
                <Clusters />
              </ModuleGuard>
            } />
            <Route path="/planner/clusters/:id" element={
              <ModuleGuard module="planner">
                <ClusterDetail />
              </ModuleGuard>
            } />
            <Route path="/planner/ideas" element={
              <ModuleGuard module="planner">
                <Ideas />
              </ModuleGuard>
            } />

            {/* Writer Module - Redirect dashboard to tasks */}
            <Route path="/writer" element={<Navigate to="/writer/tasks" replace />} />
            <Route path="/writer/tasks" element={
              <ModuleGuard module="writer">
                <Tasks />
              </ModuleGuard>
            } />
            {/* Writer Content Routes - Order matters: list route must come before detail route */}
            <Route path="/writer/content" element={
              <ModuleGuard module="writer">
                <Content />
              </ModuleGuard>
            } />
            {/* Content detail view - matches /writer/content/:id (e.g., /writer/content/10) */}
            <Route path="/writer/content/:id" element={
              <ModuleGuard module="writer">
                <ContentView />
              </ModuleGuard>
            } />
            <Route path="/writer/drafts" element={<Navigate to="/writer/content" replace />} />
            <Route path="/writer/images" element={
              <ModuleGuard module="writer">
                <Images />
              </ModuleGuard>
            } />
            <Route path="/writer/review" element={
              <ModuleGuard module="writer">
                <Review />
              </ModuleGuard>
            } />
            <Route path="/writer/published" element={
              <ModuleGuard module="writer">
                <Published />
              </ModuleGuard>
            } />

            {/* Automation Module */}
            <Route path="/automation" element={<AutomationPage />} />

            {/* Linker Module - Redirect dashboard to content */}
            <Route path="/linker" element={<Navigate to="/linker/content" replace />} />
            <Route path="/linker/content" element={
              <ModuleGuard module="linker">
                <LinkerContentList />
              </ModuleGuard>
            } />

            {/* Optimizer Module - Redirect dashboard to content */}
            <Route path="/optimizer" element={<Navigate to="/optimizer/content" replace />} />
            <Route path="/optimizer/content" element={
              <ModuleGuard module="optimizer">
                <OptimizerContentSelector />
              </ModuleGuard>
            } />
            <Route path="/optimizer/analyze/:id" element={
              <ModuleGuard module="optimizer">
                <AnalysisPreview />
              </ModuleGuard>
            } />

            {/* Thinker Module */}
            {/* Thinker Module - Redirect dashboard to prompts */}
            <Route path="/thinker" element={<Navigate to="/thinker/prompts" replace />} />
            <Route path="/thinker/prompts" element={
              <ModuleGuard module="thinker">
                <Prompts />
              </ModuleGuard>
            } />
            <Route path="/thinker/author-profiles" element={
              <ModuleGuard module="thinker">
                <AuthorProfiles />
              </ModuleGuard>
            } />
            <Route path="/thinker/profile" element={
              <ModuleGuard module="thinker">
                <ThinkerProfile />
              </ModuleGuard>
            } />
            <Route path="/thinker/strategies" element={
              <ModuleGuard module="thinker">
                <Strategies />
              </ModuleGuard>
            } />
            <Route path="/thinker/image-testing" element={
              <ModuleGuard module="thinker">
                <ImageTesting />
              </ModuleGuard>
            } />

            {/* Billing Module */}
            <Route path="/billing" element={<Navigate to="/billing/overview" replace />} />
            <Route path="/billing/overview" element={<CreditsAndBilling />} />
            <Route path="/billing/credits" element={<Credits />} />
            <Route path="/billing/transactions" element={<Transactions />} />
            <Route path="/billing/usage" element={<Usage />} />

            {/* Account Section - Billing & Management Pages */}
            <Route path="/account/plans" element={<PlansAndBillingPage />} />
            <Route path="/account/purchase-credits" element={<PurchaseCreditsPage />} />
            <Route path="/account/settings" element={<AccountSettingsPage />} />
            <Route path="/account/team" element={<TeamManagementPage />} />
            <Route path="/account/usage" element={<UsageAnalyticsPage />} />
            
            {/* Admin Routes - Only Dashboard for aws-admin users */}
            <Route path="/admin/dashboard" element={
              <AwsAdminGuard>
                <AdminSystemDashboard />
              </AwsAdminGuard>
            } />
            
            {/* Reference Data */}
            <Route path="/reference/seed-keywords" element={<SeedKeywords />} />
            <Route path="/planner/keyword-opportunities" element={<KeywordOpportunities />} />
            <Route path="/reference/industries" element={<ReferenceIndustries />} />

            {/* Setup Pages */}
            <Route path="/setup/add-keywords" element={<IndustriesSectorsKeywords />} />
            {/* Legacy redirect */}
            <Route path="/setup/industries-sectors-keywords" element={<Navigate to="/setup/add-keywords" replace />} />

            {/* Settings */}
            <Route path="/settings/profile" element={<ProfileSettingsPage />} />
            <Route path="/settings" element={<GeneralSettings />} />
            <Route path="/settings/users" element={<Users />} />
            <Route path="/settings/subscriptions" element={<Subscriptions />} />
            <Route path="/settings/system" element={<SystemSettings />} />
            <Route path="/settings/account" element={<AccountSettings />} />
            <Route path="/settings/modules" element={<ModuleSettings />} />
            <Route path="/settings/ai" element={<AISettings />} />
            <Route path="/settings/plans" element={<Plans />} />
            <Route path="/settings/industries" element={<Industries />} />
            <Route path="/settings/integration" element={<Integration />} />
            <Route path="/settings/publishing" element={<Publishing />} />
            <Route path="/settings/sites" element={<Sites />} />
            <Route path="/settings/import-export" element={<ImportExport />} />

            {/* Sites Management */}
            <Route path="/sites" element={<SiteList />} />
            <Route path="/sites/manage" element={<SiteManage />} />
            <Route path="/sites/:id" element={<SiteDashboard />} />
            <Route path="/sites/:id/pages" element={<PageManager />} />
            <Route path="/sites/:id/pages/new" element={<PageManager />} />
            <Route path="/sites/:id/pages/:pageId/edit" element={<PageManager />} />
            <Route path="/sites/:id/content" element={<SiteContent />} />
            <Route path="/sites/:id/settings" element={<SiteSettings />} />
            <Route path="/sites/:id/sync" element={<SyncDashboard />} />
            <Route path="/sites/:id/deploy" element={<DeploymentPanel />} />
            <Route path="/sites/:id/posts/:postId" element={<PostEditor />} />
            <Route path="/sites/:id/posts/:postId/edit" element={<PostEditor />} />


            {/* Help */}
            <Route path="/help" element={<Help />} />
            <Route path="/help/docs" element={<Docs />} />
            <Route path="/help/system-testing" element={<SystemTesting />} />
            <Route path="/help/function-testing" element={<FunctionTesting />} />
            
            {/* Components (Showcase Page) */}
            <Route path="/components" element={<Components />} />
          </Route>

          {/* Fallback Route */}
          <Route path="*" element={<NotFound />} />
        </Routes>
        </Suspense>
      </HelmetProvider>
    </>
  );
}
