'use client';

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

interface Product {
  id: number;
  name: string;
  slug: string;
  price: number;
  compare_at_price?: number;
  sale_price?: number;
  image_url: string;
  category?: {
    name: string;
    slug: string;
  };
  is_best_selling?: boolean;
}

interface Category {
  id: number;
  name: string;
  slug: string;
  parent_id?: number | null;
}

interface SidebarFiltersProps {
  categories: Category[];
  slug: string;
}

const SidebarFilters: React.FC<SidebarFiltersProps> = ({ categories, slug }) => {
  const router = useRouter();
  const searchParams = useSearchParams();

  // URL parameters
  const filterCatsParam = searchParams.get('filterCats') || '';
  const brandsParam = searchParams.get('brands') || '';
  const flagsParam = searchParams.get('flags') || '';
  const maxPriceParam = searchParams.get('maxPrice') || '';

  // Local state for smooth slider dragging
  const [priceRange, setPriceRange] = useState(parseInt(maxPriceParam || '5000', 10));

  // Sync price slider state with URL updates
  useEffect(() => {
    setPriceRange(parseInt(maxPriceParam || '5000', 10));
  }, [maxPriceParam]);

  // Derived state from URL params
  const selectedCategories = filterCatsParam ? filterCatsParam.split(',') : [];
  const selectedBrands = brandsParam ? brandsParam.split(',') : [];
  const selectedFlags = flagsParam ? flagsParam.split(',') : [];

  const updateRouteWithFilters = (updates: Record<string, string | null>) => {
    const current = new URLSearchParams(Array.from(searchParams.entries()));
    Object.entries(updates).forEach(([key, value]) => {
      if (value === null || value === '') {
        current.delete(key);
      } else {
        current.set(key, value);
      }
    });
    current.set('page', '1');
    router.push(`/collections/${slug}?${current.toString()}`);
  };

  const handleCategoryToggle = (catSlug: string) => {
    const isMainSlug = catSlug === slug;
    let nextFilterCats: string[];

    if (isMainSlug) {
      if (selectedCategories.length > 0) {
        const nextSlug = selectedCategories[0];
        nextFilterCats = selectedCategories.slice(1);
        updateRouteWithNewSlug(nextSlug, nextFilterCats);
      } else {
        return;
      }
    } else {
      if (selectedCategories.includes(catSlug)) {
        nextFilterCats = selectedCategories.filter(s => s !== catSlug);
      } else {
        nextFilterCats = [...selectedCategories, catSlug];
      }
      updateRouteWithNewSlug(slug, nextFilterCats);
    }
  };

  const updateRouteWithNewSlug = (newSlug: string, nextFilterCats: string[]) => {
    const current = new URLSearchParams(Array.from(searchParams.entries()));
    if (nextFilterCats.length > 0) {
      current.set('filterCats', nextFilterCats.join(','));
    } else {
      current.delete('filterCats');
    }
    current.set('page', '1');
    router.push(`/collections/${newSlug}?${current.toString()}`);
  };

  const toggleBrandSelection = (brandName: string) => {
    const next = selectedBrands.includes(brandName)
      ? selectedBrands.filter(b => b !== brandName)
      : [...selectedBrands, brandName];
    updateRouteWithFilters({ brands: next.length > 0 ? next.join(',') : null });
  };

  const toggleFlagSelection = (flag: string) => {
    const next = selectedFlags.includes(flag)
      ? selectedFlags.filter(f => f !== flag)
      : [...selectedFlags, flag];
    updateRouteWithFilters({ flags: next.length > 0 ? next.join(',') : null });
  };

  const handleClearAllFilters = () => {
    const current = new URLSearchParams(Array.from(searchParams.entries()));
    current.delete('filterCats');
    current.delete('brands');
    current.delete('flags');
    current.delete('maxPrice');
    current.delete('sortBy');
    current.set('page', '1');
    router.push(`/collections/${slug}?${current.toString()}`);
  };

  const hasActiveFilters = selectedCategories.length > 0 || selectedBrands.length > 0 || selectedFlags.length > 0 || priceRange < 5000 || searchParams.has('sortBy');

  // Category relationships check (Mustard Oil 'oil' and Ghee 'ghee' behave as subcategories of 'oil-ghee')
  const currentCat = categories.find(c => c.slug === slug);
  const isSubcategory = (currentCat && currentCat.parent_id !== null && currentCat.parent_id !== undefined) || ['oil', 'ghee'].includes(slug);
  const showCategoryFilter = !isSubcategory;
  
  const filterCatOptions = slug === 'oil-ghee'
    ? categories.filter(c => ['oil', 'ghee'].includes(c.slug))
    : currentCat
      ? categories.filter(c => c.parent_id === currentCat.id)
      : [];

  return (
    <div className="space-y-4">
      {/* Clear All Filters Button */}
      {hasActiveFilters && (
        <button
          onClick={handleClearAllFilters}
          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 (Only displayed on parent/main categories showing their subcategories) */}
      {showCategoryFilter && filterCatOptions.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 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">
            {filterCatOptions.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={selectedCategories.includes(cat.slug) || slug === cat.slug}
                  onChange={() => handleCategoryToggle(cat.slug)}
                  className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
                />
                <span>{cat.name}</span>
              </label>
            ))}
          </div>
        </div>
      )}

      {/* Price Range */}
      <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-[10px] font-black text-secondary">৳{priceRange}</span>
        </div>
        <div className="space-y-3 pt-2">
          <input
            type="range"
            min="0"
            max="5000"
            step="50"
            value={priceRange}
            onChange={(e) => {
              const val = parseInt(e.target.value, 10);
              setPriceRange(val);
              updateRouteWithFilters({ maxPrice: val.toString() });
            }}
            className="w-full h-1.5 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-secondary"
          />
          <div className="flex justify-between items-center text-xxs font-bold text-slate-400">
            <span>৳0</span>
            <span>৳5,000</span>
          </div>
        </div>
      </div>

      {/* Brands */}
      <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">
              Brands
            </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">
          {['Ghorer Bazar', 'Pure', 'Organic', 'Handmade'].map(brand => (
            <label key={brand} className="flex items-center gap-2.5 text-xs font-semibold text-slate-700 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={selectedBrands.includes(brand)}
                onChange={() => toggleBrandSelection(brand)}
                className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
              />
              <span>{brand}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Product Flag */}
      <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">
              Product Flag
            </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={selectedFlags.includes('best-selling')}
              onChange={() => toggleFlagSelection('best-selling')}
              className="rounded border-slate-350 text-secondary focus:ring-secondary h-4.5 w-4.5 cursor-pointer"
            />
            <span>Best Selling</span>
          </label>
        </div>
      </div>
    </div>
  );
};

