import React, { useState, useEffect, useMemo } from 'react';
import { Header } from './components/Header';
import { HeroDark } from './components/HeroDark';
import { CategoryHeader } from './components/CategoryHeader';
import { CategoryCards } from './components/CategoryCards';
import { FeatureBar } from './components/FeatureBar';
import { WhatsAppFloating } from './components/WhatsAppFloating';
import { SearchModal } from './components/SearchModal';
import { Footer } from './components/Footer';
import { ProductCard, ProductCardSkeleton } from './components/ProductCard';
import { ProductDetailPage } from './components/ProductDetailPage';
import { CategoriesPage } from './components/CategoriesPage';
import { Shop2Page } from './components/Shop2Page';
import { AdminPanel } from './components/AdminPanel';
import { CartDrawer, CartItem } from './components/CartDrawer';
import { CheckoutModal } from './components/CheckoutModal';
import { OrderTrackingModal } from './components/OrderTrackingModal';
import { OrderTrackingPage } from './components/OrderTrackingPage';
import { TopPromoBar } from './components/TopPromoBar';
import { WishlistModal } from './components/WishlistModal';
import { RecentlyViewedSection } from './components/RecentlyViewedSection';
import { PartnersSection } from './components/PartnersSection';
import { getWishlistItems, subscribeToWishlist } from './services/wishlistService';
import { InfoPage, InfoPageSlug } from './components/InfoPage';
import { WCProduct, WCCategory, getWCProducts, getWCCategories } from './services/woocommerce';
import {
  getCachedProducts,
  getCachedCategories,
  getCachedProductById,
  saveProductsToCache,
  saveCategoriesToCache,
  getProductSlug,
} from './services/productCache';
import { Sparkles, ArrowRight, Store } from 'lucide-react';

const resolveInfoSlug = (path: string, hash: string): InfoPageSlug | null => {
  const p = path.startsWith('/page/')
    ? path.replace('/page/', '').trim().toLowerCase()
    : path.replace('/', '').trim().toLowerCase();
  const h = hash.replace('#', '').trim().toLowerCase();
  const target = p || h;

  if (target === 'about' || target === 'about-us') return 'about-us';
  if (target === 'contact' || target === 'contact-us') return 'contact-us';
  if (target === 'team' || target === 'our-team' || target === 'collaborative-team') return 'collaborative-team';
  if (target === 'terms-of-service' || target === 'terms-conditions' || target === 'terms') return 'terms-conditions';
  if (target === 'privacy-policy' || target === 'privacy') return 'privacy-policy';
  if (target === 'shipping-details' || target === 'shipping') return 'shipping-details';
  if (target === 'refund-returns-policy' || target === 'refund-policy' || target === 'returns-policy') return 'refund-returns-policy';
  if (target === 'connect') return 'connect';
  if (target === 'introduction') return 'introduction';
  if (target === 'visit-store') return 'visit-store';

  return null;
};

