'use client';

import React, { useEffect, useState, useRef, useMemo, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import api from '@/lib/api';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { ProductCard } from '@/components/ProductCard';
import { Search, SlidersHorizontal, ChevronLeft, ChevronRight, X } from 'lucide-react';
import Link from 'next/link';
import { useSiteSettings } from '@/context/SiteSettingsContext';

interface Product {
  id: number;
  name: string;
  slug: string;
  price: number;
  compare_at_price?: number;
  sale_price?: number;
  image_url: string;
  is_featured?: boolean;
  sku?: string;
  short_description?: string;
  variants?: Array<{ options?: string }>;
  category?: {
    name: string;
    slug: string;
  };
}

interface Category {
  id: number;
  name: string;
  slug: string;
}

// ── Filter State ────────────────────────────────────────────────────────────
interface FilterState {
  categorySlug: string;
  search: string;
  minPrice: string;
  maxPrice: string;
  attributeValues: string[];
  featured: boolean;
  sortBy: string;
}

const defaultFilters: FilterState = {
  categorySlug: '',
  search: '',
  minPrice: '',
  maxPrice: '',
  attributeValues: [],
  featured: false,
  sortBy: 'latest',
};

// ── Sidebar Filters ─────────────────────────────────────────────────────────
interface SidebarFiltersProps {
  categories: Category[];
  filterConfig: any;
  loadingFilters?: boolean;
  filters: FilterState;
  onFilterChange: (updates: Partial<FilterState>) => void;
}

const SidebarFilters: React.FC<SidebarFiltersProps> = ({
  categories,
  filterConfig,
  loadingFilters = false,
  filters,
  onFilterChange,
}) => {
  const [minPriceInput, setMinPriceInput] = useState(filters.minPrice);
  const [maxPriceInput, setMaxPriceInput] = useState(filters.maxPrice);

  // Sync local price inputs when filters reset externally
  useEffect(() => { setMinPriceInput(filters.minPrice); }, [filters.minPrice]);
  useEffect(() => { setMaxPriceInput(filters.maxPrice); }, [filters.maxPrice]);

  const hasActiveFilters = filters.categorySlug || filters.featured || filters.search || filters.minPrice || filters.maxPrice || filters.attributeValues.length > 0;

  const handleApplyPrice = (e: React.FormEvent) => {
    e.preventDefault();
    onFilterChange({ minPrice: minPriceInput, maxPrice: maxPriceInput });
  };

  const handleToggleAttrVal = (val: string) => {
    const next = filters.attributeValues.includes(val)
      ? filters.attributeValues.filter(v => v !== val)
      : [...filters.attributeValues, val];
    onFilterChange({ attributeValues: next });
  };

  if (loadingFilters) {
    return (
      <div className="space-y-4">
        <div className="bg-white border border-slate-200 rounded p-5 shadow-sm space-y-4 animate-pulse">
          <div className="h-4 bg-slate-100 rounded w-1/3"></div>
          <div className="space-y-2 pt-2">
            {[...Array(5)].map((_, i) => <div key={i} className="h-3.5 bg-slate-100 rounded w-3/4"></div>)}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Clear All Filters */}
      {hasActiveFilters && (
        <button
          onClick={() => onFilterChange({ ...defaultFilters })}
          className="w-full bg-[#d91e18] hover:bg-[#c01712] text-white text-xs font-bold py-2.5 px-4 rounded flex items-center justify-center gap-2 transition-colors duration-200 cursor-pointer shadow-sm"
        >
          <X className="h-4 w-4" />
          <span>Clear All Filters</span>
        </button>
      )}

      {/* Filter by Category */}
      <div className="bg-white border border-slate-200 rounded p-5 shadow-sm space-y-4">
        <div className="flex justify-between items-center border-b border-slate-100 pb-2 relative">
          <div className="relative">
            <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">Filter By Category</h3>
            <div className="absolute -bottom-[9px] left-0 w-full h-[2px] bg-secondary"></div>
          </div>
          <span className="text-slate-400 font-bold text-xs select-none">—</span>
        </div>
        <div className="flex flex-col gap-2.5 pt-2">
          <label className="flex items-center gap-2.5 text-xs font-semibold text-slate-700 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={!filters.categorySlug}
              onChange={() => onFilterChange({ categorySlug: '' })}
              className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
            />
            <span>All Products</span>
          </label>
          {categories.map((cat) => (
            <label key={cat.id} className="flex items-center gap-2.5 text-xs font-semibold text-slate-700 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={filters.categorySlug === cat.slug}
                onChange={() => onFilterChange({ categorySlug: filters.categorySlug === cat.slug ? '' : cat.slug })}
                className="rounded border-slate-300 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
              />
              <span>{cat.name}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Filter by Price Range */}
      {filterConfig?.enable_price_filter === true && (
        <div className="bg-white border border-slate-200 rounded p-5 shadow-sm space-y-4">
          <div className="flex justify-between items-center border-b border-slate-100 pb-2 relative">
            <div className="relative">
              <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">Price Range</h3>
              <div className="absolute -bottom-[9px] left-0 w-full h-[2px] bg-secondary"></div>
            </div>
            <span className="text-slate-400 font-bold text-xs select-none">—</span>
          </div>
          <form onSubmit={handleApplyPrice} className="space-y-3 pt-2">
            <div className="flex items-center gap-2">
              <input
                type="number"
                placeholder="Min"
                value={minPriceInput}
                onChange={(e) => setMinPriceInput(e.target.value)}
                className="w-full text-xs px-2.5 py-1.5 border border-slate-200 rounded focus:border-secondary focus:ring-0 focus:outline-none"
              />
              <span className="text-slate-400 text-xs">to</span>
              <input
                type="number"
                placeholder="Max"
                value={maxPriceInput}
                onChange={(e) => setMaxPriceInput(e.target.value)}
                className="w-full text-xs px-2.5 py-1.5 border border-slate-200 rounded focus:border-secondary focus:ring-0 focus:outline-none"
              />
            </div>
            <button
              type="submit"
              className="w-full bg-secondary hover:bg-secondary-dark text-white text-[11px] font-bold py-1.5 px-3 rounded transition-colors duration-200 cursor-pointer"
            >
              Apply
            </button>
          </form>
        </div>
      )}

      {/* Filter by Custom Product Attributes */}
      {filterConfig?.enable_attr_filter && (
        <>
          {Array.isArray(filterConfig.attributes) && filterConfig.attributes.length > 0 ? (
            filterConfig.attributes.map((attr: any) => (
              <div key={attr.name} className="bg-white border border-slate-200 rounded p-5 shadow-sm space-y-4">
                <div className="flex justify-between items-center border-b border-slate-100 pb-2 relative">
                  <div className="relative">
                    <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">Filter By {attr.name}</h3>
                    <div className="absolute -bottom-[9px] left-0 w-full h-[2px] bg-secondary"></div>
                  </div>
                  <span className="text-slate-400 font-bold text-xs select-none">—</span>
                </div>
                <div className="flex flex-col gap-2.5 pt-2">
                  {attr.values.map((val: string) => (
                    <label key={val} className="flex items-center gap-2.5 text-xs font-semibold text-slate-700 cursor-pointer select-none">
                      <input
                        type="checkbox"
                        checked={filters.attributeValues.includes(val)}
                        onChange={() => handleToggleAttrVal(val)}
                        className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
                      />
                      <span>{val}</span>
                    </label>
                  ))}
                </div>
              </div>
            ))
          ) : filterConfig.attribute_name && filterConfig.attribute_values?.length > 0 ? (
            <div className="bg-white border border-slate-200 rounded p-5 shadow-sm space-y-4">
              <div className="flex justify-between items-center border-b border-slate-100 pb-2 relative">
                <div className="relative">
                  <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">Filter By {filterConfig.attribute_name}</h3>
                  <div className="absolute -bottom-[9px] left-0 w-full h-[2px] bg-secondary"></div>
                </div>
                <span className="text-slate-400 font-bold text-xs select-none">—</span>
              </div>
              <div className="flex flex-col gap-2.5 pt-2">
                {filterConfig.attribute_values.map((val: string) => (
                  <label key={val} className="flex items-center gap-2.5 text-xs font-semibold text-slate-700 cursor-pointer select-none">
                    <input
                      type="checkbox"
                      checked={filters.attributeValues.includes(val)}
                      onChange={() => handleToggleAttrVal(val)}
                      className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
                    />
                    <span>{val}</span>
                  </label>
                ))}
              </div>
            </div>
          ) : null}
        </>
      )}

      {/* Promotions / Featured */}
      <div className="bg-white border border-slate-200 rounded p-5 shadow-sm space-y-4">
        <div className="flex justify-between items-center border-b border-slate-100 pb-2 relative">
          <div className="relative">
            <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">Promotions</h3>
            <div className="absolute -bottom-[9px] left-0 w-full h-[2px] bg-secondary"></div>
          </div>
          <span className="text-slate-400 font-bold text-xs select-none">—</span>
        </div>
        <div className="flex flex-col gap-2.5 pt-2">
          <label className="flex items-center gap-2.5 text-xs font-semibold text-slate-700 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={filters.featured}
              onChange={(e) => onFilterChange({ featured: e.target.checked })}
              className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
            />
            <span>Weekly Featured Deals</span>
          </label>
        </div>
      </div>
    </div>
  );
};

// ── Product Grid Area ────────────────────────────────────────────────────────
interface ProductGridAreaProps {
  onOpenMobileFilters?: () => void;
  filterConfig: any;
  allProducts: Product[];
  loadingAll: boolean;
  filters: FilterState;
  onFilterChange: (updates: Partial<FilterState>) => void;
}

const PRODUCTS_PER_PAGE = 20;

const ProductGridArea: React.FC<ProductGridAreaProps> = ({
  onOpenMobileFilters,
  filterConfig,
  allProducts,
  loadingAll,
  filters,
  onFilterChange,
}) => {
  const defaultLimit = filterConfig?.view_product ? parseInt(filterConfig.view_product, 10) : PRODUCTS_PER_PAGE;
  const [limit, setLimit] = useState(defaultLimit);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchInput, setSearchInput] = useState(filters.search);

  // Reset page when filters change
  useEffect(() => { setCurrentPage(1); }, [filters]);
  useEffect(() => { setSearchInput(filters.search); }, [filters.search]);

  // ── Client-side filter + sort ──────────────────────────────────────────────
  const filteredProducts = useMemo(() => {
    let list = [...allProducts];

    // Search
    if (filters.search) {
      const q = filters.search.toLowerCase();
      list = list.filter(p =>
        p.name?.toLowerCase().includes(q) ||
        p.sku?.toLowerCase().includes(q) ||
        p.short_description?.toLowerCase().includes(q)
      );
    }

    // Category
    if (filters.categorySlug) {
      list = list.filter(p => p.category?.slug === filters.categorySlug);
    }

    // Featured
    if (filters.featured) {
      list = list.filter(p => p.is_featured);
    }

    // Price range
    if (filters.minPrice) {
      list = list.filter(p => p.price >= parseFloat(filters.minPrice));
    }
    if (filters.maxPrice) {
      list = list.filter(p => p.price <= parseFloat(filters.maxPrice));
    }

    // Attribute values
    if (filters.attributeValues.length > 0) {
      list = list.filter(p =>
        p.variants?.some(v =>
          filters.attributeValues.some(val =>
            v.options && v.options.includes(`"${val}"`)
          )
        )
      );
    }

    // Sort
    switch (filters.sortBy) {
      case 'price_asc':
        list.sort((a, b) => a.price - b.price);
        break;
      case 'price_desc':
        list.sort((a, b) => b.price - a.price);
        break;
      case 'name_asc':
        list.sort((a, b) => a.name.localeCompare(b.name));
        break;
      case 'featured':
        list.sort((a, b) => (b.is_featured ? 1 : 0) - (a.is_featured ? 1 : 0));
        break;
      default: // 'latest' — keep original order (newest first from API)
        break;
    }

    return list;
  }, [allProducts, filters]);

  // Paginate client-side
  const totalProducts = filteredProducts.length;
  const lastPage = Math.max(1, Math.ceil(totalProducts / limit));
  const safePage = Math.min(currentPage, lastPage);
  const paginatedProducts = filteredProducts.slice((safePage - 1) * limit, safePage * limit);

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onFilterChange({ search: searchInput });
  };

  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= lastPage) {
      setCurrentPage(newPage);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  return (
    <div className="space-y-6">
      {/* Toolbar */}
      <div className="grid grid-cols-3 gap-2 bg-white border border-slate-200 rounded p-2 lg:px-4 lg:py-3 shadow-sm lg:flex lg:justify-between lg:items-center">
        {/* Mobile Filters Toggle */}
        <button
          type="button"
          onClick={onOpenMobileFilters}
          className="flex lg:hidden items-center justify-center gap-1.5 border border-secondary text-secondary bg-white py-2 px-1 rounded-md text-[10px] font-normal hover:bg-secondary/10 transition-colors cursor-pointer select-none"
        >
          <SlidersHorizontal className="h-3.5 w-3.5 text-secondary" />
          <span>Filters</span>
        </button>

        {/* Sort By */}
        <div className="flex items-center gap-2 w-full lg:w-auto">
          <span className="text-xs font-semibold text-slate-500 hidden lg:inline">Sort By :</span>
          <div className="relative w-full lg:w-auto">
            <select
              value={filters.sortBy}
              onChange={(e) => onFilterChange({ sortBy: e.target.value })}
              className="w-full appearance-none text-[10px] lg:text-xs font-normal lg:font-semibold border border-slate-200 py-2 pl-2 pr-6 lg:py-1.5 lg:pl-3 lg:pr-8 rounded focus:outline-none bg-white text-slate-700 cursor-pointer hover:border-slate-350 transition-colors"
            >
              <option value="latest">Latest</option>
              <option value="price_asc">Price: Low to High</option>
              <option value="price_desc">Price: High to Low</option>
              <option value="name_asc">Alphabetical</option>
              <option value="featured">Featured First</option>
            </select>
            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2 text-slate-400">
              <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
              </svg>
            </div>
          </div>
        </div>

        {/* Per-page selector */}
        <div className="relative w-full lg:w-auto">
          <select
            value={limit}
            onChange={(e) => {
              setLimit(parseInt(e.target.value, 10));
              setCurrentPage(1);
            }}
            className="w-full appearance-none text-[10px] lg:text-xs font-normal lg:font-semibold border border-secondary py-2 pl-2 pr-6 lg:py-1.5 lg:pl-3 lg:pr-8 rounded focus:outline-none bg-white text-secondary cursor-pointer hover:border-secondary/70 transition-colors"
          >
            <option value="12">Show 12</option>
            <option value="16">Show 16</option>
            <option value="20">Show 20</option>
            <option value="24">Show 24</option>
            <option value="36">Show 36</option>
          </select>
          <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2 text-secondary">
            <svg className="h-3 w-3 text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M19 9l-7 7-7-7" />
            </svg>
          </div>
        </div>
      </div>

      {/* Products Grid / Skeletons */}
      {loadingAll ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4 lg:gap-6">
          {[...Array(8)].map((_, i) => (
            <div key={i} className="flex flex-col gap-3 overflow-hidden rounded border border-slate-200 bg-white p-4 animate-pulse">
              <div className="aspect-square bg-slate-100 rounded w-full"></div>
              <div className="h-3.5 bg-slate-150 rounded w-3/4"></div>
              <div className="h-3.5 bg-slate-150 rounded w-1/2"></div>
              <div className="h-8 bg-slate-150 rounded w-full mt-4"></div>
            </div>
          ))}
        </div>
      ) : paginatedProducts.length === 0 ? (
        <div className="text-center py-20 bg-white border border-dashed border-slate-200 rounded">
          <p className="text-sm font-semibold text-slate-500">No products found matching active filters.</p>
        </div>
      ) : (
        <>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4 lg:gap-6">
            {paginatedProducts.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>

          {/* Pagination */}
          {lastPage > 1 && (
            <div className="flex items-center justify-between border-t border-slate-100 pt-6">
              <span className="text-xxs font-semibold text-slate-500">
                Showing page {safePage} of {lastPage} ({totalProducts} items)
              </span>
              <div className="flex items-center gap-1.5">
                <button
                  onClick={() => handlePageChange(safePage - 1)}
                  disabled={safePage === 1}
                  className="p-2 border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:hover:bg-transparent cursor-pointer"
                >
                  <ChevronLeft className="h-4 w-4" />
                </button>
                {[...Array(lastPage)].map((_, idx) => {
                  const pageNum = idx + 1;
                  return (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={`h-8 w-8 text-xs font-bold rounded-lg transition-all cursor-pointer ${
                        safePage === pageNum
                          ? 'bg-secondary text-white shadow-sm'
                          : 'border border-slate-200 text-slate-600 hover:bg-slate-50'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}
                <button
                  onClick={() => handlePageChange(safePage + 1)}
                  disabled={safePage === lastPage}
                  className="p-2 border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:hover:bg-transparent cursor-pointer"
                >
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
};

// ── ShopContent ──────────────────────────────────────────────────────────────
const ShopContent: React.FC = () => {
  const searchParams = useSearchParams();
  const { settings } = useSiteSettings();
  const categories = settings?.categories || [];
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);

  // Initialise filters from URL params (for deep-link / header search support)
  const [filters, setFilters] = useState<FilterState>({
    categorySlug: searchParams.get('categorySlug') || '',
    search: searchParams.get('search') || '',
    minPrice: searchParams.get('minPrice') || '',
    maxPrice: searchParams.get('maxPrice') || '',
    attributeValues: searchParams.get('attributeValues') ? (searchParams.get('attributeValues') || '').split(',') : [],
    featured: searchParams.get('featured') === 'true',
    sortBy: searchParams.get('sortBy') || 'latest',
  });

  // Keep filters in sync when URL params change (e.g. header search nav)
  useEffect(() => {
    setFilters(prev => ({
      ...prev,
      search: searchParams.get('search') || prev.search,
      categorySlug: searchParams.get('categorySlug') || prev.categorySlug,
    }));
  }, [searchParams]);

  const handleFilterChange = (updates: Partial<FilterState>) => {
    setFilters(prev => ({ ...prev, ...updates }));
  };

  // ── Filter config ──────────────────────────────────────────────────────────
  const [loadingFilters, setLoadingFilters] = useState(true);
  const [filterConfig, setFilterConfig] = useState<any>({
    enable_price_filter: null,
    price_range_max: 10000,
    enable_attr_filter: false,
    attribute_name: '',
    attribute_values: [],
  });

  useEffect(() => {
    const loadFilters = async () => {
      if (typeof window !== 'undefined') {
        const cached = sessionStorage.getItem('shop_filters_config');
        if (cached) {
          try { setFilterConfig(JSON.parse(cached)); setLoadingFilters(false); } catch {}
        }
      }
      try {
        const res = await api.get('/api/shop-filters');
        setFilterConfig(res.data);
        if (typeof window !== 'undefined') {
          sessionStorage.setItem('shop_filters_config', JSON.stringify(res.data));
        }
      } catch {}
      finally { setLoadingFilters(false); }
    };
    loadFilters();
  }, []);

  // ── Load ALL products once ─────────────────────────────────────────────────
  const [allProducts, setAllProducts] = useState<Product[]>([]);
  const [loadingAll, setLoadingAll] = useState(true);

  useEffect(() => {
    const fetchAll = async () => {
      setLoadingAll(true);
      try {
        const res = await api.get('/api/products', { params: { per_page: 500 } });
        setAllProducts(res.data.data || []);
      } catch {
        console.error('Failed to load all products');
      } finally {
        setLoadingAll(false);
      }
    };
    fetchAll();
  }, []);

  const sidebarProps = { categories, filterConfig, loadingFilters, filters, onFilterChange: handleFilterChange };

  return (
    <div className="w-full">
      {/* Breadcrumb */}
      <div className="w-full bg-[#f5f6f8] border-b border-slate-200/50 py-2 mb-3">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 flex justify-between items-center">
          <h1 className="text-base sm:text-xl font-bold text-slate-800 capitalize">Shop</h1>
          <nav className="text-[13px] lg:text-[14px] text-slate-500 font-open-sans font-medium flex items-center gap-1.5">
            <Link href="/" className="hover:text-secondary text-slate-400 transition-colors">Home</Link>
            <span className="text-slate-300 select-none">&gt;</span>
            <span className="text-slate-600 capitalize">Shop</span>
          </nav>
        </div>
      </div>

      <div className="mx-auto max-w-7xl px-4 pb-12 sm:px-6 lg:px-8">
        <div className="flex flex-col lg:flex-row gap-6">

          {/* Left Sidebar (Desktop) */}
          <aside className="hidden lg:block lg:w-64 flex-shrink-0">
            <Suspense fallback={<div className="bg-white border border-slate-200 rounded p-5 shadow-sm animate-pulse h-64" />}>
              <SidebarFilters {...sidebarProps} />
            </Suspense>
          </aside>

          {/* Mobile Filter Drawer */}
          <div
            className={`fixed inset-0 z-50 flex lg:hidden bg-black/50 backdrop-blur-xs transition-opacity duration-300 ${
              mobileFiltersOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
            }`}
            onClick={() => setMobileFiltersOpen(false)}
          >
            <div
              className={`w-80 max-w-[85vw] bg-white h-full flex flex-col p-5 shadow-2xl overflow-y-auto transition-transform duration-300 ease-out ${
                mobileFiltersOpen ? 'translate-x-0' : '-translate-x-full'
              }`}
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex justify-between items-center border-b border-slate-100 pb-3 mb-4">
                <h2 className="text-sm font-bold text-slate-800 uppercase tracking-wider">Filters</h2>
                <button onClick={() => setMobileFiltersOpen(false)} className="p-1 rounded hover:bg-slate-100 text-slate-500 cursor-pointer">
                  <X className="h-5 w-5" />
                </button>
              </div>
              <SidebarFilters {...sidebarProps} />
            </div>
          </div>

          {/* Right: Product Grid */}
          <div className="flex-1">
            <Suspense fallback={
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4 lg:gap-6 animate-pulse">
                {[...Array(8)].map((_, i) => (
                  <div key={i} className="flex flex-col gap-3 overflow-hidden rounded border border-slate-200 bg-white p-4">
                    <div className="aspect-square bg-slate-100 rounded w-full"></div>
                    <div className="h-3.5 bg-slate-150 rounded w-3/4"></div>
                    <div className="h-3.5 bg-slate-150 rounded w-1/2"></div>
                    <div className="h-8 bg-slate-150 rounded w-full mt-4"></div>
                  </div>
                ))}
              </div>
            }>
              <ProductGridArea
                onOpenMobileFilters={() => setMobileFiltersOpen(true)}
                filterConfig={filterConfig}
                allProducts={allProducts}
                loadingAll={loadingAll}
                filters={filters}
                onFilterChange={handleFilterChange}
              />
            </Suspense>
          </div>

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

export default function Shop() {
  return (
    <>
      <Header />
      <main className="flex-1 bg-slate-50/50 min-h-screen">
        <Suspense fallback={
          <div className="flex items-center justify-center py-40 gap-3 text-xs font-bold text-slate-400">
            <span>Loading Shop...</span>
          </div>
        }>
          <ShopContent />
        </Suspense>
      </main>
      <Footer />
    </>
  );
}
