import { useEffect, lazy, Suspense } from "react";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { CartProvider } from "@/contexts/CartContext";
import { AuthProvider } from "@/contexts/AuthContext";
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { reportError } from "@/lib/errorReporter";
import { initPerfMonitoring } from "@/lib/perfReporter";
import { AdminProtectedRoute } from "@/components/admin/AdminProtectedRoute";
import { ThemeProvider } from "@/components/theme/ThemeProvider";
import { markNativeEnvironment } from "@/lib/native";

// 关键路径（首屏 / 高频）保持同步加载
import ChatPage from "./pages/ChatPage";
import AuthPage from "./pages/AuthPage";
import NotFound from "./pages/NotFound";

// 次要路由懒加载，按需切片，显著降低首屏 bundle
const ProfilePage = lazy(() => import("./pages/ProfilePage"));
const OrdersPage = lazy(() => import("./pages/OrdersPage"));
const NotificationPage = lazy(() => import("./pages/NotificationPage"));
const CheckoutPage = lazy(() => import("./pages/CheckoutPage"));
const AfterSalesPage = lazy(() => import("./pages/AfterSalesPage"));
const CouponsPage = lazy(() => import("./pages/CouponsPage"));
const ShopPage = lazy(() => import("./pages/ShopPage"));
const MobilePage = lazy(() => import("./pages/MobilePage"));
const GenUIDebugPage = lazy(() => import("./pages/GenUIDebugPage"));
const DebugAuthPage = lazy(() => import("./pages/DebugAuthPage"));
// Admin 子树整体懒加载（最重的部分）
const AdminPage = lazy(() => import("./pages/AdminPage"));
const AdminAuthPage = lazy(() => import("./pages/AdminAuthPage"));
const SystemHealthPage = lazy(() => import("./pages/admin/SystemHealthPage"));
const AIProvidersPage = lazy(() => import("./pages/admin/AIProvidersPage"));
const AdminMePage = lazy(() => import("./pages/admin/AdminMePage"));

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 1,
      refetchOnWindowFocus: false,
      staleTime: 30_000,
    },
  },
});

// 懒加载页面回退（避免空白闪烁）
const RouteFallback = () => (
  <div className="flex h-screen items-center justify-center">
    <div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
  </div>
);

const useGlobalErrorHandler = () => {
  useEffect(() => {
    const isExtensionNoise = (s: string) =>
      s.includes("chrome-extension://") ||
      s.includes("moz-extension://") ||
      s.includes("MetaMask");

    const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
      const reason: any = event.reason;
      const errorString = String(reason?.stack || reason || "");
      if (isExtensionNoise(errorString)) {
        console.warn("[Extension Error Caught]", reason);
        event.preventDefault();
        return;
      }
      console.error("[Unhandled Rejection]", reason);
      void reportError({
        message: reason?.message || String(reason) || "Unhandled promise rejection",
        stack: reason?.stack,
        severity: "error",
        context: { source: "unhandledrejection" },
      });
    };

    const handleWindowError = (event: ErrorEvent) => {
      const errorString = String(event.error?.stack || event.message || "");
      if (isExtensionNoise(errorString)) return;
      void reportError({
        message: event.message || event.error?.message || "Window error",
        stack: event.error?.stack,
        severity: "error",
        context: {
          source: "window.onerror",
          filename: event.filename,
          lineno: event.lineno,
          colno: event.colno,
        },
      });
    };

    window.addEventListener("unhandledrejection", handleUnhandledRejection);
    window.addEventListener("error", handleWindowError);

    return () => {
      window.removeEventListener("unhandledrejection", handleUnhandledRejection);
      window.removeEventListener("error", handleWindowError);
    };
  }, []);
};

const App = () => {
  useGlobalErrorHandler();
  useEffect(() => { initPerfMonitoring(); markNativeEnvironment(); }, []);

  return (
  <ErrorBoundary scope="app-root">
  <ThemeProvider defaultTheme="system">
  <QueryClientProvider client={queryClient}>
    <AuthProvider>
      <CartProvider>
        <TooltipProvider>
          <Toaster />
          <Sonner />
          <BrowserRouter>
            <Suspense fallback={<RouteFallback />}>
              <Routes>
                <Route path="/auth" element={<AuthPage />} />
                <Route path="/profile" element={<ProtectedRoute><ProfilePage /></ProtectedRoute>} />
                <Route path="/orders" element={<ProtectedRoute><OrdersPage /></ProtectedRoute>} />
                <Route path="/notifications" element={<ProtectedRoute><NotificationPage /></ProtectedRoute>} />
                <Route path="/checkout" element={<ProtectedRoute><CheckoutPage /></ProtectedRoute>} />
                <Route path="/aftersales" element={<ProtectedRoute><AfterSalesPage /></ProtectedRoute>} />
                <Route path="/coupons" element={<ProtectedRoute><CouponsPage /></ProtectedRoute>} />
                <Route path="/admin/login" element={<AdminAuthPage />} />
                <Route path="/admin/system-health" element={
                  <AdminProtectedRoute><SystemHealthPage /></AdminProtectedRoute>
                } />
                <Route path="/admin/me" element={
                  <AdminProtectedRoute><AdminMePage /></AdminProtectedRoute>
                } />
                <Route path="/admin/ai-providers" element={
                  <AdminProtectedRoute><AIProvidersPage /></AdminProtectedRoute>
                } />
                <Route path="/admin/*" element={
                  <AdminProtectedRoute><AdminPage /></AdminProtectedRoute>
                } />
                <Route path="/debug-auth" element={<ProtectedRoute><DebugAuthPage /></ProtectedRoute>} />
                <Route path="/mobile" element={<ProtectedRoute><MobilePage /></ProtectedRoute>} />
                <Route path="/genui-debug" element={<ProtectedRoute><GenUIDebugPage /></ProtectedRoute>} />
                {/* 公开访问 */}
                <Route path="/shop" element={<ShopPage />} />
                <Route path="/" element={<ChatPage />} />
                <Route path="/chat" element={<div>ChatPage temporarily disabled due to syntax errors</div>} />
                <Route path="*" element={<NotFound />} />
              </Routes>
            </Suspense>
          </BrowserRouter>
        </TooltipProvider>
      </CartProvider>
    </AuthProvider>
  </QueryClientProvider>
  </ThemeProvider>
  </ErrorBoundary>
  );
};

export default App;