export default function App() {
  const [isSearchOpen, setIsSearchOpen] = useState<boolean>(false);
  const [isCartOpen, setIsCartOpen] = useState<boolean>(false);
  const [isCheckoutOpen, setIsCheckoutOpen] = useState<boolean>(false);
  const [isWhatsAppCheckoutMode, setIsWhatsAppCheckoutMode] = useState<boolean>(false);
  const [isTrackingOpen, setIsTrackingOpen] = useState<boolean>(false);
  const [isWishlistOpen, setIsWishlistOpen] = useState<boolean>(false);
  const [wishlistItems, setWishlistItems] = useState<WCProduct[]>(() => getWishlistItems());

  useEffect(() => {
    const unsub = subscribeToWishlist((items) => {
      setWishlistItems(items);
    });
    return () => unsub();
  }, []);

// Products & Categories (Cached in localStorage for fast instant render, updated live from database)
  const [products, setProducts] = useState<WCProduct[]>(() => getCachedProducts());
  const [categories, setCategories] = useState<WCCategory[]>(() => getCachedCategories());
  const [isInitialLoading, setIsInitialLoading] = useState<boolean>(() => products.length === 0);

  // Parse current URL route synchronously on initial mount to prevent homepage flashing
  const initialRoute = useMemo(() => {
    const path = window.location.pathname;
    const hash = window.location.hash.replace('#', '').trim();
    const searchParams = new URLSearchParams(window.location.search);
    const catParam = searchParams.get('category');
    const searchParam = searchParams.get('search');

    const matchedInfoSlug = resolveInfoSlug(path, hash);

    if (matchedInfoSlug) {
      return {
        view: 'infoPage' as const,
        infoSlug: matchedInfoSlug,
        product: null,
        shopCategory: null,
        shopSearchQuery: '',
      };
    }

    if (
      path === '/tnl-secret-portal-x92' ||
      path === '/tnl-portal-2026-admin' ||
      hash === 'tnl-secret-portal-x92' ||
      hash === 'tnl-portal-2026-admin'
    ) {
      return {
        view: 'admin' as const,
        infoSlug: 'introduction' as InfoPageSlug,
        product: null,
        shopCategory: null,
        shopSearchQuery: '',
      };
    }

    if (path === '/categories' || path.startsWith('/categories/') || hash === 'categories') {
      return {
        view: 'categories' as const,
        infoSlug: 'introduction' as InfoPageSlug,
        product: null,
        shopCategory: null,
        shopSearchQuery: '',
      };
    }

    if (
      path === '/track-order' ||
      path === '/order-tracking' ||
      path === '/track' ||
      path.startsWith('/track-order') ||
      path.startsWith('/order-tracking') ||
      path === '/page/track-order' ||
      hash === 'track-order' ||
      hash === 'order-tracking' ||
      hash === 'track'
    ) {
      return {
        view: 'trackOrder' as const,
        infoSlug: 'introduction' as InfoPageSlug,
        product: null,
        shopCategory: null,
        shopSearchQuery: '',
      };
    }

    if (path.startsWith('/product-category/')) {
      const catSlug = path.replace('/product-category/', '').trim().toLowerCase();
      return {
        view: 'shop2' as const,
        infoSlug: 'introduction' as InfoPageSlug,
        product: null,
        shopCategory: catSlug || null,
        shopSearchQuery: searchParam || '',
      };
    }

    if (path.startsWith('/product/')) {
      const slugOrId = decodeURIComponent(path.replace('/product/', '')).trim().toLowerCase();
      let found = null;
      if (slugOrId) {
        found = getCachedProductById(slugOrId) || products.find(
          (p) =>
            p.id.toString() === slugOrId ||
            getProductSlug(p) === slugOrId ||
            p.slug?.toLowerCase() === slugOrId ||
            p.permalink?.toLowerCase().includes(`/product/${slugOrId}`) ||
            p.name.toLowerCase().replace(/[^a-z0-9]+/g, '-') === slugOrId
        ) || null;
      }
      return {
        view: 'productDetail' as const,
        infoSlug: 'introduction' as InfoPageSlug,
        product: found,
        shopCategory: null,
        shopSearchQuery: '',
      };
    }

    if (
      path.startsWith('/shop-2') ||
      path.startsWith('/shop') ||
      hash === 'shop-2' ||
      hash === 'shop'
    ) {
      return {
        view: 'shop2' as const,
        infoSlug: 'introduction' as InfoPageSlug,
        product: null,
        shopCategory: catParam || null,
        shopSearchQuery: searchParam || '',
      };
    }

    return {
      view: 'home' as const,
      infoSlug: 'introduction' as InfoPageSlug,
      product: null,
      shopCategory: null,
      shopSearchQuery: '',
    };
  }, []);

  // Main Page View State: 'home' | 'shop2' | 'productDetail' | 'admin' | 'infoPage' | 'categories' | 'trackOrder'
  const [currentView, setCurrentView] = useState<'home' | 'shop2' | 'productDetail' | 'admin' | 'infoPage' | 'categories' | 'trackOrder'>(initialRoute.view);
  const [infoPageSlug, setInfoPageSlug] = useState<InfoPageSlug>(initialRoute.infoSlug);
  const [selectedProduct, setSelectedProduct] = useState<WCProduct | null>(initialRoute.product);
  const [selectedShop2Category, setSelectedShop2Category] = useState<number | string | null>(initialRoute.shopCategory);
  const [selectedShop2SearchQuery, setSelectedShop2SearchQuery] = useState<string>(initialRoute.shopSearchQuery);
  const [showVariationNotice, setShowVariationNotice] = useState<boolean>(false);

  // Cart State with LocalStorage Persistence
  const [cartItems, setCartItems] = useState<CartItem[]>(() => {
    try {
      const saved = localStorage.getItem('timenlife_cart_session');
      return saved ? JSON.parse(saved) : [];
    } catch {
      return [];
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem('timenlife_cart_session', JSON.stringify(cartItems));
    } catch {
      // ignore
    }
  }, [cartItems]);

  // Route Synchronization Helper for browser URL address bar (Supports /admin12345, product slug, & info pages)
  useEffect(() => {
    const handleRouteSync = () => {
      const path = window.location.pathname;
      const hash = window.location.hash.replace('#', '').trim();
      const searchParams = new URLSearchParams(window.location.search);
      const catParam = searchParams.get('category');

      // Check for Info Page routes (e.g. /about, /contact, /terms-of-service, /privacy-policy, /introduction, etc.)
      const matchedInfoSlug = resolveInfoSlug(path, hash);

      if (matchedInfoSlug) {
        setInfoPageSlug(matchedInfoSlug);
        setCurrentView('infoPage');
        setSelectedProduct(null);
        return;
      }

      // Hard secret admin route ONLY (/tnl-secret-portal-x92 or #tnl-secret-portal-x92)
      if (
        path === '/tnl-secret-portal-x92' ||
        path === '/tnl-portal-2026-admin' ||
        window.location.hash === '#tnl-secret-portal-x92' ||
        window.location.hash === '#tnl-portal-2026-admin'
      ) {
        setCurrentView('admin');
        setSelectedProduct(null);
        return;
      }

      // Block standard /admin routes for security
      if (path === '/admin' || path === '/admin12345' || path.startsWith('/admin/')) {
        setCurrentView('home');
        setSelectedProduct(null);
        return;
      }

      // Dedicated Categories Page Route (/categories or #categories)
      if (path === '/categories' || path.startsWith('/categories/') || hash === 'categories') {
        setCurrentView('categories');
        setSelectedProduct(null);
        return;
      }

      // Dedicated Order Tracking Page Route (/track-order, /order-tracking, #track-order, /page/track-order)
      if (
        path === '/track-order' ||
        path === '/order-tracking' ||
        path === '/track' ||
        path.startsWith('/track-order') ||
        path.startsWith('/order-tracking') ||
        path === '/page/track-order' ||
        hash === 'track-order' ||
        hash === 'order-tracking' ||
        hash === 'track'
      ) {
        setCurrentView('trackOrder');
        setSelectedProduct(null);
        return;
      }

      // Product Category Dedicated Page Route (/product-category/health-beauty or /product-category/316)
      if (path.startsWith('/product-category/')) {
        const catSlug = path.replace('/product-category/', '').trim().toLowerCase();
        setCurrentView('shop2');
        setSelectedShop2Category(catSlug || null);
        setSelectedProduct(null);
        return;
      }

      // Product detail route with SLUG or ID (/product/time-n-life or /product/aneelas-embroidered-lawn-3-piece-suit)
      if (path.startsWith('/product/')) {
        const slugOrId = decodeURIComponent(path.replace('/product/', '')).trim().toLowerCase();
        
        if (slugOrId) {
          // 1. Try matching cached product by slug or ID
          const found = getCachedProductById(slugOrId) || products.find(
            (p) =>
              p.id.toString() === slugOrId ||
              getProductSlug(p) === slugOrId ||
              p.slug?.toLowerCase() === slugOrId ||
              p.permalink?.toLowerCase().includes(`/product/${slugOrId}`) ||
              p.name.toLowerCase().replace(/[^a-z0-9]+/g, '-') === slugOrId
          );

          if (found) {
            setSelectedProduct(found);
            setCurrentView('productDetail');
          } else {
            // Immediately activate productDetail view so ProductDetailPageSkeleton with spinners renders
            setCurrentView('productDetail');

            // 2. Fetch live product from WooCommerce API
            const fetchUrl = `/api/wc/products/${encodeURIComponent(slugOrId)}`;
            
            fetch(fetchUrl)
              .then((res) => res.json())
              .then((data) => {
                if (data.success && data.product) {
                  setSelectedProduct(data.product);
                  saveProductsToCache([data.product]);
                } else if (data.products && data.products.length > 0) {
                  setSelectedProduct(data.products[0]);
                  saveProductsToCache([data.products[0]]);
                }
              })
              .catch(() => {
                // view stays productDetail
              });
          }
        }
      } else if (path.startsWith('/shop-2') || path.startsWith('/shop') || window.location.hash === '#shop-2' || window.location.hash === '#shop') {
        const searchParam = searchParams.get('search');
        setCurrentView('shop2');
        setSelectedShop2Category(catParam || null);
        setSelectedShop2SearchQuery(searchParam || '');
        setSelectedProduct(null);
      } else {
        setCurrentView('home');
        setSelectedProduct(null);
        setSelectedShop2Category(null);
        setSelectedShop2SearchQuery('');
      }
    };

    handleRouteSync();
    window.addEventListener('popstate', handleRouteSync);
    return () => window.removeEventListener('popstate', handleRouteSync);
  }, [products]);

  // Fetch live WooCommerce data directly from database on mount for homepage & shop
  useEffect(() => {
    let isMounted = true;
    async function loadWCData() {
      try {
        const res = await getWCProducts(undefined, 100);
        if (isMounted && res && res.products && res.products.length > 0) {
          setProducts(res.products);
          saveProductsToCache(res.products);
        }

        const liveCats = await getWCCategories();
        if (isMounted && liveCats && liveCats.length > 0) {
          setCategories(liveCats);
          saveCategoriesToCache(liveCats);
        }
      } catch (err) {
        console.warn('Failed to load live WooCommerce catalog:', err);
      } finally {
        if (isMounted) setIsInitialLoading(false);
      }
    }
    loadWCData();

    return () => {
      isMounted = false;
    };
  }, []);

  const headerTheme = 'light';

  // Navigation Helpers with Address Bar URL synchronization
  const navigateToHome = () => {
    if (window.location.pathname !== '/') {
      window.history.pushState({}, '', '/');
    }
    setCurrentView('home');
    setSelectedProduct(null);
    setSelectedShop2Category(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const navigateToCategories = () => {
    if (window.location.pathname !== '/categories') {
      window.history.pushState({}, '', '/categories');
    }
    setCurrentView('categories');
    setSelectedProduct(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const navigateToTrackOrder = () => {
    if (window.location.pathname !== '/track-order') {
      window.history.pushState({}, '', '/track-order');
    }
    setCurrentView('trackOrder');
    setSelectedProduct(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const navigateToShop2 = (catId?: number | string | null, searchQuery?: string) => {
    let targetUrl = '/shop';
    const params = new URLSearchParams();
    if (catId) {
      targetUrl = `/product-category/${catId}`;
    }
    if (searchQuery) {
      params.set('search', searchQuery);
      targetUrl += (targetUrl.includes('?') ? '&' : '?') + params.toString();
    }
    if (window.location.pathname + window.location.search !== targetUrl) {
      window.history.pushState({}, '', targetUrl);
    }
    setSelectedShop2Category(catId ? String(catId) : null);
    setSelectedShop2SearchQuery(searchQuery || '');
    setCurrentView('shop2');
    setSelectedProduct(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const openProductDetail = (product: WCProduct, notice = false) => {
    const slugStr = getProductSlug(product);
    const targetUrl = `/product/${slugStr}`;
    if (window.location.pathname !== targetUrl) {
      window.history.pushState({}, '', targetUrl);
    }
    setSelectedProduct(product);
    setShowVariationNotice(notice);
    setCurrentView('productDetail');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const navigateToInfoPage = (slug: InfoPageSlug) => {
    let targetUrl = `/${slug}`;
    if (slug === 'about-us') targetUrl = '/about';
    else if (slug === 'contact-us') targetUrl = '/contact';
    else if (slug === 'terms-conditions') targetUrl = '/terms-of-service';

    if (window.location.pathname !== targetUrl) {
      window.history.pushState({}, '', targetUrl);
    }
    setInfoPageSlug(slug);
    setCurrentView('infoPage');
    setSelectedProduct(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Cart Handlers
  const handleAddToCart = (product: WCProduct, quantity = 1) => {
    setCartItems((prev) => {
      const existingIndex = prev.findIndex((item) => item.product.id === product.id);
      if (existingIndex > -1) {
        const updated = [...prev];
        updated[existingIndex].quantity += quantity;
        return updated;
      }
      return [...prev, { product, quantity }];
    });
    setIsCartOpen(true);
  };

  const handleOrderWhatsAppDirect = (product: WCProduct, quantity = 1) => {
    setCartItems((prev) => {
      const existingIndex = prev.findIndex((item) => item.product.id === product.id);
      if (existingIndex > -1) {
        const updated = [...prev];
        updated[existingIndex].quantity += quantity;
        return updated;
      }
      return [...prev, { product, quantity }];
    });
    setIsWhatsAppCheckoutMode(true);
    setIsCheckoutOpen(true);
  };

  // Card Add To Cart Router (Redirects to Product Page if product has variations/attributes)
  const handleCardAddToCart = (product: WCProduct, e?: React.MouseEvent) => {
    if (e) e.stopPropagation();
    const hasOptions =
      (product.attributes && product.attributes.length > 0) ||
      (product as any).type === 'variable' ||
      ((product as any).variations && (product as any).variations.length > 0);

    if (hasOptions) {
      openProductDetail(product, true);
    } else {
      handleAddToCart(product, 1);
    }
  };

  const handleUpdateCartQuantity = (productId: number, delta: number) => {
    setCartItems((prev) =>
      prev
        .map((item) => {
          if (item.product.id === productId) {
            const newQty = item.quantity + delta;
            return newQty > 0 ? { ...item, quantity: newQty } : null;
          }
          return item;
        })
        .filter(Boolean) as CartItem[]
    );
  };

  const handleRemoveCartItem = (productId: number) => {
    setCartItems((prev) => prev.filter((i) => i.product.id !== productId));
  };

  const cartTotalAmount = cartItems.reduce((sum, item) => {
    const price = parseFloat(item.product.sale_price || item.product.price || '0');
    return sum + price * item.quantity;
  }, 0);

  const cartItemCount = cartItems.reduce((sum, item) => sum + item.quantity, 0);

  const scrollToCategories = () => {
    if (currentView !== 'home') {
      setCurrentView('home');
    }
    setTimeout(() => {
      const el = document.getElementById('health-beauty') || document.getElementById('categories-section');
      if (el) {
        el.scrollIntoView({ behavior: 'smooth' });
      }
    }, 100);
  };

  return (
    <div className="min-h-screen bg-[#FCF8F5] flex flex-col font-sans selection:bg-rose-500 selection:text-white">
      {/* Top Promo Code Announcement Bar */}
      <TopPromoBar />

      <main className="min-h-screen flex flex-col relative flex-1">
        
        {/* Header */}
        <Header
          theme={headerTheme}
          currentView={currentView}
          currentInfoPage={infoPageSlug}
          onNavigate={(view) => {
            if (view === 'home') navigateToHome();
            if (view === 'shop2') navigateToShop2();
            if (view === 'categories') navigateToCategories();
          }}
          onNavigateInfoPage={(slug) => navigateToInfoPage(slug)}
          onSelectCategory={(catSlug) => navigateToShop2(catSlug)}
          cartCount={cartItemCount}
          cartTotal={cartTotalAmount}
          wishlistCount={wishlistItems.length}
          onOpenSearch={() => setIsSearchOpen(true)}
          onOpenCart={() => setIsCartOpen(true)}
          onOpenWishlist={() => setIsWishlistOpen(true)}
          onOpenTracking={navigateToTrackOrder}
        />

        {/* VIEW 0: SECRET ADMIN PANEL (/admin12345) */}
        {currentView === 'admin' && (
          <AdminPanel onBackToStore={navigateToHome} />
        )}

        {/* VIEW: DEDICATED CATEGORIES PAGE (/categories) */}
        {currentView === 'categories' && (
          <CategoriesPage
            categories={categories}
            products={products}
            onSelectCategory={(catSlug) => navigateToShop2(catSlug)}
            onSelectProduct={openProductDetail}
            onAddToCart={(prod) => handleCardAddToCart(prod)}
            onNavigateHome={navigateToHome}
            onNavigateShop={() => navigateToShop2()}
          />
        )}

        {/* VIEW 1: PRODUCT DETAIL PAGE (/product/:slug) */}
        {currentView === 'productDetail' && (
          <ProductDetailPage
            product={selectedProduct}
            allProducts={products}
            onBack={() => navigateToShop2()}
            onSelectProduct={openProductDetail}
            onAddToCart={handleAddToCart}
            onOrderWhatsAppDirect={handleOrderWhatsAppDirect}
            selectVariationNotice={showVariationNotice}
          />
        )}

        {/* VIEW 2: EXPLORE CATEGORIES & SHOP PAGE (/shop) */}
        {currentView === 'shop2' && (
          <Shop2Page
            products={products}
            categories={categories}
            initialCategoryId={selectedShop2Category}
            initialSearchQuery={selectedShop2SearchQuery}
            onSelectProduct={openProductDetail}
            onAddToCart={(prod) => handleCardAddToCart(prod)}
            onNavigateHome={navigateToHome}
          />
        )}

        {/* VIEW 3: HOMEPAGE */}
        {currentView === 'home' && (
          <>
            {/* Dark Hero */}
            <HeroDark
              onExploreClick={() => navigateToShop2()}
              onSearchSubmit={(searchQuery) => navigateToShop2(null, searchQuery)}
            />

            {/* Light Category Intro */}
            <div id="categories-section" className="pt-6">
              <CategoryHeader onExploreClick={() => navigateToShop2()} />
            </div>

            {/* Category Showcase Cards */}
            <CategoryCards onSelectCategory={(catId) => navigateToShop2(catId)} />

            {/* Featured Products Grid Preview */}
            <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 space-y-8">
              <div className="flex flex-col sm:flex-row items-center justify-between gap-4 border-b border-[#F2E5D9] pb-4">
                <div className="space-y-1 text-center sm:text-left">
                  <span className="text-xs font-bold tracking-widest text-[#C81E3D] uppercase flex items-center justify-center sm:justify-start gap-1.5">
                    <Sparkles className="w-3.5 h-3.5" />
                    <span>FULL PRODUCTS CATALOG</span>
                  </span>
                  <h2 className="text-2xl sm:text-3xl font-bold font-playfair text-[#1E2432]">
                    Popular Items in Our Collection
                  </h2>
                </div>

                <button
                  onClick={() => navigateToShop2()}
                  className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[#C81E3D] text-white font-bold text-xs uppercase tracking-wider hover:bg-[#A6142E] transition-all shadow-sm cursor-pointer"
                >
                  <Store className="w-4 h-4" />
                  <span>View All Products in Shop</span>
                  <ArrowRight className="w-4 h-4" />
                </button>
              </div>

              <div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 sm:gap-6">
                {products.length === 0 ? (
                  Array.from({ length: 10 }).map((_, idx) => (
                    <ProductCardSkeleton key={idx} />
                  ))
                ) : (
                  products.slice(0, 10).map((prod) => (
                    <ProductCard
                      key={prod.id}
                      product={prod}
                      onSelectProduct={openProductDetail}
                      onAddToCart={(p, e) => handleCardAddToCart(p, e)}
                    />
                  ))
                )}
              </div>
            </section>

            {/* Recently Viewed Products */}
            <RecentlyViewedSection
              onSelectProduct={openProductDetail}
              onAddToCart={(p) => handleCardAddToCart(p)}
            />

            {/* Our Official Partners Section */}
            <PartnersSection />

            {/* Feature Bar */}
            <FeatureBar />
          </>
        )}

        {/* VIEW 4: INFORMATIONAL SUPPORT PAGES */}
        {currentView === 'infoPage' && (
          <InfoPage
            slug={infoPageSlug}
            onBackToHome={navigateToHome}
            onNavigatePage={navigateToInfoPage}
            onNavigateShop={() => navigateToShop2()}
          />
        )}

        {/* VIEW 5: DEDICATED ORDER & COURIER TRACKING PAGE (/track-order) */}
        {currentView === 'trackOrder' && (
          <OrderTrackingPage
            onBackToHome={navigateToHome}
            onNavigateShop={() => navigateToShop2()}
          />
        )}

        {/* Footer */}
        <Footer
          onOpenTracking={navigateToTrackOrder}
          onNavigatePage={navigateToInfoPage}
          onNavigateShop={() => navigateToShop2()}
        />

        {/* Floating WhatsApp Support Button */}
        <WhatsAppFloating />

      </main>

      {/* Search Modal */}
      <SearchModal
        isOpen={isSearchOpen}
        onClose={() => setIsSearchOpen(false)}
        products={products}
        onSelectProduct={openProductDetail}
        onNavigateShop2={(searchQuery) => navigateToShop2(null, searchQuery)}
      />

      {/* Cart Drawer */}
      <CartDrawer
        isOpen={isCartOpen}
        onClose={() => setIsCartOpen(false)}
        cartItems={cartItems}
        onUpdateQuantity={handleUpdateCartQuantity}
        onRemoveItem={handleRemoveCartItem}
        onClearCart={() => {
          setCartItems([]);
          localStorage.removeItem('timenlife_cart_session');
        }}
        onOpenCheckout={(isWhatsApp = false) => {
          setIsWhatsAppCheckoutMode(isWhatsApp);
          setIsCheckoutOpen(true);
        }}
      />

      {/* Direct Order / WhatsApp Order Checkout Modal */}
      <CheckoutModal
        isOpen={isCheckoutOpen}
        onClose={() => setIsCheckoutOpen(false)}
        cartItems={cartItems}
        initialWhatsAppMode={isWhatsAppCheckoutMode}
        onClearCart={() => {
          setCartItems([]);
          localStorage.removeItem('timenlife_cart_session');
        }}
        onOrderSuccess={(order) => {
          setCartItems([]);
          localStorage.removeItem('timenlife_cart_session');
        }}
      />

      {/* Order & Leopards Courier Tracking Modal */}
      <OrderTrackingModal
        isOpen={isTrackingOpen}
        onClose={() => setIsTrackingOpen(false)}
      />

      {/* Saved Wishlist Modal */}
      <WishlistModal
        isOpen={isWishlistOpen}
        onClose={() => setIsWishlistOpen(false)}
        onAddToCart={(p) => handleCardAddToCart(p)}
        onSelectProduct={openProductDetail}
      />

    </div>
  );
}
