/* ================================================
   XEVON — Premium Men's Fashion Store
   JavaScript — All Interactivity
   ================================================ */

/* ── Initialize Lucide Icons ──────────────────── */
lucide.createIcons();

/* ── Product Data Array ────────────────────────── */
const products = [
  {
    id: 1,
    name: 'Premium Cotton Panjabi',
    category: 'Panjabi',
    price: 1890,
    originalPrice: 2450,
    discount: 23,
    colors: ['Black', 'Navy', 'Cream'],
    sizes: ['M', 'L', 'XL'],
    badge: 'New',
    emoji: '🥻',
    colorBg: 'bg-amber-50',
    rating: 4.8,
    reviews: 124
  },
  {
    id: 2,
    name: 'Oversized Drop Shoulder Tee',
    category: 'T-Shirt',
    price: 650,
    originalPrice: 850,
    discount: 24,
    colors: ['Black', 'White', 'Gray'],
    sizes: ['M', 'L', 'XL', '2XL'],
    badge: 'Trending',
    emoji: '👕',
    colorBg: 'bg-blue-50',
    rating: 4.6,
    reviews: 89
  },
  {
    id: 3,
    name: 'Slim Fit Formal Shirt',
    category: 'Shirt',
    price: 1250,
    originalPrice: 1600,
    discount: 22,
    colors: ['White', 'Blue', 'Pink'],
    sizes: ['S', 'M', 'L', 'XL'],
    badge: '',
    emoji: '👔',
    colorBg: 'bg-rose-50',
    rating: 4.5,
    reviews: 67
  },
  {
    id: 4,
    name: 'Cotton Chino Trouser',
    category: 'Trouser',
    price: 990,
    originalPrice: 1350,
    discount: 27,
    colors: ['Khaki', 'Navy', 'Black'],
    sizes: ['M', 'L', 'XL'],
    badge: 'Best Seller',
    emoji: '👖',
    colorBg: 'bg-green-50',
    rating: 4.7,
    reviews: 203
  },
  {
    id: 5,
    name: 'Winter Hooded Jacket',
    category: 'Winter Wear',
    price: 2800,
    originalPrice: 4500,
    discount: 38,
    colors: ['Black', 'Gray', 'Olive'],
    sizes: ['L', 'XL', '2XL'],
    badge: 'Hot',
    emoji: '🧥',
    colorBg: 'bg-cyan-50',
    rating: 4.9,
    reviews: 156
  },
  {
    id: 6,
    name: 'Drop Shoulder Polo',
    category: 'Drop Shoulder',
    price: 780,
    originalPrice: 1100,
    discount: 29,
    colors: ['Navy', 'Maroon', 'Green'],
    sizes: ['M', 'L', 'XL'],
    badge: 'New',
    emoji: '🎽',
    colorBg: 'bg-purple-50',
    rating: 4.4,
    reviews: 45
  },
  {
    id: 7,
    name: 'Embroidered Panjabi',
    category: 'Panjabi',
    price: 2200,
    originalPrice: 2900,
    discount: 24,
    colors: ['White', 'Cream', 'Light Blue'],
    sizes: ['M', 'L', 'XL'],
    badge: 'Premium',
    emoji: '🥻',
    colorBg: 'bg-amber-50',
    rating: 4.9,
    reviews: 178
  },
  {
    id: 8,
    name: 'Graphic Print T-Shirt',
    category: 'T-Shirt',
    price: 550,
    originalPrice: 750,
    discount: 27,
    colors: ['Black', 'White'],
    sizes: ['S', 'M', 'L', 'XL', '2XL'],
    badge: '',
    emoji: '👕',
    colorBg: 'bg-indigo-50',
    rating: 4.3,
    reviews: 92
  },
  {
    id: 9,
    name: 'Relaxed Fit Trouser',
    category: 'Trouser',
    price: 890,
    originalPrice: 1200,
    discount: 26,
    colors: ['Black', 'Olive', 'Beige'],
    sizes: ['M', 'L', 'XL', '2XL'],
    badge: 'New',
    emoji: '👖',
    colorBg: 'bg-emerald-50',
    rating: 4.6,
    reviews: 54
  }
];

