import { lazy, Suspense, useEffect, useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './App.css';
import { CartProvider } from './CartProvider.tsx'; // Import CartProvider
import { ToastContainer } from 'react-toastify'; // Import ToastContainer
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from './config/firebase-config.js'; // Adjust the path to your Firebase config
import { ClipLoader } from 'react-spinners';
import { UserProvider } from './UserContext';
import { FavouritesProvider } from './FavouritesProvider';
import { HelmetProvider } from 'react-helmet-async';
import GoogleAnalytics from './components/Analytics/GoogleAnalytics.tsx';
import WebVitalsMonitor from './components/Performance/WebVitalsMonitor.tsx';
import { useAnalytics } from './hooks/useAnalytics';
const Layout = lazy(() => import('./Layout'));

const HomePage = lazy(() => import('./components/homepage').then(module => ({ default: module.HomePage })));
const ProductList = lazy(() => import('./components/productlist').then(module => ({ default: module.ProductList })));
const AllProductsPageV3 = lazy(() => import('./components/AllProducts/AllProductsPageV3/AllProductsPageV3.tsx').then(module => ({ default: module.AllProductsPageV3 })));

const AllProductsWrapper = () => <AllProductsPageV3 />;
const LoginLayout = lazy(() => import('./components/Login/login.jsx').then(module => ({ default: module.LoginLayout })));
const RegisterLayout = lazy(() => import('./components/Login/register.tsx').then(module => ({ default: module.RegisterLayout })));
const AccountLayout = lazy(() => import('./components/Account/Account.tsx').then(module => ({ default: module.AccountLayout })));
const ProductPage = lazy(() => import('./components/SingleProduct/ProductPage.tsx').then(module => ({ default: module.ProductPage })));
const ProductPageV2 = lazy(() => import('./components/SingleProduct/ProductPageV2.tsx').then(module => ({ default: module.ProductPageV2 })));
const EditProfileLayout = lazy(() => import('./components/Account/EditProfileLayout.tsx').then(module => ({ default: module.EditProfileLayout })));
const ChangePasswordLayout = lazy(() => import('./components/Account/ChangePasswordLayout.jsx').then(module => ({ default: module.ChangePasswordLayout })));
const SearchQueryPage = lazy(() => import('./components/searchQuery/search_query_page.jsx').then(module => ({ default: module.SearchQueryPage })));
const SearchQueryPageV2 = lazy(() => import('./components/searchQuery/SearchQueryPageV2.jsx').then(module => ({ default: module.SearchQueryPageV2 })));
const ForgotPassword = lazy(() => import('./components/Login/forgotpassword/ForgotPassword.jsx').then(module => ({ default: module.ForgotPassword })));
const RegulationsLayout = lazy(() => import('./components/Politics/RegulationsLayout.jsx').then(module => ({ default: module.RegulationsLayout })));
const PrivacyPolicyLayout = lazy(() => import('./components/Politics/PrivacyPolicyLayout.jsx').then(module => ({ default: module.PrivacyPolicyLayout })));
const ReturnsLayout = lazy(() => import('./components/Politics/ReturnsLayout.jsx').then(module => ({ default: module.ReturnsLayout })));
const DeliveryTracking = lazy(() => import('./components/Politics/DeliveryTracking.jsx').then(module => ({ default: module.DeliveryTracking })));
const PaymentPage = lazy(() => import('./components/Payment/PaymentPage.tsx').then(module => ({ default: module.PaymentPage })));
const Returns = lazy(() => import('./components/Politics/Returns.jsx').then(module => ({ default: module.Returns })));
const ReturnLayout = lazy(() => import('./Returns/ReturnLayout.jsx').then(module => ({ default: module.ReturnLayout })));
const OrderPage = lazy(() => import('./components/Order/OrderPage.tsx').then(module => ({ default: module.OrderPage })));
const PanelPage = lazy(() => import('./components/Panel/PanelPage.tsx').then(module => ({ default: module.PanelPage })));
const PaymentReturn = lazy(() => import('./components/Payment/PaymentReturn.tsx').then(module => ({ default: module.PaymentReturn })));
const BusinessSalesPage = lazy(() => import('./components/BusinessSalesPage/BusinessSalesPage.tsx').then(module => ({ default: module.BusinessSalesPage })));
const CategoryProductsV2 = lazy(() => import('./components/Categories/CategoryProductsV2.tsx').then(module => ({ default: module.CategoryProductsV2 })));
const CategoryByIdPage = lazy(() => import('./components/Categories/CategoryByIdPage.tsx').then(module => ({ default: module.CategoryByIdPage })));
const AllBlogsPage = lazy(() => import('./components/Blog/Blog').then(module => ({ default: module.AllBlogsPage })));
const BlogPage = lazy(() => import('./components/Blog/BlogPage').then(module => ({ default: module })));
const ProductPageWrapper = lazy(() => import('./components/ProductPageWrapper.jsx').then(module => ({ default: module.default })));
const StaticFileHandler = lazy(() => import('./components/StaticFileHandler.jsx'));
const NotFound404 = lazy(() => import('./components/Error/NotFound404.tsx'));
const ReviewPage = lazy(() => import('./components/Review/ReviewPage.tsx').then(module => ({ default: module.ReviewPage })));
import { featureFlags } from './config/featureFlags';

const AnalyticsInitializer = () => {
  useAnalytics();
  return null;
};

function App() {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
    });
    return () => unsubscribe();
  }, []);

  return (
    <HelmetProvider>
      <GoogleAnalytics />
      <WebVitalsMonitor />
      <UserProvider>
        <CartProvider>
          <FavouritesProvider>

            <Router>
              <AnalyticsInitializer />
              <div>
                <ToastContainer autoClose={3000} />

              <Suspense fallback={
                <div className='loading-container'>
                  <ClipLoader size={24} />
                </div>
              }>
                <Routes>
                  <Route element={<Layout user={user} />}>
                    <Route path="/" element={<HomePage />} />
                    <Route path="/wszystkieprodukty" element={<AllProductsWrapper />} />
                    <Route path="/payment-return/:transactionId" element={<PaymentReturn />} />
                    <Route path="/products" element={<ProductList />} />
                    <Route path="/product/:productSlug" element={featureFlags.useProductPageV2 ? <ProductPageV2 key={window.location.pathname} /> : <ProductPage key={window.location.pathname} />} />
                    <Route path="/review/:token" element={<ReviewPage />} />
                    {/* Static files and verification routes - must come before catch-all */}
                    <Route path="/google103be3bc8ad3d9e9.html" element={<StaticFileHandler />} />
                    <Route path="/BingSiteAuth.xml" element={<StaticFileHandler />} />
                    <Route path="/robots.txt" element={<StaticFileHandler />} />
                    <Route path="/sitemap.xml" element={<StaticFileHandler />} />
                    {/* Product catch-all route with exclusions - MUST be last */}
                    <Route path="/:productSlug" element={<ProductPageWrapper />} />
                    <Route path="/searchquery/:query" element={featureFlags.useV2Pages ? <SearchQueryPageV2 /> : <SearchQueryPage />} />
                    <Route path="/kategoria/:categoryId/:categoryName" element={featureFlags.useV2Pages ? <CategoryByIdPage /> : <CategoryByIdPage />} />
                    <Route path="/kategoria/:query" element={featureFlags.useV2Pages ? <SearchQueryPageV2 /> : <SearchQueryPage />} />
                    <Route path="/konto" element={<AccountLayout />} />
                    <Route path="/konto/edytuj" element={<EditProfileLayout />} />
                    <Route path="/konto/zamowienie/:productId" element={<OrderPage />} />
                    <Route path="/konto/zwrot" element={<ReturnLayout />} />
                    <Route path="/konto/password" element={<ChangePasswordLayout />} />
                    <Route path="/konto/panel" element={<PanelPage />} />
                    <Route path="/payment" element={<PaymentPage />} />
                    <Route path="/login" element={<LoginLayout />} />
                    <Route path="/rejestracja" element={<RegisterLayout />} />
                    <Route path="/forgotpassword" element={<ForgotPassword />} />
                    <Route path="/regulamin" element={<RegulationsLayout />} />
                    <Route path="/zwroty" element={<ReturnsLayout />} />
                    <Route path="/dostawaizwrot" element={<DeliveryTracking />} />
                    <Route path="/politykaprywatnosci" element={<PrivacyPolicyLayout />} />
                    <Route path="/dlafirm" element={<BusinessSalesPage />} />
                    <Route path="/zwrotyireklamacje" element={<Returns />} />
                    <Route path="/strefadrewniana" element={<CategoryProductsV2 queryCategories={["2777073",  "3344533", "3344531", "3344532"]} path={"Strefa Drewniana"} />} />
                    <Route path="/ozdobynasciane" element={<CategoryProductsV2 queryCategories={["3344531"]} path={"Ozdoby Na Ścianę"} />} />
                    <Route path="/zeZdjeciem" element={<CategoryProductsV2 queryCategories={["3344329", "3344533"]} path={"Ze Zdjęciem"} />} />

                    <Route path="/blog" element={<AllBlogsPage />} />
                    <Route path="/blog/:title" element={<BlogPage />} />

                  </Route>
                  
                  {/* 404 Catch-all route - MUST be last */}
                  <Route path="*" element={<NotFound404 />} />

                </Routes>
              </Suspense>

              </div>
            </Router>
          </FavouritesProvider>

        </CartProvider>
      </UserProvider>
    </HelmetProvider>
  );
}

export default App;