import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { GlobalThemeHeader } from './components/ThemeHeaders';
import MobileBottomNav from './components/MobileBottomNav';
import { GlobalThemeFooter } from './components/ThemeFooters';
import CartDrawer from './components/CartDrawer';
import ProductDetailPage from './components/ProductDetailPage';
import CheckoutPopup from './components/CheckoutPopup';
import AdminDashboard from './components/AdminDashboard';
import AdminLogin from './components/AdminLogin';
import AuthModal, { CustomerUser } from './components/AuthModal';
import UbaidiChat from './components/UbaidiChat';
import { trackPageView, trackProductView, trackCheckoutStart, trackOrderComplete } from './analytics';
import MainLanding from './components/MainLanding';
import SuperAdminDashboard from './components/SuperAdminDashboard';
import TrendingPage from './components/TrendingPage';
import ShopPage from './components/ShopPage';
import AboutPage from './components/AboutPage';
import ContactPage from './components/ContactPage';
import BlogPage from './components/BlogPage';
import BrandsPage from './components/BrandsPage';
import LegalPages from './components/LegalPages';
import LandingPage from './components/LandingPage';
import {
  FeaturesPage, ThemesPage, AIMessengerPage,
  CareerPage, PressPage, PartnersPage, HelpCenterPage,
  PrivacyPolicyPage, TermsPage, ShophyAboutPage, ShophyContactPage
} from './components/SitePages';
import MainFAQPage from './components/MainFAQPage';
import ProductLandingPage from './components/ProductLandingPage';
import ProductLandingPage01 from './components/ProductLandingPage01';
import ProductLandingPage02 from './components/ProductLandingPage02';
import ProductLandingPage03 from './components/ProductLandingPage03';
import ProductLandingPage04 from './components/ProductLandingPage04';
import ProductLandingPage05 from './components/ProductLandingPage05';
import ProductLandingPage06 from './components/ProductLandingPage06';
import HomePage01 from './components/HomePage01';
import HomePage02 from './components/HomePage02';
import HomePage03 from './components/HomePage03';
import HomePage04 from './components/HomePage04';
import HomePage05 from './components/HomePage05';
import CustomPageView from './components/CustomPageView';
import FeaturesRow from './components/FeaturesRow';
import { PromoBannersRow1, PromoBannersRow2 } from './components/PromoBanners';
import { LargePromoBanner, PopularCompanies } from './components/SpecialBanners';
import { CartItem, Product, SiteSettings, Order, View, Testimonial, Lead } from './types';
import { TESTIMONIALS } from './constants';
import { initGTM, pushToDataLayer, gtmEvents } from './utils/tagmeneger';
import { api } from './lib/api';
import { Loader2 } from 'lucide-react';

// ── Store-scoped cache keys — prevents cross-subdomain cache contamination ────
const _storeSlug = (() => {
  try {
    const hostname = window.location.hostname;
    const parts = hostname.split('.');
    if (hostname.includes('localhost')) {
      if (parts.length > 1 && parts[0] !== 'localhost') return parts[0];
    } else {
      if (parts.length >= 3 && parts[0] !== 'www' && !/^\d+$/.test(parts[0])) return parts[0];
    }
    return localStorage.getItem('preview_store_slug') || 'default';
  } catch { return 'default'; }
})();

const CACHE_KEYS = {
  PRODUCTS: `sf_${_storeSlug}_products`,
  TESTIMONIALS: `sf_${_storeSlug}_testimonials`,
  SETTINGS: `sf_${_storeSlug}_settings`,
  PAGE_VIEWS: `sf_${_storeSlug}_page_views`,
  CONTENT_VIEWS: `sf_${_storeSlug}_content_views`
};

// ✅ Clear demo products from localStorage if they were cached from constants (IDs: '1', '2', '3')
const DEMO_PRODUCT_IDS = new Set(['1', '2', '3']);
(() => {
  try {
    const cached = localStorage.getItem(CACHE_KEYS.PRODUCTS);
    if (cached) {
      const parsed = JSON.parse(cached);
      // If all cached products are demo products, clear the cache
      if (Array.isArray(parsed) && parsed.length > 0 && parsed.every((p: any) => DEMO_PRODUCT_IDS.has(String(p.id)))) {
        localStorage.removeItem(CACHE_KEYS.PRODUCTS);
        console.log('🧹 Cleared demo products from cache');
      }
    }
  } catch { }
})();

// ✅ One-time migration: clear stale 'sf_default_*' cache that was shared across all tenants
// (caused by the old parts.length >= 3 bug — now fixed to >= 2)
(() => {
  try {
    if (_storeSlug !== 'default') {
      // Remove old shared cache keys that may have wrong tenant's data
      ['sf_default_settings', 'sf_default_products', 'sf_default_testimonials'].forEach(k => {
        if (localStorage.getItem(k)) {
          localStorage.removeItem(k);
          console.log('🧹 Cleared stale shared cache:', k);
        }
      });
    }
  } catch { }
})();

const BRAND_LOGO = '';

const createSlug = (text: string) => {
  if (!text) return '';
  return text
    .normalize('NFC')
    .toLowerCase()
    .trim()
    .replace(/[^\u0980-\u09FFa-zA-Z0-9\s-]/g, '')
    .replace(/\s+/g, '-');
};

// =====================================================
// getDisplayName: Bangla-first display helper
// Use this everywhere for product name display (NOT for URL slugs)
// Rule: prefer nameBangla (BN), fallback to name (EN) if BN is missing/corrupted
// =====================================================
export const getDisplayName = (nameBangla?: string, nameEn?: string): string => {
  const bn = (nameBangla || '').trim();
  // Valid if contains at least one Bengali Unicode character (U+0980–U+09FF)
  if (bn && /[\u0980-\u09FF]/.test(bn)) return bn;
  return nameEn || bn || 'Unnamed';
};