/* ── Application State ─────────────────────────── */
let cart = [];
let wishlist = new Set();

/* ── Color Name to Tailwind Class Map ───────────── */
const colorMap = {
  'Black': 'bg-gray-900',
  'White': 'bg-white border border-gray-300',
  'Navy': 'bg-blue-800',
  'Cream': 'bg-amber-100',
  'Gray': 'bg-gray-400',
  'Pink': 'bg-pink-300',
  'Blue': 'bg-blue-500',
  'Khaki': 'bg-yellow-600',
  'Olive': 'bg-green-700',
  'Maroon': 'bg-purple-900',
  'Green': 'bg-green-600',
  'Light Blue': 'bg-sky-200',
  'Beige': 'bg-amber-200'
};

/* ── Generate Star Rating HTML ──────────────────── */
function renderStars(rating) {
  const full = Math.floor(rating);
  const hasHalf = rating % 1 >= 0.5;
  let stars = '';
  for (let i = 0; i < full; i++) {
    stars += '<svg class="w-3 h-3 text-amber-400 fill-current" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/></svg>';
  }
  if (hasHalf) {
    stars += '<svg class="w-3 h-3 text-amber-400 fill-current" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" clip-path="inset(0 50% 0 0)"/></svg>';
  }
  return stars;
}

/* ── Render Product Cards into the Grid ────────── */
function renderProducts(filterCategory = 'All') {
  const grid = document.getElementById('product-grid');
  const filtered = filterCategory === 'All'
    ? products
    : products.filter(p => p.category === filterCategory);

  if (filtered.length === 0) {
    grid.innerHTML = `
      <div class="col-span-full text-center py-16">
        <svg class="w-16 h-16 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"/>
        </svg>
        <p class="text-gray-400 text-lg font-medium">No products found</p>
        <p class="text-gray-300 text-sm mt-1">Try a different category</p>
      </div>
    `;
    return;
  }

  grid.innerHTML = filtered.map(p => `
    <div class="product-card group bg-white rounded-2xl border border-gray-100 overflow-hidden" data-id="${p.id}" data-category="${p.category}">
      <!-- Product Image Area -->
      <div class="relative aspect-[3/4] overflow-hidden ${p.colorBg}">
        <div class="absolute inset-0 flex items-center justify-center">
          <span class="text-6xl lg:text-7xl product-image">${p.emoji}</span>
        </div>
        <!-- Discount Tag -->
        <span class="absolute top-3 left-3 bg-red-500 text-white text-xs font-bold px-2.5 py-1 rounded-full z-10 shadow-sm">-${p.discount}%</span>
        <!-- Badge Tag -->
        ${p.badge ? `<span class="absolute top-3 right-3 bg-brand text-white text-[10px] font-bold px-2.5 py-1 rounded-full z-10 shadow-sm">${p.badge}</span>` : ''}
        <!-- Quick View Overlay (desktop) -->
        <div class="absolute inset-x-0 bottom-0 p-3 bg-gradient-to-t from-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 translate-y-4 group-hover:translate-y-0 z-10">
          <button class="w-full py-2 bg-white/95 backdrop-blur-sm text-gray-800 text-xs font-semibold rounded-lg hover:bg-white transition-colors">
            Quick View
          </button>
        </div>
        <!-- Wishlist Heart Button -->
        <button onclick="toggleWishlist(${p.id}, this)" class="wishlist-btn absolute bottom-3 right-3 w-9 h-9 bg-white/90 backdrop-blur-sm rounded-full flex items-center justify-center shadow-md hover:bg-brand hover:text-white z-10 text-gray-400 ${wishlist.has(p.id) ? 'text-brand active' : ''}">
          <svg class="w-4 h-4" fill="${wishlist.has(p.id) ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/>
          </svg>
        </button>
      </div>
      <!-- Product Info -->
      <div class="p-3 lg:p-4">
        <p class="text-[10px] text-brand font-semibold uppercase tracking-widest mb-1">${p.category}</p>
        <h3 class="text-sm font-semibold text-gray-800 line-clamp-2 leading-snug mb-1.5 group-hover:text-brand transition-colors duration-200">${p.name}</h3>
        <!-- Star Rating -->
        <div class="flex items-center gap-1 mb-2">
          <div class="flex items-center gap-0.5">${renderStars(p.rating)}</div>
          <span class="text-[10px] text-gray-400">(${p.reviews})</span>
        </div>
        <!-- Price -->
        <div class="flex items-baseline gap-2 mb-3">
          <span class="text-base font-bold text-gray-900">৳${p.price.toLocaleString()}</span>
          <span class="text-xs text-gray-400 line-through">৳${p.originalPrice.toLocaleString()}</span>
        </div>
        <!-- Color Swatches -->
        <div class="flex items-center gap-1.5 mb-3">
          ${p.colors.map(c => `<span class="w-4 h-4 rounded-full color-swatch ${colorMap[c] || 'bg-gray-300'} border border-gray-200" title="${c}"></span>`).join('')}
        </div>
        <!-- Add to Cart Button -->
        <button onclick="addToCart(${p.id})" class="quick-add-btn w-full py-2.5 bg-gray-900 hover:bg-brand text-white text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5">
          <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 100 4 2 2 0 000-4z"/>
          </svg>
          Select Options
        </button>
      </div>
    </div>
  `).join('');
}

