import React, { useState, useEffect, useMemo } from 'react';
import {
  Search,
  Filter,
  Sparkles,
  ShoppingBag,
  SlidersHorizontal,
  X,
  Tag,
  FolderTree,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  RotateCcw,
  Truck,
  ShieldCheck,
  Home,
  ArrowLeft,
} from 'lucide-react';
import { WCProduct, WCCategory, getWCProducts, decodeHtmlEntities, stripHtmlTags } from '../services/woocommerce';
import { saveProductsToCache } from '../services/productCache';
import { ProductCard, ProductCardSkeleton } from './ProductCard';

import { getEffectiveProductRating } from '../services/reviewService';

interface Shop2PageProps {
  products: WCProduct[];
  categories: WCCategory[];
  initialCategoryId?: number | string | null;
  initialSearchQuery?: string;
  onSelectProduct: (product: WCProduct) => void;
  onAddToCart: (product: WCProduct) => void;
  onNavigateHome: () => void;
}

export const Shop2Page: React.FC<Shop2PageProps> = ({
  products: initialProducts,
  categories,
  initialCategoryId = null,
  initialSearchQuery = '',
  onSelectProduct,
  onAddToCart,
  onNavigateHome,
}) => {
  const [selectedMainCatId, setSelectedMainCatId] = useState<string>('');
  const [selectedSubCatId, setSelectedSubCatId] = useState<string>('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | string | null>(initialCategoryId);
  const [priceFilter, setPriceFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState(initialSearchQuery || '');
  const [sortBy, setSortBy] = useState<'latest' | 'price-low' | 'price-high' | 'rating'>('latest');

  // Sync prop changes if initialSearchQuery changes
  useEffect(() => {
    if (initialSearchQuery !== undefined) {
      setSearchQuery(initialSearchQuery);
      setCurrentPage(1);
    }
  }, [initialSearchQuery]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [jumpPageInput, setJumpPageInput] = useState<string>('');
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // Paginated Catalog State
  const [pageProducts, setPageProducts] = useState<WCProduct[]>(initialProducts);
  const [totalProductsCount, setTotalProductsCount] = useState<number>(7500);
  const [totalPagesCount, setTotalPagesCount] = useState<number>(313);

  const [expandedCategories, setExpandedCategories] = useState<Record<number, boolean>>({
    217: true,
    428: true,
    75: true,
    316: true,
  });

  // Sync prop changes if initialCategoryId changes
  useEffect(() => {
    if (initialCategoryId !== undefined && initialCategoryId !== null) {
      const matchCat = categories.find(
        (c) => c.id === Number(initialCategoryId) || c.slug.toLowerCase() === String(initialCategoryId).toLowerCase()
      );
      if (matchCat) {
        if (matchCat.parent && matchCat.parent > 0) {
          setSelectedMainCatId(String(matchCat.parent));
          setSelectedSubCatId(String(matchCat.id));
        } else {
          setSelectedMainCatId(String(matchCat.id));
          setSelectedSubCatId('');
        }
      } else {
        setSelectedMainCatId(String(initialCategoryId));
        setSelectedSubCatId('');
      }
      setSelectedCategoryId(initialCategoryId);
      setCurrentPage(1);
    }
  }, [initialCategoryId, categories]);

  // Fetch paginated products from WooCommerce API
  useEffect(() => {
    let isMounted = true;
    async function fetchPageData() {
      setIsLoading(true);
      try {
        const activeCat = selectedSubCatId || selectedMainCatId || selectedCategoryId || undefined;
        const res = await getWCProducts(activeCat, 24, currentPage, searchQuery);
        if (isMounted) {
          if (res.products && res.products.length > 0) {
            setPageProducts(res.products);
            setTotalProductsCount(res.totalProducts || 7500);
            setTotalPagesCount(res.totalPages || Math.ceil((res.totalProducts || 7500) / 24));
            saveProductsToCache(res.products);
          } else {
            setPageProducts([]);
            setTotalProductsCount(0);
            setTotalPagesCount(1);
          }
        }
      } catch (err) {
        if (isMounted) {
          setPageProducts([]);
          setTotalProductsCount(0);
          setTotalPagesCount(1);
        }
      } finally {
        if (isMounted) setIsLoading(false);
      }
    }

    fetchPageData();

    return () => {
      isMounted = false;
    };
  }, [currentPage, selectedMainCatId, selectedSubCatId, selectedCategoryId, searchQuery]);

  // Top-level categories
  const topCategories = useMemo(() => {
    return categories
      .filter((c) => (!c.parent || c.parent === 0) && (c.count > 0 || c.id === 217 || c.id === 428 || c.id === 75 || c.id === 316))
      .map((c) => ({
        ...c,
        name: stripHtmlTags(c.name),
        description: stripHtmlTags(c.description || ''),
      }))
      .sort((a, b) => (b.count || 0) - (a.count || 0));
  }, [categories]);

  // Subcategories for selected main category
  const availableSubcategories = useMemo(() => {
    if (!selectedMainCatId) return [];
    const mainObj = categories.find(
      (c) => c.id === Number(selectedMainCatId) || c.slug.toLowerCase() === String(selectedMainCatId).toLowerCase()
    );
    if (!mainObj) return [];
    return categories
      .filter((c) => c.parent === mainObj.id)
      .map((c) => ({
        ...c,
        name: stripHtmlTags(c.name),
      }))
      .sort((a, b) => (b.count || 0) - (a.count || 0));
  }, [categories, selectedMainCatId]);

  const getSubcategories = (parentId: number) => {
    return categories
      .filter((c) => c.parent === parentId && c.count > 0)
      .map((c) => ({
        ...c,
        name: stripHtmlTags(c.name),
        description: stripHtmlTags(c.description || ''),
      }))
      .sort((a, b) => (b.count || 0) - (a.count || 0));
  };

  // Category Selection Handlers
  const handleMainCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const val = e.target.value;
    setSelectedMainCatId(val);
    setSelectedSubCatId('');
    setSelectedCategoryId(val || null);
    setCurrentPage(1);

    if (val) {
      const matchCat = categories.find((c) => c.id === Number(val) || c.slug === String(val));
      const slug = matchCat ? matchCat.slug : String(val);
      window.history.pushState({}, '', `/product-category/${slug}`);
    } else {
      window.history.pushState({}, '', '/shop');
    }
  };

  const handleSubCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const val = e.target.value;
    setSelectedSubCatId(val);
    setSelectedCategoryId(val || selectedMainCatId || null);
    setCurrentPage(1);

    if (val) {
      const matchCat = categories.find((c) => c.id === Number(val) || c.slug === String(val));
      const slug = matchCat ? matchCat.slug : String(val);
      window.history.pushState({}, '', `/product-category/${slug}`);
    }
  };

  const handleResetFilters = () => {
    setSelectedMainCatId('');
    setSelectedSubCatId('');
    setSelectedCategoryId(null);
    setPriceFilter('all');
    setSortBy('latest');
    setSearchQuery('');
    setCurrentPage(1);
    if (window.location.pathname !== '/shop') {
      window.history.pushState({}, '', '/shop');
    }
  };

  // Toggle category accordion
  const toggleCategoryExpand = (id: number, e: React.MouseEvent) => {
    e.stopPropagation();
    setExpandedCategories((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  // Handle Page Change
  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > totalPagesCount) return;
    setCurrentPage(newPage);
    window.scrollTo({ top: 350, behavior: 'smooth' });
  };

  const handleJumpToPage = (e: React.FormEvent) => {
    e.preventDefault();
    const parsed = parseInt(jumpPageInput, 10);
    if (!isNaN(parsed) && parsed >= 1 && parsed <= totalPagesCount) {
      handlePageChange(parsed);
      setJumpPageInput('');
    }
  };

  // Filtered & Sorted Products
  const filteredPageProducts = useMemo(() => {
    let result = [...pageProducts];

    // Price Filtering
    if (priceFilter === 'under-1000') {
      result = result.filter((p) => parseFloat(p.price || '0') < 1000);
    } else if (priceFilter === '1000-3000') {
      result = result.filter((p) => {
        const pr = parseFloat(p.price || '0');
        return pr >= 1000 && pr <= 3000;
      });
    } else if (priceFilter === '3000-5000') {
      result = result.filter((p) => {
        const pr = parseFloat(p.price || '0');
        return pr >= 3000 && pr <= 5000;
      });
    } else if (priceFilter === '5000-10000') {
      result = result.filter((p) => {
        const pr = parseFloat(p.price || '0');
        return pr >= 5000 && pr <= 10000;
      });
    } else if (priceFilter === 'above-10000') {
      result = result.filter((p) => parseFloat(p.price || '0') > 10000);
    }

    // Sorting
    if (sortBy === 'price-low') {
      result.sort((a, b) => parseFloat(a.price || '0') - parseFloat(b.price || '0'));
    } else if (sortBy === 'price-high') {
      result.sort((a, b) => parseFloat(b.price || '0') - parseFloat(a.price || '0'));
    } else if (sortBy === 'rating') {
      result.sort((a, b) => parseFloat(getEffectiveProductRating(b).averageRating) - parseFloat(getEffectiveProductRating(a).averageRating));
    }

    return result;
  }, [pageProducts, priceFilter, sortBy]);

  const selectedCategoryObj = useMemo(() => {
    const active = selectedSubCatId || selectedMainCatId || selectedCategoryId;
    if (!active) return null;
    const targetStr = String(active).toLowerCase();
    return (
      categories.find(
        (c) =>
          c.id === Number(active) ||
          c.slug.toLowerCase() === targetStr ||
          c.name.toLowerCase().includes(targetStr.replace(/-/g, ' '))
      ) || null
    );
  }, [categories, selectedSubCatId, selectedMainCatId, selectedCategoryId]);

  // Generate pagination pill buttons around current page
  const pageNumbers = useMemo(() => {
    const pages: (number | string)[] = [];
    const delta = 2;
    for (let i = 1; i <= totalPagesCount; i++) {
      if (i === 1 || i === totalPagesCount || (i >= currentPage - delta && i <= currentPage + delta)) {
        pages.push(i);
      } else if (pages[pages.length - 1] !== '...') {
        pages.push('...');
      }
    }
    return pages;
  }, [currentPage, totalPagesCount]);

  return (
    <div className="bg-[#FCF8F5] min-h-screen pb-20 font-sans">
      {/* Top Breadcrumb Navigation Bar */}
      <div className="bg-[#FAF7F4] border-b border-[#E8D9CC] py-3 px-4 sm:px-8">
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-2 text-xs sm:text-sm font-medium text-slate-600">
            <button
              onClick={onNavigateHome}
              className="hover:text-[#C81E3D] flex items-center gap-1 transition-colors cursor-pointer font-semibold"
            >
              <Home className="w-4 h-4 text-[#C81E3D]" />
              <span>Home</span>
            </button>
            <span className="text-slate-300">/</span>
            <span className="font-bold text-[#C81E3D]">Products Shop</span>
            {selectedCategoryObj && (
              <>
                <span className="text-slate-300">/</span>
                <span className="text-slate-800 font-bold">{selectedCategoryObj.name}</span>
              </>
            )}
          </div>

          <button
            onClick={onNavigateHome}
            className="px-3.5 py-1.5 rounded-xl bg-white border border-slate-300 hover:border-[#C81E3D] text-slate-700 hover:text-[#C81E3D] text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer shadow-2xs"
          >
            <ArrowLeft className="w-3.5 h-3.5" />
            <span>Back to Store</span>
          </button>
        </div>
      </div>

      {/* Hero Banner */}
      <div className="bg-gradient-to-b from-[#1E1915] via-[#2A231D] to-[#1E1915] text-white py-10 sm:py-12 px-4 border-b border-[#D4AF37]/30">
        <div className="max-w-7xl mx-auto space-y-4 text-center">
          <div className="inline-flex items-center gap-2 bg-[#C81E3D]/20 border border-[#C81E3D]/40 text-[#FF859B] text-xs font-bold px-3.5 py-1 rounded-full uppercase tracking-widest">
            <Sparkles className="w-3.5 h-3.5" />
            <span>TIME N LIFE EXCLUSIVE CATALOG</span>
          </div>

          <h1 className="text-3xl sm:text-5xl font-extrabold font-playfair tracking-tight text-amber-50">
            Explore All <span className="text-[#C81E3D]">Products</span>
          </h1>

          <p className="text-slate-300 text-xs sm:text-sm max-w-2xl mx-auto font-sans leading-relaxed">
            Browse our complete collection of thousands of premium products across Health &amp; Beauty, Fashion, Watches, Jewelry, Electronics, and Home Essentials — all available with fast nationwide Cash on Delivery.
          </p>

          <div className="pt-2 flex flex-wrap items-center justify-center gap-4 text-xs text-amber-200/90 font-medium">
            <span className="flex items-center gap-1.5 bg-white/5 border border-amber-500/20 px-3 py-1 rounded-full">
              <Truck className="w-3.5 h-3.5 text-amber-400" />
              Express Cash on Delivery
            </span>
            <span className="flex items-center gap-1.5 bg-white/5 border border-amber-500/20 px-3 py-1 rounded-full">
              <ShieldCheck className="w-3.5 h-3.5 text-amber-400" />
              100% Quality Guaranteed
            </span>
            <span className="flex items-center gap-1.5 bg-white/5 border border-amber-500/20 px-3 py-1 rounded-full">
              <Sparkles className="w-3.5 h-3.5 text-amber-400" />
              7,500+ Curated Products
            </span>
          </div>
        </div>
      </div>

      {/* Main Container */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-8 space-y-8">
        
        {/* 1. TOP FILTERING TOOLBAR (Category Dropdown, Subcategory Dropdown, Price Filter, Search & Reset) */}
        <section className="bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] shadow-md p-5 sm:p-6 space-y-4">
          <div className="flex items-center justify-between gap-2 border-b border-[#F2E5D9] pb-3">
            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[#C81E3D]">
              <SlidersHorizontal className="w-4 h-4 text-[#C81E3D]" />
              <span>Filter Catalog</span>
            </div>

            {(selectedMainCatId || selectedSubCatId || priceFilter !== 'all' || searchQuery || sortBy !== 'latest') && (
              <button
                onClick={handleResetFilters}
                className="inline-flex items-center gap-1.5 text-xs font-bold text-[#C81E3D] bg-rose-50 border border-rose-200 px-3 py-1.5 rounded-xl hover:bg-[#C81E3D] hover:text-white transition-colors cursor-pointer"
              >
                <RotateCcw className="w-3.5 h-3.5" />
                <span>Reset Filters</span>
              </button>
            )}
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3.5">
            {/* Search Input */}
            <div className="relative">
              <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">
                Search Product
              </label>
              <div className="relative">
                <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value);
                    setCurrentPage(1);
                  }}
                  placeholder="Search name/keyword..."
                  className="w-full bg-[#FAF5F0] border border-[#F2E5D9] rounded-xl pl-9 pr-8 py-2 text-xs text-slate-800 focus:outline-none focus:border-[#C81E3D] font-medium"
                />
                {searchQuery && (
                  <button
                    onClick={() => {
                      setSearchQuery('');
                      setCurrentPage(1);
                    }}
                    className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                )}
              </div>
            </div>

            {/* Main Category Dropdown */}
            <div>
              <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">
                Main Category
              </label>
              <select
                value={selectedMainCatId}
                onChange={handleMainCategoryChange}
                className="w-full bg-[#FAF5F0] border border-[#F2E5D9] text-slate-800 text-xs font-semibold rounded-xl px-3 py-2 focus:outline-none focus:border-[#C81E3D] cursor-pointer"
              >
                <option value="">All Main Categories</option>
                {topCategories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {cat.name} ({cat.count || 0})
                  </option>
                ))}
              </select>
            </div>

            {/* Sub Category Dropdown */}
            <div>
              <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">
                Sub Category
              </label>
              <select
                value={selectedSubCatId}
                onChange={handleSubCategoryChange}
                disabled={!selectedMainCatId || availableSubcategories.length === 0}
                className={`w-full border text-xs font-semibold rounded-xl px-3 py-2 focus:outline-none cursor-pointer ${
                  !selectedMainCatId || availableSubcategories.length === 0
                    ? 'bg-slate-100 border-slate-200 text-slate-400 cursor-not-allowed'
                    : 'bg-[#FAF5F0] border-[#F2E5D9] text-slate-800 focus:border-[#C81E3D]'
                }`}
              >
                <option value="">
                  {!selectedMainCatId
                    ? 'Select Main Category First'
                    : availableSubcategories.length === 0
                    ? 'No Subcategories'
                    : 'All Subcategories'}
                </option>
                {availableSubcategories.map((sub) => (
                  <option key={sub.id} value={sub.id}>
                    {sub.name} ({sub.count || 0})
                  </option>
                ))}
              </select>
            </div>

            {/* Filter by Price Range */}
            <div>
              <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">
                Filter By Price
              </label>
              <select
                value={priceFilter}
                onChange={(e) => {
                  setPriceFilter(e.target.value);
                  setCurrentPage(1);
                }}
                className="w-full bg-[#FAF5F0] border border-[#F2E5D9] text-slate-800 text-xs font-semibold rounded-xl px-3 py-2 focus:outline-none focus:border-[#C81E3D] cursor-pointer"
              >
                <option value="all">All Prices</option>
                <option value="under-1000">Under Rs 1,000</option>
                <option value="1000-3000">Rs 1,000 - Rs 3,000</option>
                <option value="3000-5000">Rs 3,000 - Rs 5,000</option>
                <option value="5000-10000">Rs 5,000 - Rs 10,000</option>
                <option value="above-10000">Above Rs 10,000</option>
              </select>
            </div>

            {/* Sort Order */}
            <div>
              <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">
                Sort Products By
              </label>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as any)}
                className="w-full bg-[#FAF5F0] border border-[#F2E5D9] text-slate-800 text-xs font-semibold rounded-xl px-3 py-2 focus:outline-none focus:border-[#C81E3D] cursor-pointer"
              >
                <option value="latest">Latest Published</option>
                <option value="price-low">Price: Low to High</option>
                <option value="price-high">Price: High to Low</option>
                <option value="rating">Top Rated First</option>
              </select>
            </div>
          </div>
        </section>

        {/* 2. PRODUCTS GRID SECTION (FIRST) */}
        <section className="space-y-6">
          {/* Active Category / Filter Info Header */}
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 bg-[#FFFDFB] px-5 py-3.5 rounded-2xl border border-[#F2E5D9] shadow-xs">
            <div className="text-xs text-slate-700 font-semibold flex flex-wrap items-center gap-2">
              <span className="bg-[#FAF0E6] text-[#C81E3D] px-3 py-1 rounded-lg border border-[#E8D9CC] font-bold">
                Page {currentPage} of {totalPagesCount}
              </span>
              <span className="text-slate-500">
                Showing {filteredPageProducts.length} of {totalProductsCount.toLocaleString()} products
              </span>
              {selectedCategoryObj && (
                <span className="bg-amber-100/80 text-amber-900 border border-amber-300/60 px-2.5 py-0.5 rounded-full text-[11px] font-bold">
                  Category: {selectedCategoryObj.name}
                </span>
              )}
            </div>
          </div>

          {/* Products Grid or Loading Skeleton */}
          {isLoading ? (
            <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
              {Array.from({ length: 12 }).map((_, idx) => (
                <ProductCardSkeleton key={idx} />
              ))}
            </div>
          ) : filteredPageProducts.length > 0 ? (
            <>
              <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
                {filteredPageProducts.map((prod) => (
                  <ProductCard
                    key={prod.id}
                    product={prod}
                    onSelectProduct={onSelectProduct}
                    onAddToCart={(p, e) => {
                      e.stopPropagation();
                      onAddToCart(p);
                    }}
                  />
                ))}
              </div>

              {/* PAGINATION CONTROL BAR */}
              <div className="bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] shadow-md p-6 flex flex-col md:flex-row items-center justify-between gap-6 mt-8">
                {/* Previous / Page Buttons / Next */}
                <div className="flex flex-wrap items-center justify-center gap-1.5">
                  <button
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage <= 1}
                    className={`inline-flex items-center gap-1 px-3.5 py-2 rounded-xl text-xs font-bold transition-all ${
                      currentPage <= 1
                        ? 'opacity-40 cursor-not-allowed bg-slate-100 text-slate-400'
                        : 'bg-[#FAF5F0] hover:bg-[#C81E3D] hover:text-white text-slate-800 border border-[#F2E5D9] cursor-pointer'
                    }`}
                  >
                    <ChevronLeft className="w-4 h-4" />
                    <span>Previous</span>
                  </button>

                  {pageNumbers.map((p, idx) => {
                    if (p === '...') {
                      return (
                        <span key={`dots-${idx}`} className="px-2 text-slate-400 text-xs font-mono">
                          ...
                        </span>
                      );
                    }
                    const isCurrent = p === currentPage;
                    return (
                      <button
                        key={`page-${p}`}
                        onClick={() => handlePageChange(Number(p))}
                        className={`w-9 h-9 rounded-xl text-xs font-bold transition-all cursor-pointer ${
                          isCurrent
                            ? 'bg-[#C81E3D] text-white shadow-md'
                            : 'bg-[#FAF5F0] hover:bg-rose-100/70 text-slate-800 border border-[#F2E5D9]'
                        }`}
                      >
                        {p}
                      </button>
                    );
                  })}

                  <button
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage >= totalPagesCount}
                    className={`inline-flex items-center gap-1 px-3.5 py-2 rounded-xl text-xs font-bold transition-all ${
                      currentPage >= totalPagesCount
                        ? 'opacity-40 cursor-not-allowed bg-slate-100 text-slate-400'
                        : 'bg-[#FAF5F0] hover:bg-[#C81E3D] hover:text-white text-slate-800 border border-[#F2E5D9] cursor-pointer'
                    }`}
                  >
                    <span>Next</span>
                    <ChevronRight className="w-4 h-4" />
                  </button>
                </div>

                {/* Direct Jump To Page Form */}
                <form onSubmit={handleJumpToPage} className="flex items-center gap-2 text-xs font-medium text-slate-700">
                  <span>Go to Page:</span>
                  <input
                    type="number"
                    min="1"
                    max={totalPagesCount}
                    value={jumpPageInput}
                    onChange={(e) => setJumpPageInput(e.target.value)}
                    placeholder={`${currentPage}`}
                    className="w-16 bg-[#FAF5F0] border border-[#F2E5D9] rounded-xl px-2 py-1.5 text-center font-bold focus:outline-none focus:border-[#C81E3D]"
                  />
                  <button
                    type="submit"
                    className="px-3 py-1.5 bg-[#1E2432] text-white font-bold rounded-xl hover:bg-[#C81E3D] transition-colors cursor-pointer"
                  >
                    Jump
                  </button>
                </form>
              </div>
            </>
          ) : (
            <div className="bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] p-12 text-center space-y-4">
              <ShoppingBag className="w-12 h-12 text-slate-300 mx-auto" />
              <h3 className="text-xl font-bold font-playfair text-slate-800">No Products Found</h3>
              <p className="text-xs text-slate-500 max-w-sm mx-auto">
                No products matched your selected filters or search query.
              </p>
              <button
                onClick={handleResetFilters}
                className="px-4 py-2 bg-[#C81E3D] text-white text-xs font-bold rounded-xl uppercase tracking-wider hover:bg-[#A6142E] transition-colors cursor-pointer"
              >
                Clear Filters &amp; Show All Products
              </button>
            </div>
          )}
        </section>

        {/* 3. CATEGORIES & SUBCATEGORIES SECTION (AT THE BOTTOM AFTER PRODUCTS) */}
        <section className="bg-[#FFFDFB] rounded-3xl border border-[#F2E5D9] shadow-md p-6 sm:p-8 space-y-6 mt-12">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 border-b border-[#F2E5D9] pb-4">
            <div className="space-y-1">
              <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[#C81E3D]">
                <FolderTree className="w-4 h-4 text-[#C81E3D]" />
                <span>Store Directory</span>
              </div>
              <h2 className="text-2xl font-bold font-playfair text-[#1E2432]">
                Categories &amp; Subcategories
              </h2>
            </div>

            {selectedMainCatId && (
              <button
                onClick={handleResetFilters}
                className="inline-flex items-center gap-1.5 text-xs font-bold text-[#C81E3D] bg-rose-50 border border-rose-200 px-3 py-1.5 rounded-lg hover:bg-[#C81E3D] hover:text-white transition-colors cursor-pointer"
              >
                <X className="w-3.5 h-3.5" />
                <span>Show All Categories</span>
              </button>
            )}
          </div>

          {/* Category Cards Grid with Subcategories */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {topCategories.map((cat) => {
              const subcats = getSubcategories(cat.id);
              const isSelected =
                selectedMainCatId === String(cat.id) ||
                (selectedMainCatId && selectedMainCatId.toLowerCase() === cat.slug.toLowerCase());
              const isExpanded = !!expandedCategories[cat.id];

              return (
                <div
                  key={cat.id}
                  className={`rounded-2xl border transition-all duration-300 overflow-hidden flex flex-col justify-between ${
                    isSelected
                      ? 'bg-rose-50/80 border-[#C81E3D] shadow-md ring-2 ring-[#C81E3D]/20'
                      : 'bg-[#FAF5F0] border-[#F2E5D9] hover:border-[#D4AF37] hover:shadow-sm'
                  }`}
                >
                  <div
                    onClick={() => {
                      if (isSelected) {
                        handleResetFilters();
                      } else {
                        setSelectedMainCatId(String(cat.id));
                        setSelectedSubCatId('');
                        setSelectedCategoryId(cat.id);
                        setCurrentPage(1);
                        window.history.pushState({}, '', `/product-category/${cat.slug}`);
                        window.scrollTo({ top: 350, behavior: 'smooth' });
                      }
                    }}
                    className="p-4 cursor-pointer space-y-3"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Tag className="w-4 h-4 text-[#B8860B]" />
                        <span className="text-xs font-bold text-slate-800 uppercase tracking-wider">
                          {cat.name}
                        </span>
                      </div>
                      <span className="text-[10px] font-extrabold bg-amber-100 text-amber-900 px-2 py-0.5 rounded-full">
                        {cat.count ? `${cat.count.toLocaleString()}+` : '2,000+'} Items
                      </span>
                    </div>

                    <p className="text-xs text-slate-600 line-clamp-2">
                      {cat.description || 'Explore our exclusive collection in this category.'}
                    </p>
                  </div>

                  {/* Subcategories Accordion */}
                  {subcats.length > 0 && (
                    <div className="border-t border-[#E8D9CC] bg-white/60">
                      <button
                        onClick={(e) => toggleCategoryExpand(cat.id, e)}
                        className="w-full px-4 py-2 flex items-center justify-between text-[11px] font-bold text-slate-700 hover:text-[#C81E3D] uppercase tracking-wider cursor-pointer"
                      >
                        <span>Subcategories ({subcats.length})</span>
                        <ChevronDown
                          className={`w-3.5 h-3.5 transition-transform duration-200 ${
                            isExpanded ? 'rotate-180 text-[#C81E3D]' : 'text-slate-400'
                          }`}
                        />
                      </button>

                      {isExpanded && (
                        <div className="px-3 pb-3 space-y-1">
                          {subcats.map((sub) => {
                            const isSubSelected = selectedSubCatId === String(sub.id);
                            return (
                              <button
                                key={sub.id}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  if (isSubSelected) {
                                    setSelectedSubCatId('');
                                    setSelectedCategoryId(cat.id);
                                  } else {
                                    setSelectedMainCatId(String(cat.id));
                                    setSelectedSubCatId(String(sub.id));
                                    setSelectedCategoryId(sub.id);
                                    window.history.pushState({}, '', `/product-category/${sub.slug}`);
                                  }
                                  setCurrentPage(1);
                                  window.scrollTo({ top: 350, behavior: 'smooth' });
                                }}
                                className={`w-full text-left px-3 py-1.5 rounded-lg text-xs flex items-center justify-between transition-colors cursor-pointer ${
                                  isSubSelected
                                    ? 'bg-[#C81E3D] text-white font-bold'
                                    : 'hover:bg-rose-100/60 text-slate-700'
                                }`}
                              >
                                <span className="truncate">{sub.name}</span>
                                <span className="text-[10px] opacity-80 ml-2 font-semibold">
                                  ({sub.count || 500}+)
                                </span>
                              </button>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </section>

      </div>
    </div>
  );
};