const mapProduct = (p: any): Product => ({
  id: p.id,
  name: p.name || '',
  nameBangla: (() => {
    // Store raw value from DB — let display layer handle corruption fallback
    const bn = (p.name_bangla || p.nameBangla || '').trim();
    // If valid Bangla, return it. If '????' or empty, fall back to English for now.
    if (bn && /[\u0980-\u09FF]/.test(bn)) return bn;
    return p.name || '';
  })(),
  price: Number(p.price) || 0,
  priceMap: p.price_map || p.priceMap || {},
  priceConfigs: p.price_configs || p.priceConfigs || {},
  highlight: p.highlight || '',
  image: p.image || '',
  category: p.category || 'Basic',
  description: p.description || '',
  usage: p.product_usage || p.usage || [],
  sizes: p.sizes || [],
  isFeatured: p.is_featured === 1 || p.is_featured === true || p.isFeatured === true,
  features: p.features || [],
  faqs: p.faqs || [],
  qualityStandards: p.quality_standards || p.qualityStandards || [],
  usageTips: p.usage_tips || p.usageTips || [],
  packageSectionImage: p.package_section_image || p.packageSectionImage,
  freeDeliveryEnabled: p.free_delivery_enabled === 1 || p.free_delivery_enabled === true || p.freeDeliveryEnabled === true,
  // ✅ Stock fields
  stock: Number(p.stock ?? 0),
  lowStockThreshold: Number(p.low_stock_threshold ?? p.lowStockThreshold ?? 20),
  variant_stock: (() => {
    const vs = p.variant_stock;
    if (!vs) return null;
    if (typeof vs === 'string') { try { return JSON.parse(vs); } catch { return null; } }
    if (typeof vs === 'object' && !Array.isArray(vs)) return vs;
    return null;
  })(),
  // ✅ Landing page basic fields
  landingTheme: p.landing_theme || p.landingTheme || 'primary',
  landingTitle: p.landing_title || p.landingTitle,
  landingSubtitle: p.landing_subtitle || p.landingSubtitle,
  landingProductImage: p.landing_product_image || p.landingProductImage,
  landingUsageTitle: p.landing_usage_title || p.landingUsageTitle,
  // ✅ Landing page section fields (previously missing — caused data loss on reload)
  landingProblemTitle: p.landing_problem_title || p.landingProblemTitle,
  landingProblems: p.landing_problems || p.landingProblems || [],
  landingSolutionName: p.landing_solution_name || p.landingSolutionName,
  landingSolutionDesc: p.landing_solution_desc || p.landingSolutionDesc,
  landingSolutionBenefits: p.landing_solution_benefits || p.landingSolutionBenefits || [],
  landingSolutionImage: p.landing_solution_image || p.landingSolutionImage,
  landingBenefitsTitle: p.landing_benefits_title || p.landingBenefitsTitle,
  landingBenefitsSubtitle: p.landing_benefits_subtitle || p.landingBenefitsSubtitle,
  landingWhyChooseUs: p.landing_why_choose_us || p.landingWhyChooseUs || [],
  landingAuthorityTitle: p.landing_authority_title || p.landingAuthorityTitle,
  landingAuthorityPoints: p.landing_authority_points || p.landingAuthorityPoints || [],
  landingGuaranteeTitle: p.landing_guarantee_title || p.landingGuaranteeTitle,
  landingGuaranteeText: p.landing_guarantee_text || p.landingGuaranteeText,
  landingProcessSteps: p.landing_process_steps || p.landingProcessSteps || [],
  landingCtaTitle: p.landing_cta_title || p.landingCtaTitle,
  landingCtaSubtitle: p.landing_cta_subtitle || p.landingCtaSubtitle,
  landingPackageImages: p.landing_package_images || p.landingPackageImages || [],
  landingTestimonialImages: p.landing_testimonial_images || p.landingTestimonialImages || [],
  // ✅ Landing Page 02-06 specific fields (also previously missing)
  landingOfferTitle: p.landing_offer_title || p.landingOfferTitle,
  landingOfferBadge: p.landing_offer_badge || p.landingOfferBadge,
  landingReviewsTitle: p.landing_reviews_title || p.landingReviewsTitle,
  landingReviewsSubtitle: p.landing_reviews_subtitle || p.landingReviewsSubtitle,
  landingTrustTitle: p.landing_trust_title || p.landingTrustTitle,
  landingTrustElements: p.landing_trust_elements || p.landingTrustElements || [],
  videoTestimonialUrl: p.video_testimonial_url || p.videoTestimonialUrl,
  videoTestimonialTitle: p.video_testimonial_title || p.videoTestimonialTitle,
  comparisonImage1: p.comparison_image1 || p.comparisonImage1,
  comparisonLabel1: p.comparison_label1 || p.comparisonLabel1,
  comparisonImage2: p.comparison_image2 || p.comparisonImage2,
  comparisonLabel2: p.comparison_label2 || p.comparisonLabel2,
});