/* ── Wishlist Toggle Function ──────────────────── */
function toggleWishlist(productId, btnEl) {
  const svg = btnEl.querySelector('svg');
  if (wishlist.has(productId)) {
    wishlist.delete(productId);
    btnEl.classList.remove('text-brand', 'active');
    btnEl.classList.add('text-gray-400');
    svg.setAttribute('fill', 'none');
  } else {
    wishlist.add(productId);
    btnEl.classList.add('text-brand', 'active');
    btnEl.classList.remove('text-gray-400');
    svg.setAttribute('fill', 'currentColor');
    btnEl.classList.add('scale-125');
    setTimeout(() => btnEl.classList.remove('scale-125'), 250);
  }
  updateWishlistCount();
}

/* ── Update Wishlist Badge Counters ───────────── */
function updateWishlistCount() {
  const count = wishlist.size;
  ['wishlist-count', 'mobile-wishlist-badge'].forEach(id => {
    const el = document.getElementById(id);
    if (!el) return;
    if (count > 0) {
      el.textContent = count;
      el.classList.remove('hidden');
      el.classList.add('flex');
    } else {
      el.classList.add('hidden');
      el.classList.remove('flex');
    }
  });
}

/* ── Add to Cart Function ──────────────────────── */
function addToCart(productId) {
  const product = products.find(p => p.id === productId);
  if (!product) return;

  const existing = cart.find(item => item.id === productId);
  if (existing) {
    existing.quantity++;
  } else {
    cart.push({ ...product, quantity: 1 });
  }
  updateCartUI();
  openCartDrawer();

  // Visual feedback on the product card button
  const card = document.querySelector(`.product-card[data-id="${productId}"]`);
  if (card) {
    card.classList.add('added');
    const btn = card.querySelector('.quick-add-btn');
    if (btn) {
      const origHTML = btn.innerHTML;
      btn.innerHTML = `
        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/>
        </svg>
        Added to Cart!
      `;
      setTimeout(() => {
        btn.innerHTML = origHTML;
        card.classList.remove('added');
      }, 1500);
    }
  }
}

/* ── Remove Item from Cart ─────────────────────── */
function removeFromCart(productId) {
  // Animate removal
  const cartItem = document.querySelector(`.cart-item[data-cart-id="${productId}"]`);
  if (cartItem) {
    cartItem.classList.add('removing');
    setTimeout(() => {
      cart = cart.filter(item => item.id !== productId);
      updateCartUI();
    }, 300);
  } else {
    cart = cart.filter(item => item.id !== productId);
    updateCartUI();
  }
}

