import React, { Suspense, lazy } from "react";
import ReactDOM from "react-dom/client";
import { HelmetProvider } from "react-helmet-async";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./index.css";
import Layout from "./components/Layout";
import Loader from "./components/Loader";
import ScrollToTop from "./components/ScrollToTop";
import ErrorBoundary from "./components/ErrorBoundary";
import { initAllAnalytics } from "./utils/deferredAnalytics";
import { initPWAFeatures } from "./utils/pwaFeatures";

// ==========================================
// Core Web Vitals Monitoring (Production)
// ==========================================
const initCoreWebVitals = async () => {
  try {
    if (process.env.NODE_ENV === "production") {
      const { getCLS, getFID, getFCP, getLCP, getTTFB } = await import(
        "web-vitals"
      );

      getCLS((metric) => {
        if (metric.value > 0.1) console.warn("⚠️ CLS:", metric.value);
      });

      getFID((metric) => {
        if (metric.value > 100) console.warn("⚠️ FID:", metric.value);
      });

      getLCP((metric) => {
        if (metric.value > 2500) console.warn("⚠️ LCP:", metric.value);
      });

      getTTFB((metric) => {
        console.log("TTFB:", metric.value);
      });
    }
  } catch (error) {
    console.error("Web Vitals monitoring error:", error);
  }
};

// Initialize performance monitoring
if (process.env.NODE_ENV === "production") {
  initCoreWebVitals();
}

// Lazy load components for better performance
const Home = lazy(() => import("./pages/Home"));
const Work = lazy(() => import("./pages/Work"));
const ProjectDetail = lazy(() => import("./pages/ProjectDetail"));
const About = lazy(() => import("./pages/About"));
const Contact = lazy(() => import("./pages/Contact"));
const DeveloperHub = lazy(() => import("./pages/DeveloperHub"));
const FAQ = lazy(() => import("./pages/FAQ"));
const NotFound = lazy(() => import("./pages/NotFound"));

// Preload critical components with optimized strategy
const preloadComponents = async () => {
  const routes = [
    () => import("./pages/Home"),
    () => import("./pages/Work"),
    () => import("./pages/About"),
    () => import("./pages/Contact"),
  ];

  try {
    // Preload most critical routes first
    await Promise.all(routes.slice(0, 2).map((route) => route()));

    // Preload remaining routes after a delay to avoid blocking
    await new Promise((resolve) => {
      setTimeout(async () => {
        try {
          await Promise.all(routes.slice(2).map((route) => route()));
        } catch (err) {
          console.warn("Failed to preload remaining components:", err);
        }
        resolve();
      }, 1500);
    });
  } catch (error) {
    console.warn("Failed to preload some components:", error);
  }
};

// Enhanced Suspense fallback with better UX
const LoadingFallback = () => (
  <div className="min-h-screen flex items-center justify-center bg-slate-900">
    <div className="flex flex-col items-center gap-4">
      <div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
      <p className="text-slate-400 text-sm">Loading...</p>
    </div>
  </div>
);

// Vite PWA plugin auto-registers the service worker (registerType: 'autoUpdate')
// We can still run custom PWA features post-load
if (import.meta.env.PROD) {
  window.addEventListener("load", () => {
    try {
      initPWAFeatures();
    } catch (error) {
      console.log("PWA features init failed: ", error);
    }
  });
}

// Initialize deferred analytics (only in production)
if (import.meta.env.PROD) {
  initAllAnalytics({
    // Uncomment and configure when ready:
    // umami: {
    //   websiteId: "your-umami-website-id",
    //   src: "https://analytics.umami.is/script.js"
    // },
    // ga4: {
    //   measurementId: "G-XXXXXXXXXX"
    // },
    // sentry: {
    //   dsn: "your-sentry-dsn",
    //   options: { sampleRate: 0.1 }
    // },
    custom: {
      endpoint: "/api/analytics",
    },
  });
}

// App component with error boundary and performance optimizations
const App = () => {
  React.useEffect(() => {
    preloadComponents();

    // Mark app as interactive
    if (typeof window !== "undefined" && window.performance) {
      window.performance.mark("app-interactive");
    }

    // Report initial load performance
    setTimeout(() => {
      if (performanceMonitor) {
        performanceMonitor.checkPerformanceBudget();
      }
    }, 1000);
  }, []);

  return (
    <React.StrictMode>
      <ErrorBoundary>
        <HelmetProvider>
          <Router>
            <ScrollToTop />
            <Layout>
              <Suspense fallback={<LoadingFallback />}>
                <Routes>
                  <Route path="/" element={<Home />} />
                  <Route path="/work" element={<Work />} />
                  <Route path="/project/:id" element={<ProjectDetail />} />
                  <Route path="/about" element={<About />} />
                  <Route path="/contact" element={<Contact />} />
                  <Route path="/developer-hub" element={<DeveloperHub />} />
                  <Route
                    path="/developer-help"
                    element={<DeveloperHub />}
                  />{" "}
                  {/* Redirect old URL */}
                  <Route path="/faq" element={<FAQ />} />
                  <Route path="*" element={<NotFound />} />
                </Routes>
              </Suspense>
            </Layout>
          </Router>
        </HelmetProvider>
      </ErrorBoundary>
    </React.StrictMode>
  );
};

// Create root with concurrent features
const root = ReactDOM.createRoot(document.getElementById("root"));

// Use concurrent rendering for better performance
root.render(<App />);