// =====================================================
// ✅ FIXED: fetchAllData - better error handling
// =====================================================
const fetchAllData = async () => {
  console.log('📡 Fetching all data from PHP API...');

  try {
    const [products, testimonials, settings] = await Promise.allSettled([
      api.products.getAll().catch(err => {
        console.error('Products fetch failed:', err);
        return [];
      }),
      api.testimonials.getAll().catch(err => {
        console.error('Testimonials fetch failed:', err);
        return [];
      }),
      api.settings.get().catch(err => {
        console.error('Settings fetch failed:', err);
        return null;
      })
    ]);

    const data: any = {};

    if (products.status === 'fulfilled' && products.value) {
      const mapped = products.value.map(mapProduct);
      data.products = mapped;
      localStorage.setItem(CACHE_KEYS.PRODUCTS, JSON.stringify(mapped));
      console.log('✅ Products fetched:', mapped.length);
    } else {
      console.warn('Using cached or default products');
    }

    if (testimonials.status === 'fulfilled' && testimonials.value) {
      data.testimonials = testimonials.value;
      localStorage.setItem(CACHE_KEYS.TESTIMONIALS, JSON.stringify(testimonials.value));
      console.log('✅ Testimonials fetched:', testimonials.value.length);
    }

    if (settings.status === 'fulfilled' && settings.value) {
      data.settings = settings.value;
      localStorage.setItem(CACHE_KEYS.SETTINGS, JSON.stringify(settings.value));
      console.log('✅ Settings fetched:', settings.value);
    }

    return data;
  } catch (err) {
    console.error('❌ Failed to fetch from PHP API:', err);
    return {};
  }
};

// Start fetch immediately
const fetchPromise = fetchAllData();