/* ── Update Cart Item Quantity ──────────────────── */
function updateCartQuantity(productId, delta) {
  const item = cart.find(i => i.id === productId);
  if (!item) return;
  item.quantity += delta;
  if (item.quantity <= 0) {
    removeFromCart(productId);
    return;
  }
  updateCartUI();
}

/* ── Update Cart UI (badges, items, totals) ────── */
function updateCartUI() {
  const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);

  // Update all badge counters
  ['cart-badge', 'mobile-cart-badge'].forEach(id => {
    const el = document.getElementById(id);
    if (!el) return;
    if (totalItems > 0) {
      el.textContent = totalItems;
      el.classList.remove('hidden');
      el.classList.add('flex');
    } else {
      el.classList.add('hidden');
      el.classList.remove('flex');
    }
  });
  const drawerCount = document.getElementById('cart-drawer-count');
  if (drawerCount) drawerCount.textContent = `(${totalItems})`;

  const emptyState = document.getElementById('cart-empty-state');
  const itemsList = document.getElementById('cart-items-list');
  const footer = document.getElementById('cart-footer');

  if (cart.length === 0) {
    emptyState.classList.remove('hidden');
    itemsList.classList.add('hidden');
    footer.classList.add('hidden');
  } else {
    emptyState.classList.add('hidden');
    itemsList.classList.remove('hidden');
    footer.classList.remove('hidden');

    itemsList.innerHTML = cart.map(item => `
      <div class="cart-item flex gap-3 p-3 bg-gray-50 rounded-xl" data-cart-id="${item.id}">
        <div class="w-16 h-16 ${item.colorBg} rounded-lg flex items-center justify-center flex-shrink-0">
          <span class="text-2xl">${item.emoji}</span>
        </div>
        <div class="flex-1 min-w-0">
          <h4 class="text-sm font-semibold text-gray-800 truncate">${item.name}</h4>
          <p class="text-xs text-gray-400 mt-0.5">${item.category}</p>
          <div class="flex items-center justify-between mt-2">
            <div class="flex items-center gap-2">
              <button onclick="updateCartQuantity(${item.id}, -1)" class="w-7 h-7 bg-white border border-gray-200 rounded-md flex items-center justify-center text-gray-600 hover:border-brand hover:text-brand transition text-xs font-bold">-</button>
              <span class="text-sm font-semibold w-5 text-center">${item.quantity}</span>
              <button onclick="updateCartQuantity(${item.id}, 1)" class="w-7 h-7 bg-white border border-gray-200 rounded-md flex items-center justify-center text-gray-600 hover:border-brand hover:text-brand transition text-xs font-bold">+</button>
            </div>
            <span class="text-sm font-bold text-gray-900">৳${(item.price * item.quantity).toLocaleString()}</span>
          </div>
        </div>
        <button onclick="removeFromCart(${item.id})" class="text-gray-300 hover:text-red-500 transition self-start mt-0.5 p-1">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
          </svg>
        </button>
      </div>
    `).join('');

    document.getElementById('cart-subtotal').textContent = `৳${subtotal.toLocaleString()}`;
    document.getElementById('cart-total').textContent = `৳${subtotal.toLocaleString()}`;
  }
}

/* ── Cart Drawer Open / Close ──────────────────── */
function openCartDrawer() {
  const overlay = document.getElementById('cart-overlay');
  const drawer = document.getElementById('cart-drawer');
  overlay.classList.remove('hidden');
  requestAnimationFrame(() => {
    overlay.style.opacity = '1';
  });
  drawer.classList.add('open');
  document.body.style.overflow = 'hidden';
}

function closeCartDrawer() {
  const overlay = document.getElementById('cart-overlay');
  const drawer = document.getElementById('cart-drawer');
  overlay.style.opacity = '0';
  setTimeout(() => overlay.classList.add('hidden'), 350);
  drawer.classList.remove('open');
  document.body.style.overflow = '';
}