interface ProductGridAreaProps {
  categories: Category[];
  slug: string;
  onOpenMobileFilters?: () => void;
}

const ProductGridArea: React.FC<ProductGridAreaProps> = ({ slug, onOpenMobileFilters }) => {
  const router = useRouter();
  const searchParams = useSearchParams();

  // API State
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  // Scroll position restoration (per-collection-slug key)
  const scrollRestoredRef = useRef(false);
  const pendingRestoreRef = useRef(false);
  const isRestoringRef = useRef(false); // pause scroll-save during smooth scroll
  const SCROLL_KEY = `scroll_collection_${slug}`;

  useEffect(() => {
    if (typeof window !== 'undefined') {
      history.scrollRestoration = 'manual';
      const saved = sessionStorage.getItem(SCROLL_KEY);
      if (saved && parseInt(saved, 10) > 0) {
        pendingRestoreRef.current = true;
        isRestoringRef.current = true; // block scroll-saving during loading
      }
    }
    const handleScrollSave = () => {
      if (isRestoringRef.current) return; // don't save during restoration
      sessionStorage.setItem(SCROLL_KEY, String(window.scrollY));
    };
    window.addEventListener('scroll', handleScrollSave, { passive: true });
    return () => window.removeEventListener('scroll', handleScrollSave);
  }, [SCROLL_KEY]);

  // Restore scroll once products are rendered
  useEffect(() => {
    if (loading) return;
    if (!pendingRestoreRef.current) return;
    pendingRestoreRef.current = false;
    const saved = sessionStorage.getItem(SCROLL_KEY);
    if (!saved) {
      isRestoringRef.current = false;
      return;
    }
    const pos = parseInt(saved, 10);
    if (isNaN(pos) || pos <= 0) {
      isRestoringRef.current = false;
      return;
    }
    setTimeout(() => {
      isRestoringRef.current = true;
      window.scrollTo({ top: pos, behavior: 'smooth' });
      scrollRestoredRef.current = true;
      // Re-enable saving after smooth scroll animation finishes (~600ms)
      // and lock in the correct target position
      setTimeout(() => {
        isRestoringRef.current = false;
        sessionStorage.setItem(SCROLL_KEY, String(pos));
      }, 700);
    }, 120);
  }, [loading, SCROLL_KEY]);

  const [totalProducts, setTotalProducts] = useState(0);

  // Pagination states
  const paramPage = parseInt(searchParams.get('page') || '1', 10);
  const paramPerPage = parseInt(searchParams.get('perPage') || '20', 10);
  const [currentPage, setCurrentPage] = useState(paramPage);
  const [perPage, setPerPage] = useState(paramPerPage);
  const [lastPage, setLastPage] = useState(1);

  // Sync state with URL params
  useEffect(() => {
    setCurrentPage(paramPage);
  }, [paramPage]);

  useEffect(() => {
    setPerPage(paramPerPage);
  }, [paramPerPage]);

  const sortByParam = searchParams.get('sortBy') || 'latest';
  const maxPriceParam = searchParams.get('maxPrice') || '5000';
  const filterCatsParam = searchParams.get('filterCats') || '';
  const brandsParam = searchParams.get('brands') || '';
  const flagsParam = searchParams.get('flags') || '';

  // Fetch products under this collection/slug with active filters
  useEffect(() => {
    const fetchCollectionProducts = async () => {
      console.log('Collection page fetchCollectionProducts triggered. slug:', slug, 'page:', currentPage, 'perPage:', perPage);
      const cacheKey = `collection_cache_${slug}_${currentPage}_${perPage}_${sortByParam}_${maxPriceParam}_${filterCatsParam}_${brandsParam}_${flagsParam}`;
      
      // Try loading from session cache first for instant render
      let hasCache = false;
      if (typeof window !== 'undefined') {
        try {
          const cached = sessionStorage.getItem(cacheKey);
          if (cached) {
            const parsed = JSON.parse(cached);
            if (Array.isArray(parsed.products)) {
              setProducts(parsed.products);
              setLastPage(parsed.lastPage || 1);
              setTotalProducts(parsed.totalProducts || 0);
              setLoading(false);
              hasCache = true;
            }
          }
        } catch (e) {
          console.error('Failed to parse collection cache', e);
        }
      }

      if (!hasCache) {
        setLoading(true);
      }

      try {
        const queryParams = new URLSearchParams();
        
        const selectedCategories = filterCatsParam ? filterCatsParam.split(',') : [];
        const selectedBrands = brandsParam ? brandsParam.split(',') : [];
        const selectedFlags = flagsParam ? flagsParam.split(',') : [];
        const priceRange = parseInt(maxPriceParam || '5000', 10);
        const sortBy = sortByParam || 'latest';

        // Pass combined category slugs
        const allCategoriesToFetch = Array.from(new Set([slug, ...selectedCategories].filter(Boolean))).join(',');
        queryParams.set('category_slug', allCategoriesToFetch);
        queryParams.set('page', currentPage.toString());
        queryParams.set('sortBy', sortBy);
        queryParams.set('per_page', perPage.toString());

        const url = `/api/products?${queryParams.toString()}`;
        console.log('Requesting API URL:', url);
        const res = await api.get(url);
        console.log('API Response received:', res.status, res.data);
        
        let fetchedItems: Product[] = res.data.data || [];
        console.log('Fetched items count:', fetchedItems.length);
        
        // Price range filter
        fetchedItems = fetchedItems.filter(item => {
          const itemPrice = item.sale_price ?? item.price;
          return itemPrice <= priceRange;
        });

        // Brand mock filters (if brand option selected, match mock names in titles)
        if (selectedBrands.length > 0) {
          fetchedItems = fetchedItems.filter(item => {
            return selectedBrands.some(brand => 
              item.name.toLowerCase().includes(brand.toLowerCase())
            );
          });
        }

        // Product flag filter (Best Selling)
        if (selectedFlags.includes('best-selling')) {
          fetchedItems = fetchedItems.filter(item => item.is_best_selling);
        }

        console.log('Filtered items count:', fetchedItems.length);

        const fetchedLastPage = res.data.last_page || 1;
        const fetchedTotal = res.data.total || fetchedItems.length;

        setProducts(fetchedItems);
        setLastPage(fetchedLastPage);
        setTotalProducts(fetchedTotal);

        // Save to cache
        if (typeof window !== 'undefined') {
          try {
            sessionStorage.setItem(cacheKey, JSON.stringify({
              products: fetchedItems,
              lastPage: fetchedLastPage,
              totalProducts: fetchedTotal
            }));
          } catch (e) {
            console.error('Failed to write collection cache', e);
          }
        }
      } catch (err) {
        console.error('Failed to load collection products error:', err);
      } finally {
        console.log('Setting loading to false');
        setLoading(false);
      }
    };

    fetchCollectionProducts();
  }, [slug, currentPage, perPage, sortByParam, maxPriceParam, filterCatsParam, brandsParam, flagsParam]);

  const updateQueryParams = (updates: Record<string, string | null>) => {
    const current = new URLSearchParams(Array.from(searchParams.entries()));
    Object.entries(updates).forEach(([key, value]) => {
      if (value === null || value === '') {
        current.delete(key);
      } else {
        current.set(key, value);
      }
    });
    router.push(`/collections/${slug}?${current.toString()}`);
  };

  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= lastPage) {
      updateQueryParams({ page: newPage.toString() });
    }
  };

  return (
    <div className="space-y-6">
      {/* Toolbar (Sorting - Mockup Style) */}
      <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">
        {/* Filters Toggle Button (mobile only) */}
        <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 Container */}
        <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={sortByParam}
              onChange={(e) => {
                updateQueryParams({ sortBy: e.target.value, page: '1' });
              }}
              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">Default Sorting</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>
            </select>
            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2 text-slate-400">
              <svg className="h-3.5 w-3.5" 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>

        {/* Show count limit */}
        <div className="relative w-full lg:w-auto">
          <select
            value={perPage}
            onChange={(e) => {
              const val = parseInt(e.target.value, 10);
              updateQueryParams({ perPage: val.toString(), page: '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-orange-350 transition-colors"
          >
            <option value="12">Show 12</option>
            <option value="20">Show 20</option>
            <option value="40">Show 40</option>
            <option value="80">Show 80</option>
          </select>
          <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2 text-secondary">
            <svg className="h-3.5 w-3.5 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>

      {/* Product Grid / Skeleton */}
      {loading ? (
        <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 overflow-hidden rounded border border-slate-200 bg-white p-4 animate-pulse space-y-3">
              <div className="aspect-square bg-slate-100 rounded w-full"></div>
              <div className="h-3 bg-slate-150 rounded w-3/4"></div>
              <div className="h-3 bg-slate-150 rounded w-1/2"></div>
              <div className="h-8 bg-slate-150 rounded w-full mt-4"></div>
            </div>
          ))}
        </div>
      ) : products.length === 0 ? (
        <div className="text-center py-24 bg-white border border-dashed border-slate-200 rounded">
          <SlidersHorizontal className="h-10 w-10 text-slate-300 mx-auto mb-4" />
          <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">
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>

          {/* Pagination controls */}
          {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 {currentPage} of {lastPage}
              </span>
              
              <div className="flex items-center gap-1.5">
                <button
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 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 ${
                        currentPage === pageNum
                          ? 'bg-secondary text-white shadow-sm'
                          : 'border border-slate-200 text-slate-600 hover:bg-slate-50'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}

                <button
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === 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>
  );
};

const CollectionContent: React.FC = () => {
  const params = useParams();
  const slug = (params.slug as string) || '';
  const [categories, setCategories] = useState<Category[]>([]);
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);

  // Load category list once on mount
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const res = await api.get('/api/categories');
        setCategories(res.data.categories || []);
      } catch (err) {
        console.error('Failed to load categories', err);
      }
    };
    fetchCategories();
  }, []);

  // Resolve collection/category display title
  const activeSlugs = slug.split('-');
  const matchedCats = categories.filter(c => activeSlugs.includes(c.slug) || c.slug === slug);
  const collectionTitle = matchedCats.length > 0 
    ? matchedCats.map(c => c.name).join(' & ') 
    : slug === 'oil-ghee' ? 'Oil & Ghee' : slug.replace('-', ' ');

  return (
    <div className="w-full">
      {/* Breadcrumbs & Meta header */}
      <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">
            {collectionTitle}
          </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">{collectionTitle}</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 only) */}
          <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 space-y-4 animate-pulse">
                <div className="h-4 bg-slate-100 rounded w-1/2"></div>
                <div className="space-y-2">
                  {[...Array(5)].map((_, i) => (
                    <div key={i} className="h-3 bg-slate-100 rounded w-5/6"></div>
                  ))}
                </div>
              </div>
            }>
              <SidebarFilters categories={categories} slug={slug} />
            </Suspense>
          </aside>

          {/* Mobile Filter Drawer Overlay */}
          <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 categories={categories} slug={slug} />
            </div>
          </div>

          {/* Right Area: Sort & 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 overflow-hidden rounded border border-slate-200 bg-white p-4 space-y-3">
                    <div className="aspect-square bg-slate-100 rounded w-full"></div>
                    <div className="h-3 bg-slate-150 rounded w-3/4"></div>
                    <div className="h-3 bg-slate-150 rounded w-1/2"></div>
                    <div className="h-8 bg-slate-150 rounded w-full mt-4"></div>
                  </div>
                ))}
              </div>
            }>
              <ProductGridArea 
                categories={categories} 
                slug={slug} 
                onOpenMobileFilters={() => setMobileFiltersOpen(true)} 
              />
            </Suspense>
          </div>

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

export default function CollectionPage() {
  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 Collection...</span>
          </div>
        }>
          <CollectionContent />
        </Suspense>
      </main>
      <Footer />
    </>
  );
}