const App: React.FC = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(() => sessionStorage.getItem('shophyfast_admin_auth') === 'true');
  const [showLanding, setShowLanding] = React.useState(() => {
    const path = window.location.pathname;
    const isRoot = path === '/';

    // ✅ Determine if this is a tenant store (subdomain or custom domain)
    const hostname = window.location.hostname;
    
    // Explicitly define what constitutes the main SaaS domain
    const isMainSaaS = hostname === 'localhost' || 
                       hostname === '127.0.0.1' || 
                       hostname === 'shophyfast.com' || 
                       hostname === 'www.shophyfast.com';

    // If it's not the main SaaS domain, it must be a tenant store
    let isStoreSub = !isMainSaaS;

    // Always show MainLanding on the root path of the main domain
    return isRoot && !isStoreSub;
  });
  const [orders, setOrders] = useState<Order[]>([]);
  const [leads, setLeads] = useState<Lead[]>([]);

  // ── Customer Auth ──────────────────────────────────────────────────────────
  const [customerUser, setCustomerUser] = useState<CustomerUser | null>(() => {
    try {
      const saved = localStorage.getItem('cust_user');
      return saved ? JSON.parse(saved) : null;
    } catch { return null; }
  });
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
  const [authModalTab, setAuthModalTab] = useState<'login' | 'register'>('login');

  const handleCustomerLogin = useCallback((user: CustomerUser, token: string) => {
    setCustomerUser(user);
    localStorage.setItem('cust_user', JSON.stringify(user));
    localStorage.setItem('cust_token', token);
    setIsAuthModalOpen(false);
  }, []);

  const handleCustomerLogout = useCallback(() => {
    setCustomerUser(null);
    localStorage.removeItem('cust_user');
    localStorage.removeItem('cust_token');
    fetch('/api/customer-auth?action=logout', { method: 'POST' }).catch(() => { });
  }, []);

  const openAuthModal = useCallback((tab: 'login' | 'register' = 'login') => {
    setAuthModalTab(tab);
    setIsAuthModalOpen(true);
  }, []);

  // =====================================================
  // ✅ FIXED: Load from cache with proper error handling
  // Never show demo/constants products — API or cache only
  // =====================================================
  const [products, setProducts] = useState<Product[]>(() => {
    try {
      const cached = localStorage.getItem(CACHE_KEYS.PRODUCTS);
      if (cached) {
        const parsed = JSON.parse(cached).map(mapProduct);
        if (parsed.length > 0) {
          console.log('⚡ Products from cache');
          return parsed;
        }
      }
    } catch (err) {
      console.error('Error loading products from cache:', err);
    }
    return []; // ✅ Empty — never fall back to demo/constants
  });

  // ✅ True immediately if valid cache exists, false until API responds
  const [isProductsLoaded, setIsProductsLoaded] = useState<boolean>(() => {
    try {
      const cached = localStorage.getItem(CACHE_KEYS.PRODUCTS);
      if (cached) return JSON.parse(cached).length > 0;
    } catch { }
    return false;
  });

  const [testimonials, setTestimonials] = useState<Testimonial[]>(() => {
    try {
      const cached = localStorage.getItem(CACHE_KEYS.TESTIMONIALS);
      if (cached) {
        console.log('⚡ Testimonials from cache');
        return JSON.parse(cached);
      }
      return TESTIMONIALS;
    } catch (err) {
      console.error('Error loading testimonials from cache:', err);
      return TESTIMONIALS;
    }
  });

  const [settings, setSettings] = useState<SiteSettings>(() => {
    try {
      const cached = localStorage.getItem(CACHE_KEYS.SETTINGS);
      if (cached) {
        console.log('⚡ Settings from cache:', JSON.parse(cached));
        return JSON.parse(cached);
      }
    } catch (e) {
      console.error('Error loading settings from cache:', e);
    }

    return {
      logo: BRAND_LOGO,
      footerLogo: BRAND_LOGO,
      favicon: BRAND_LOGO,
      gtmId: '',
      promiseImage: BRAND_LOGO,
      creativeImages: [],
      address: 'হাটহাজারী,চট্টগ্রাম,বাংলাদেশ',
      phone: '+880 1790-014219',
      email: 'hello@shophyfast.com',
      heroTitle: 'Premium spices from Bangladesh — direct from farm',
      heroSubtitle: 'Experience authentic flavors. Our spices are hand-picked to bring the true taste of Bengal to your kitchen.',
      heroImage: 'https://images.unsplash.com/photo-1596040033229-a9821ebd058d?auto=format&fit=crop&q=80&w=2000',
      free_delivery_enabled: true
    };
  });

  // Track page view
  useEffect(() => {
    const pageViews = localStorage.getItem(CACHE_KEYS.PAGE_VIEWS);
    const newCount = pageViews ? parseInt(pageViews) + 1 : 1;
    localStorage.setItem(CACHE_KEYS.PAGE_VIEWS, newCount.toString());
  }, []);

  const initialPathInfo = useMemo(() => {
    let path = window.location.pathname.normalize('NFC').split('?')[0];
    if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
    const decodedPath = decodeURIComponent(path);

    let view: View = 'home';
    let slug = '';

    if (decodedPath.startsWith('/landing/')) {
      view = 'product-landing';
      slug = decodedPath.replace('/landing/', '');
    } else if (decodedPath.startsWith('/product/')) {
      view = 'product-detail';
      slug = decodedPath.replace('/product/', '');
    } else if (decodedPath.startsWith('/page/')) {
      view = 'custom-page';
      slug = decodedPath.replace('/page/', '');
    } else {
      const simpleViews: Record<string, View> = {
        '/shop': 'shop',
        '/about': 'about',
        '/contact': 'contact',
        '/landing': 'landing',
        '/admin': 'admin',
        '/login': 'home',
        '/signup': 'home',
        '/delivery-policy': 'delivery-policy',
        '/refund-policy': 'refund-policy',
        '/terms': 'terms',
        '/return-policy': 'return-policy',
        '/exchange-policy': 'exchange-policy',
        '/cancellation-policy': 'cancellation-policy',
        '/refund-only-policy': 'refund-only-policy',
      };
      // Open auth modal if /login or /signup
      if (decodedPath === '/login' || decodedPath === '/signup') {
        setTimeout(() => openAuthModal(decodedPath === '/signup' ? 'register' : 'login'), 200);
      }
      view = simpleViews[decodedPath] || 'home';
    }

    return { view, slug, path: decodedPath };
  }, []);

  const [currentView, setCurrentView] = useState<View | string>(initialPathInfo.view);
  const [shopCategory, setShopCategory] = useState<string | null>(null);

  const [selectedProduct, setSelectedProduct] = useState<Product | null>(() => {
    if (initialPathInfo.slug && products.length > 0) {
      return products.find(p =>
        createSlug(p.name) === initialPathInfo.slug
      ) || null;
    }
    return null;
  });

  // =====================================================
  // ✅ FIXED: Update with API data - better merge logic
  // =====================================================
  useEffect(() => {
    fetchPromise.then((data) => {
      // ✅ FIXED: Always replace products with API data, never show demo products
      if (data.products && data.products.length > 0) {
        setProducts(data.products);

        // Update selected product if needed
        if (initialPathInfo.slug) {
          const product = data.products.find((p: Product) =>
            createSlug(p.name) === initialPathInfo.slug
          );
          if (product) setSelectedProduct(product);
        }
      } else {
        // API returned no products — still mark as loaded (show empty state, not demo)
        console.warn('No products from API — showing empty product list');
      }
      // Mark products as loaded regardless (hides loading spinner)
      setIsProductsLoaded(true);

      // Update testimonials
      if (data.testimonials && data.testimonials.length > 0) {
        setTestimonials(data.testimonials);
      }

      // Update settings
      if (data.settings) {
        // ✅ Unknown subdomain redirect: only fire when hostname actually has a real subdomain
        // Do NOT use _storeSlug here — it falls back to 'default' on localhost (truthy = loop!)
        const _realSubdomain = (() => {
          const h = window.location.hostname;
          const p = h.split('.');
          if (h.includes('localhost')) {
            if (p.length > 1 && p[0] !== 'localhost') return p[0];
          } else {
            if (p.length >= 3 && p[0] !== 'www' && !/^\d+$/.test(p[0])) return p[0];
          }
          return ''; // No actual subdomain in browser URL
        })();

        if ((data.settings as any).__unknownTenant && _realSubdomain) {
          const mainHost = window.location.hostname.slice(_realSubdomain.length + 1); // strip "sadik."
          const port = window.location.port ? ':' + window.location.port : '';
          console.warn(`⚠️ Unknown subdomain "${_realSubdomain}" — redirecting to main domain`);
          window.location.replace(`${window.location.protocol}//${mainHost}${port}/`);
          return;
        }

        console.log('✅ Settings from PHP API:', data.settings);
        setSettings((prev: SiteSettings) => {
          const updated = { ...prev, ...data.settings };
          console.log('Updated settings:', updated);
          return updated;
        });
      }
    }).catch(() => {
      // Even on error, mark as loaded so we don't show spinner forever
      setIsProductsLoaded(true);
    });
  }, []);

  // Fetch orders and leads
  useEffect(() => {
    const fetchOrdersAndLeads = async () => {
      try {
        const [ordersData, leadsData] = await Promise.allSettled([
          api.orders.getAll(),
          api.leads.getAll()
        ]);

        if (ordersData.status === 'fulfilled' && ordersData.value) {
          const data = ordersData.value;
          setOrders(Array.isArray(data) ? data : (Array.isArray(data.data) ? data.data : []));
        }

        if (leadsData.status === 'fulfilled' && leadsData.value) {
          const data = leadsData.value;
          setLeads(Array.isArray(data) ? data : (Array.isArray(data.data) ? data.data : []));
        }
      } catch (err) {
        console.error('Error fetching orders/leads:', err);
      }
    };

    // ✅ FIX: Re-fetch products with tenant token when admin logs in
    // (fetchPromise may have run before token was saved on fresh login)
    const refetchProducts = async () => {
      try {
        const freshProducts = await api.products.getAll();
        if (freshProducts && freshProducts.length > 0) {
          const mapped = freshProducts.map(mapProduct);
          setProducts(mapped);
          localStorage.setItem(CACHE_KEYS.PRODUCTS, JSON.stringify(mapped));
          setIsProductsLoaded(true);
          console.log('✅ Products refreshed for admin:', mapped.length);
        }
      } catch (err) {
        console.error('Error re-fetching products for admin:', err);
      }
    };

    if (isAdminLoggedIn) {
      fetchOrdersAndLeads();
      refetchProducts(); // ✅ Always re-fetch products with tenant token on admin login
    }
  }, [isAdminLoggedIn]);

  // Favicon and Title update
  useEffect(() => {
    if (settings.favicon) {
      let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
      if (!link) {
        link = document.createElement('link');
        link.rel = 'icon';
        document.getElementsByTagName('head')[0].appendChild(link);
      }
      link.href = settings.favicon;
    }
    const newTitle = settings.tabTitle || settings.siteName || 'ShophyFast E-commerce';
    if (document.title !== newTitle) {
      document.title = newTitle;
    }
  }, [settings.favicon, settings.siteName, settings.tabTitle]);

  // GTM initialization — hot-swap when admin changes ID
  useEffect(() => {
    const rawId = (settings.gtm_id || settings.gtmId)?.replace(/\s+/g, '') || '';
    if (!rawId) return;

    initGTM(rawId);

    // ✅ page_view on every view change
    gtmEvents.pageView(currentView, window.location.pathname, rawId);
  }, [currentView, settings.gtm_id, settings.gtmId]);

  // ── Analytics: track page views ──────────────────────────────────────────
  useEffect(() => {
    // Track page view on every navigation (except admin view)
    if (currentView !== 'admin') {
      trackPageView(String(currentView));
    }
  }, [currentView]);

  // Handle routing
  const handleRouting = useCallback(() => {
    let path = window.location.pathname.normalize('NFC').split('?')[0];
    if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
    const decodedPath = decodeURIComponent(path);

    if (decodedPath.startsWith('/landing/')) {
      const slug = decodedPath.replace('/landing/', '');
      const product = products.find(p =>
        createSlug(p.name) === slug
      );
      if (product) {
        setSelectedProduct(product);
        setCurrentView('product-landing');
      } else {
        setCurrentView('landing');
      }
    } else if (decodedPath.startsWith('/product/')) {
      const slug = decodedPath.replace('/product/', '');
      const product = products.find(p =>
        createSlug(p.name) === slug
      );
      if (product) {
        setSelectedProduct(product);
        setCurrentView('product-detail');
      } else {
        setCurrentView('shop');
      }
    } else {
      const viewMap: Record<string, View> = {
        '/shop': 'shop',
        '/about': 'about',
        '/contact': 'contact',
        '/blog': 'blog',
        '/brands': 'brands',
        '/landing': 'landing',
        '/admin': 'admin',
        '/trending': 'trending',
        '/': 'home',
        '/delivery-policy': 'delivery-policy',
        '/refund-policy': 'refund-policy',
        '/terms': 'terms',
        '/return-policy': 'return-policy',
        '/exchange-policy': 'exchange-policy',
        '/cancellation-policy': 'cancellation-policy',
        '/refund-only-policy': 'refund-only-policy',
      };
      setCurrentView(viewMap[decodedPath] || 'home');
      setSelectedProduct(null);
    }
  }, [products]);

  useEffect(() => {
    window.addEventListener('popstate', handleRouting);
    handleRouting();
    return () => window.removeEventListener('popstate', handleRouting);
  }, [handleRouting]);

  const [directCheckoutProduct, setDirectCheckoutProduct] = useState<{ product: Product, size?: string } | null>(null);
  const [isCartCheckoutOpen, setIsCartCheckoutOpen] = useState(false);

  // =====================================================
  // ✅ FIXED: addToCart function
  // =====================================================
  const addToCart = useCallback((product: Product, size?: string, price?: number) => {
    const itemPrice = price || product.price;
    const itemId = size ? `${product.id}-${size}` : product.id;

    // ✅ Full GA4 + Facebook Pixel add_to_cart event
    gtmEvents.addToCart({
      item_id: product.id,
      item_name: product.name,
      item_name_bn: product.nameBangla || '',
      item_category: product.category || '',
      item_variant: size || '',
      price: itemPrice,
      quantity: 1,
    });

    setCartItems(prev => {
      const existing = prev.find(item => item.id === itemId);
      if (existing) {
        return prev.map(item =>
          item.id === itemId
            ? { ...item, quantity: item.quantity + 1 }
            : item
        );
      }
      return [...prev, {
        ...product,
        id: itemId,
        selectedSize: size,
        currentPrice: itemPrice,
        price: itemPrice,
        quantity: 1
      }];
    });

    setIsCartOpen(true);
  }, []);

  // =====================================================
  // ✅ FIXED: addOrder function
  // =====================================================
  const addOrder = useCallback((order: Order) => {
    setOrders(prev => [...prev, order]);
    if (!directCheckoutProduct) setCartItems([]);
    console.log('✅ Local order added successfully:', order.id);
  }, [directCheckoutProduct]);


  // ── Analytics: track checkout start ─────────────────────────────────────
  const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
  const openCheckout = useCallback((product?: Product) => {
    trackCheckoutStart(product?.id);
    setIsCheckoutOpen(true);
  }, []);

  // ── Analytics: track completed order ────────────────────────────────────
  const addOrderWithTracking = useCallback(async (order: Order) => {
    await addOrder(order);
    trackOrderComplete(order.id);
  }, [addOrder]);

  // Navigation
  const navigateTo = useCallback((view: string, data?: any) => {
    setSelectedProduct(null);
    if (view === 'shop' && data?.category) {
      setShopCategory(data.category);
    } else {
      setShopCategory(null);
    }
    setCurrentView(view as View);
    window.scrollTo({ top: 0, behavior: 'smooth' });
    const path = view === 'home' ? '/' : `/${view}`;
    window.history.pushState({ view }, '', path);
  }, []);

  // ── Analytics: track product detail views ───────────────────────────────
  useEffect(() => {
    if (selectedProduct && currentView === 'product') {
      trackProductView(selectedProduct.id, selectedProduct.name);
    }
  }, [selectedProduct, currentView]);

  // Admin login
  const handleAdminLogin = (success: boolean) => {
    if (success) {
      sessionStorage.setItem('shophyfast_admin_auth', 'true');
      setIsAdminLoggedIn(true);
    }
  };

  const handleAdminLogout = useCallback(() => {
    sessionStorage.removeItem('shophyfast_admin_auth');
    setIsAdminLoggedIn(false);
    navigateTo('home');
  }, [navigateTo]);

  const featuredProducts = useMemo(() => products, [products]);
  const cartCount = useMemo(() => cartItems.reduce((acc, item) => acc + item.quantity, 0), [cartItems]);

  // ── Super Admin route ─────────────────────────────────────────────────────
  if (currentView === 'super-admin' || window.location.pathname.startsWith('/super-admin')) {
    return <SuperAdminDashboard />;
  }

  // ── Static site pages (footer links) — main domain only ──────────────────
  const sitePath = window.location.pathname;
  const goHome = () => { window.history.pushState({}, '', '/'); window.location.reload(); };
  const _hostname2 = window.location.hostname;
  const isMainDomain = _hostname2 === 'localhost' || 
                       _hostname2 === '127.0.0.1' || 
                       _hostname2 === 'shophyfast.com' || 
                       _hostname2 === 'www.shophyfast.com';

  if (isMainDomain) {
    if (sitePath === '/features') return <FeaturesPage onBack={goHome} />;
    if (sitePath === '/themes') return <ThemesPage onBack={goHome} />;
    if (sitePath === '/ai-messenger') return <AIMessengerPage onBack={goHome} />;
    if (sitePath === '/career') return <CareerPage onBack={goHome} />;
    if (sitePath === '/press') return <PressPage onBack={goHome} />;
    if (sitePath === '/partners') return <PartnersPage onBack={goHome} />;
    if (sitePath === '/help') return <HelpCenterPage onBack={goHome} />;
    if (sitePath === '/privacy') return <PrivacyPolicyPage onBack={goHome} />;
    if (sitePath === '/terms') return <TermsPage onBack={goHome} />;
    if (sitePath === '/about') return <ShophyAboutPage onBack={goHome} />;
    if (sitePath === '/blog') return <BlogPage settings={null as any} theme="01" />;
    if (sitePath === '/contact') return <ShophyContactPage onBack={goHome} />;
    if (sitePath === '/faq') return <MainFAQPage onBack={goHome} />;
  }

  // ── Main Landing Page (shophyfast.com homepage) ───────────────────────────
  if (showLanding) {
    return (
      <MainLanding
        onTenantLogin={(tenant, token) => {
          localStorage.setItem('tenant_token', token);
          localStorage.setItem('tenant_data', JSON.stringify(tenant));
          setShowLanding(false);
          navigateTo('admin');
        }}
        onGoToAdmin={() => {
          setShowLanding(false);
          navigateTo('admin');
        }}
      />
    );
  }

  // Admin view
  if (currentView === 'admin') {
    if (isAdminLoggedIn) {
      return (
        <AdminDashboard
          products={products}
          settings={settings}
          orders={orders}
          leads={leads}
          testimonials={testimonials}
          updateProducts={(newProducts: Product[]) => {
            setProducts(newProducts);
            // ✅ FIX: Also sync localStorage cache so page reload shows correct data immediately
            try { localStorage.setItem(CACHE_KEYS.PRODUCTS, JSON.stringify(newProducts)); } catch { }
          }}
          updateSettings={setSettings}
          updateOrders={setOrders}
          updateLeads={setLeads}
          updateTestimonials={setTestimonials}
          onLogout={handleAdminLogout}
        />
      );
    }
    return <AdminLogin onLogin={handleAdminLogin} onClose={() => navigateTo('home')} isFullScreen={true} />;
  }

  // =====================================================
  // Render view
  // =====================================================
  const renderView = () => {
    if (currentView === 'product-landing' && selectedProduct) {
      // ✅ Always use fresh product from products array (fixes admin edit not reflecting immediately)
      const freshProduct = products.find(p => p.id === selectedProduct.id) || selectedProduct;
      const theme = freshProduct.landingTheme || 'primary';
      const LandingComponentProps = {
        product: freshProduct,
        settings,
        testimonials,
        addOrder,
        onNavigate: navigateTo
      };

      if (theme === '01') return <ProductLandingPage01 {...LandingComponentProps} />;
      if (theme === '02') return <ProductLandingPage02 {...LandingComponentProps} />;
      if (theme === '03') return <ProductLandingPage03 {...LandingComponentProps} />;
      if (theme === '04') return <ProductLandingPage04 {...LandingComponentProps} />;
      if (theme === '05') return <ProductLandingPage05 {...LandingComponentProps} />;
      if (theme === '06') return <ProductLandingPage06 {...LandingComponentProps} />;

      // Default to primary
      return <ProductLandingPage {...LandingComponentProps} />;
    }

    if (currentView === 'custom-page' || currentView.startsWith('page/')) {
      const slug = currentView.startsWith('page/') ? currentView.replace('page/', '') : initialPathInfo.slug;
      return <CustomPageView settings={settings} slug={slug} />;
    }
    if (currentView === 'product-detail' && selectedProduct) {
      return <ProductDetailPage
        product={selectedProduct}
        allProducts={products}
        settings={settings}
        onBack={() => navigateTo('home')}
        addToCart={addToCart}
        addOrder={addOrder}
        setIsCartOpen={setIsCartOpen}
        onOrderNow={(p, size) => setDirectCheckoutProduct({ product: p, size })}
      />;
    }
    if (['delivery-policy', 'refund-policy', 'terms', 'return-policy', 'exchange-policy', 'cancellation-policy', 'refund-only-policy'].includes(currentView)) {
      return <LegalPages type={currentView as any} onBack={() => navigateTo('home')} settings={settings} />;
    }
    switch (currentView) {
      case 'shop':
        return <ShopPage
          theme={activeTheme}
          settings={settings}
          products={products}
          initialCategory={shopCategory || 'All'}
          onSelectProduct={(p) => {
            gtmEvents.viewItem({ item_id: p.id, item_name: p.name, item_name_bn: p.nameBangla, item_category: p.category, price: p.price });
            gtmEvents.viewContent({ item_id: p.id, item_name: p.name, item_name_bn: p.nameBangla, item_category: p.category, price: p.price });
            const slug = createSlug(p.name);
            setSelectedProduct(p);
            setCurrentView('product-detail');
            window.history.pushState({ view: 'product-detail' }, '', `/product/${slug}`);
          }}
          onAddToCart={(p) => addToCart(p)}
        />;
      case 'trending':
        return <TrendingPage
          theme={activeTheme}
          settings={settings}
          products={products}
          onSelectProduct={(p) => {
            gtmEvents.viewItem({ item_id: p.id, item_name: p.name, item_name_bn: p.nameBangla, item_category: p.category, price: p.price });
            gtmEvents.viewContent({ item_id: p.id, item_name: p.name, item_name_bn: p.nameBangla, item_category: p.category, price: p.price });
            const slug = createSlug(p.name);
            setSelectedProduct(p);
            setCurrentView('product-detail');
            window.history.pushState({ view: 'product-detail' }, '', `/product/${slug}`);
          }}
          onAddToCart={(p) => addToCart(p)}
        />;
      case 'about':
        return <AboutPage />;
      case 'blog':
        return <BlogPage settings={settings} theme={activeTheme} />;
      case 'brands':
        return <BrandsPage settings={settings} theme={activeTheme} onNavigate={navigateTo} />;
      case 'contact':
        return <ContactPage settings={settings} theme={activeTheme} />;
      case 'landing':
        return <LandingPage
          products={products}
          settings={settings}
          isProductsLoading={false}
          onSelectProduct={(p) => {
            const slug = createSlug(p.name);
            setSelectedProduct(p);
            setCurrentView('product-landing');
            window.history.pushState({ view: 'product-landing' }, '', `/landing/${slug}`);
          }}
        />;
      case 'home':
      default:
        let homeTheme = '01';
        if (settings?.homePageJson) {
          try {
            const parsed = JSON.parse(settings.homePageJson);
            // ✅ FIX: Check 'theme' first (HomePageEditor saves this key)
            // 'activeTheme' is only a backward-compat fallback
            if (parsed.theme) homeTheme = parsed.theme;
            else if (parsed.activeTheme) homeTheme = parsed.activeTheme;
            console.log('🎨 Home Theme Resolved:', homeTheme, '| raw JSON:', settings.homePageJson?.slice(0, 80));
          } catch (e) {
            console.error('🌈 Theme Resolution Error:', e);
          }
        }

        const homeProps = {
          settings,
          featuredProducts,
          isProductsLoaded,
          navigateTo,
          setDirectCheckoutProduct,
          onAddToCart: addToCart,
          onSelectProduct: (p: Product) => {
            // ✅ view_item + ViewContent (Facebook Pixel style)
            gtmEvents.viewItem({ item_id: p.id, item_name: p.name, item_name_bn: p.nameBangla, item_category: p.category, price: p.price });
            gtmEvents.viewContent({ item_id: p.id, item_name: p.name, item_name_bn: p.nameBangla, item_category: p.category, price: p.price });
            const slug = createSlug(p.name);
            setSelectedProduct(p);
            setCurrentView('product-detail');
            window.history.pushState({ view: 'product-detail' }, '', `/product/${slug}`);
          }
        };

        switch (homeTheme) {
          case '02': return <HomePage02 {...homeProps} />;
          case '03': return <HomePage03 {...homeProps} />;
          case '04': return <HomePage04 {...homeProps} />;
          case '05': return <HomePage05 {...homeProps} />;
          case '01':
          default:
            return <HomePage01 {...homeProps} />;
        }
    }
  };

  let activeTheme = '01';
  if (settings?.homePageJson) {
    try {
      const parsed = JSON.parse(settings.homePageJson);
      // ✅ FIX: Check 'theme' first (primary key), 'activeTheme' is backward compat
      if (parsed.theme) activeTheme = parsed.theme;
      else if (parsed.activeTheme) activeTheme = parsed.activeTheme;
    } catch (e) { }
  }

  // Update CSS Variables for Dynamic Theming
  useEffect(() => {
    const hexToRgb = (hex: string) => {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : '99 76 159';
    };

    let themeColor = '#634C9F';
    let hoverColor = '#523A8C';

    switch (activeTheme) {
      case '01':
        themeColor = '#634C9F';
        hoverColor = '#523A8C';
        break;
      case '02':
        themeColor = '#1E1B4B'; // Deep Navy (Matched from ThemeHeader02)
        hoverColor = '#16143A';
        break;
      case '03':
        themeColor = '#E91E63'; // cosmetics pink
        hoverColor = '#C2185B';
        break;
      case '04':
        themeColor = '#F37021'; // organic orange
        hoverColor = '#E05A10';
        break;
      case '05':
        themeColor = '#1A1A1A'; // fashion black
        hoverColor = '#000000';
        break;
    }

    document.documentElement.style.setProperty('--theme-primary', themeColor);
    document.documentElement.style.setProperty('--theme-hover', hoverColor);
    document.documentElement.style.setProperty('--theme-primary-rgb', hexToRgb(themeColor));
    document.documentElement.style.setProperty('--theme-hover-rgb', hexToRgb(hoverColor));

    // Remove any existing theme- classes
    document.body.className = document.body.className.replace(/\btheme-\d{2}\b/g, '').trim();
    // Add the active theme class
    document.body.classList.add(`theme-${activeTheme}`);

    // Optionally force dark mode onto the HTML tag for Theme 05
    if (activeTheme === '05') {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }

  }, [activeTheme]);

  return (
    <div
      className={`min-h-screen ${isDarkMode ? 'dark:bg-slate-900 dark:text-white' : 'bg-white text-black'}`}
      style={{
        /* 
         * DO NOT add transform/filter/perspective here — 
         * those would break fixed positioning of MobileBottomNav.
         * Keep this as a plain stacking context.
         */
        position: 'relative',
      }}
    >
      <GlobalThemeHeader
        theme={activeTheme}
        toggleTheme={() => setIsDarkMode(!isDarkMode)}
        isDarkMode={isDarkMode}
        cartCount={cartCount}
        onCartClick={() => setIsCartOpen(true)}
        logo={settings.logo || ''}
        onNavigate={navigateTo}
        currentView={currentView}
        contactPhone={settings.phone || settings.contactPhone}
        settings={settings}
        customerUser={customerUser}
        onOpenAuth={openAuthModal}
        onCustomerLogout={handleCustomerLogout}
      />
      <main className="flex-1">
        {renderView()}
      </main>

      {currentView !== 'super-admin' && currentView !== 'admin' && (
        <UbaidiChat
          context="shop"
          tenantToken={typeof localStorage !== 'undefined' ? (localStorage.getItem('tenant_token') || undefined) : undefined}
          extra={{
            shopName: settings.siteName || 'Shop',
            shopPhone: settings.phone || settings.contactPhone || '',
            shopAddress: settings.address || '',
            shopEmail: settings.email || '',
            productsList: products.slice(0, 15).map(p => ({
              name: p.nameBangla || p.name,
              price: p.price,
              category: p.category
            }))
          }}
        />
      )}

      <div className="hidden md:block">
        <GlobalThemeFooter
          theme={activeTheme}
          settings={settings}
          onAdminClick={() => navigateTo('admin')}
          onNavigate={navigateTo}
        />
      </div>
      <MobileBottomNav
        currentView={currentView as string}
        onNavigate={navigateTo}
        cartCount={cartCount}
        onCartClick={() => setIsCartOpen(true)}
        theme={activeTheme}
        customerUser={customerUser}
        onOpenAuth={openAuthModal}
      />

      <CartDrawer
        isOpen={isCartOpen}
        onClose={() => setIsCartOpen(false)}
        items={cartItems}
        onRemove={(id) => setCartItems(prev => prev.filter(it => it.id !== id))}
        onUpdateQty={(id, delta) => setCartItems(prev => prev.map(it => it.id === id ? { ...it, quantity: Math.max(1, it.quantity + delta) } : it))}
        onCheckout={() => { setIsCartOpen(false); setIsCartCheckoutOpen(true); }}
      />

      {directCheckoutProduct && (
        <CheckoutPopup
          product={directCheckoutProduct.product}
          settings={settings}
          selectedSize={directCheckoutProduct.size}
          onClose={() => setDirectCheckoutProduct(null)}
          addOrder={addOrder}
        />
      )}

      {isCartCheckoutOpen && (
        <CheckoutPopup
          cartItems={cartItems}
          settings={settings}
          onClose={() => setIsCartCheckoutOpen(false)}
          addOrder={addOrder}
        />
      )}

      {/* Customer Auth Modal */}
      <AuthModal
        isOpen={isAuthModalOpen}
        onClose={() => setIsAuthModalOpen(false)}
        onLogin={handleCustomerLogin}
        defaultTab={authModalTab}
        storeName={settings?.siteName || 'ShophyFast'}
        tenantSlug={(() => {
          // Get tenant slug from localStorage (set when tenant logs into admin)
          const tenantData = localStorage.getItem('tenant_data');
          if (tenantData) { try { return JSON.parse(tenantData).business_slug || ''; } catch { return ''; } }
          return '';
        })()}
      />

    </div>
  );
};

export default App;