document.getElementById('cart-btn').addEventListener('click', openCartDrawer);
document.getElementById('mobile-cart-btn').addEventListener('click', openCartDrawer);
document.getElementById('close-cart-drawer').addEventListener('click', closeCartDrawer);
document.getElementById('cart-overlay').addEventListener('click', closeCartDrawer);
document.getElementById('continue-shopping-btn').addEventListener('click', closeCartDrawer);

/* ── Mobile Slide-Out Menu ──────────────────────── */
function openMobileMenu() {
  const overlay = document.getElementById('mobile-menu-overlay');
  const menu = document.getElementById('mobile-menu');
  overlay.classList.remove('hidden');
  requestAnimationFrame(() => {
    overlay.style.opacity = '1';
  });
  menu.style.transform = 'translateX(0)';
  document.body.style.overflow = 'hidden';
}

function closeMobileMenu() {
  const overlay = document.getElementById('mobile-menu-overlay');
  const menu = document.getElementById('mobile-menu');
  menu.style.transform = 'translateX(-100%)';
  overlay.style.opacity = '0';
  setTimeout(() => overlay.classList.add('hidden'), 350);
  document.body.style.overflow = '';
}

document.getElementById('hamburger-btn').addEventListener('click', openMobileMenu);
document.getElementById('close-mobile-menu').addEventListener('click', closeMobileMenu);
document.getElementById('mobile-menu-overlay').addEventListener('click', closeMobileMenu);

/* ── Mobile Filter Drawer ───────────────────────── */
function openFilterDrawer() {
  const overlay = document.getElementById('mobile-filter-overlay');
  const drawer = document.getElementById('mobile-filter-drawer');
  overlay.classList.remove('hidden');
  requestAnimationFrame(() => {
    overlay.style.opacity = '1';
  });
  drawer.style.transform = 'translateX(0)';
  document.body.style.overflow = 'hidden';
}

function closeFilterDrawer() {
  const overlay = document.getElementById('mobile-filter-overlay');
  const drawer = document.getElementById('mobile-filter-drawer');
  drawer.style.transform = 'translateX(-100%)';
  overlay.style.opacity = '0';
  setTimeout(() => overlay.classList.add('hidden'), 350);
  document.body.style.overflow = '';
}

document.getElementById('filter-toggle-btn').addEventListener('click', openFilterDrawer);
document.getElementById('close-filter-drawer').addEventListener('click', closeFilterDrawer);
document.getElementById('mobile-filter-overlay').addEventListener('click', closeFilterDrawer);

/* ── Hero Slider Logic ─────────────────────────── */
const slides = document.querySelectorAll('.hero-slide');
const dots = document.querySelectorAll('.hero-dot');
let currentSlide = 0;
let slideInterval;

function goToSlide(index) {
  slides.forEach(s => s.classList.remove('active'));
  dots.forEach(d => d.classList.remove('active'));
  slides[index].classList.add('active');
  dots[index].classList.add('active');
  currentSlide = index;
}

function nextSlide() {
  goToSlide((currentSlide + 1) % slides.length);
}

function prevSlide() {
  goToSlide((currentSlide - 1 + slides.length) % slides.length);
}

function startAutoSlide() {
  slideInterval = setInterval(nextSlide, 5000);
}

function resetAutoSlide() {
  clearInterval(slideInterval);
  startAutoSlide();
}

document.getElementById('hero-next').addEventListener('click', () => {
  nextSlide();
  resetAutoSlide();
});
document.getElementById('hero-prev').addEventListener('click', () => {
  prevSlide();
  resetAutoSlide();
});
dots.forEach(dot => {
  dot.addEventListener('click', () => {
    goToSlide(parseInt(dot.dataset.dot));
    resetAutoSlide();
  });
});

// Touch/swipe support for hero slider
let touchStartX = 0;
let touchEndX = 0;
const heroSlider = document.getElementById('hero-slider');

heroSlider.addEventListener('touchstart', (e) => {
  touchStartX = e.changedTouches[0].screenX;
}, { passive: true });

heroSlider.addEventListener('touchend', (e) => {
  touchEndX = e.changedTouches[0].screenX;
  const diff = touchStartX - touchEndX;
  if (Math.abs(diff) > 50) {
    if (diff > 0) {
      nextSlide();
    } else {
      prevSlide();
    }
    resetAutoSlide();
  }
}, { passive: true });

goToSlide(0);
startAutoSlide();

/* ── Price Range Slider Label Update ────────────── */
const priceRange = document.getElementById('price-range');
if (priceRange) {
  const updateRangeBackground = () => {
    const val = priceRange.value;
    const min = priceRange.min;
    const max = priceRange.max;
    const percentage = ((val - min) / (max - min)) * 100;
    priceRange.style.background = `linear-gradient(to right, var(--brand) ${percentage}%, var(--gray-200) ${percentage}%)`;
  };

  priceRange.addEventListener('input', function () {
    document.getElementById('price-max-label').textContent = `৳${parseInt(this.value).toLocaleString()}`;
    updateRangeBackground();
  });

  updateRangeBackground();
}

/* ── Scroll Fade-Up Animation (Intersection Observer) ── */
const fadeObserver = new IntersectionObserver(
  (entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
        fadeObserver.unobserve(entry.target);
      }
    });
  },
  { threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
);
document.querySelectorAll('.fade-up').forEach(el => fadeObserver.observe(el));

/* ── Header Shadow Enhancement on Scroll ────────── */
const header = document.getElementById('main-header');
let lastScrollY = 0;

window.addEventListener('scroll', () => {
  const scrollY = window.scrollY;

  if (scrollY > 10) {
    header.classList.add('scrolled');
  } else {
    header.classList.remove('scrolled');
  }

  lastScrollY = scrollY;
}, { passive: true });

/* ── Load More Button ───────────────────────────── */
document.getElementById('load-more-btn').addEventListener('click', function () {
  const btn = this;
  const origText = btn.innerHTML;
  btn.innerHTML = `
    <svg class="w-5 h-5 animate-spin mx-auto" fill="none" viewBox="0 0 24 24">
      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
    </svg>
  `;
  btn.disabled = true;

  setTimeout(() => {
    btn.innerHTML = 'No More Products';
    btn.classList.add('opacity-50', 'cursor-not-allowed');
  }, 1500);
});

/* ── Category Filter Pills (active toggle + filtering) ── */
let currentCategory = 'All';

document.querySelectorAll('.category-pill').forEach(btn => {
  btn.addEventListener('click', function () {
    document.querySelectorAll('.category-pill').forEach(b => {
      b.classList.remove('bg-brand', 'text-white');
      b.classList.add('bg-gray-100', 'text-gray-700');
    });
    this.classList.remove('bg-gray-100', 'text-gray-700');
    this.classList.add('bg-brand', 'text-white');

    currentCategory = this.dataset.cat;
    renderProducts(currentCategory);
  });
});

/* ── Size Filter Buttons (active toggle in sidebar) ── */
document.querySelectorAll('.size-btn').forEach(btn => {
  btn.addEventListener('click', function () {
    this.classList.toggle('selected');
  });
});

/* ── Announcement Bar Close ────────────────────── */
const announceBar = document.getElementById('announcement-bar');
const announceClose = document.getElementById('close-announce');
if (announceClose) {
  announceClose.addEventListener('click', () => {
    announceBar.style.transform = 'translateY(-100%)';
    announceBar.style.opacity = '0';
    setTimeout(() => announceBar.style.display = 'none', 300);
  });
}

/* ── Keyboard Shortcuts ─────────────────────────── */
document.addEventListener('keydown', (e) => {
  // ESC to close drawers
  if (e.key === 'Escape') {
    closeCartDrawer();
    closeMobileMenu();
    closeFilterDrawer();
  }
});

/* ── Initial Product Render ────────────────────── */
renderProducts();
