/* ==============================================================
   UNICAM — scripts.js  (FIXED)
   Bootstrap 5 required: loaded via CDN in index.html
============================================================== */

/* Safety: ensure bootstrap is available */
function _getModal(id) {
  const el = document.getElementById(id);
  if (!el || typeof bootstrap === 'undefined') {
    console.error('Bootstrap not loaded or element #' + id + ' not found');
    return null;
  }
  return bootstrap.Modal.getOrCreateInstance(el);
}

/* ══════════════════════════════════════════════
   MEGA MENU: JS hover bridge (gap-free)
══════════════════════════════════════════════ */
document.querySelectorAll('.has-mega').forEach(li => {
  let timer;
  const panel = li.querySelector('.mega-panel');
  li.addEventListener('mouseenter', () => { clearTimeout(timer); li.classList.add('mega-open'); });
  li.addEventListener('mouseleave', () => { timer = setTimeout(() => li.classList.remove('mega-open'), 80); });
  if (panel) {
    panel.addEventListener('mouseenter', () => clearTimeout(timer));
    panel.addEventListener('mouseleave', () => { timer = setTimeout(() => li.classList.remove('mega-open'), 80); });
  }
});

/* ══════════════════════════════════════════════
   STICKY NAV SHADOW (single listener)
══════════════════════════════════════════════ */
window.addEventListener('scroll', () => {
  const nav = document.getElementById('mainNav');
  if (nav) nav.classList.toggle('scrolled', window.scrollY > 10);
});

/* ══════════════════════════════════════════════
   MOBILE NAV TOGGLE
══════════════════════════════════════════════ */
function toggleMobileNav() {
  const nav = document.getElementById('mobileNav');
  if (nav) nav.classList.toggle('open');
}

/* ══════════════════════════════════════════════
   MOBILE NAV ACCORDION
══════════════════════════════════════════════ */
function toggleMobMenu(trigger, menuId) {
  const menu = document.getElementById(menuId);
  if (!menu) return;
  const isOpen = menu.classList.contains('open');
  document.querySelectorAll('.mob-submenu.open').forEach(m => m.classList.remove('open'));
  document.querySelectorAll('.mob-nav-link.open').forEach(l => l.classList.remove('open'));
  if (!isOpen) { menu.classList.add('open'); trigger.classList.add('open'); }
}

/* ══════════════════════════════════════════════
   HERO BANNER AUTO SLIDER
══════════════════════════════════════════════ */
(function () {
  const slides    = document.querySelectorAll('.hero-slide');
  const dots      = document.querySelectorAll('.slider-dot');
  const badgeStat  = document.getElementById('heroBadgeStat');
  const badgeLabel = document.getElementById('heroBadgeLabel');
  if (!slides.length) return;

  const badgeData = [
    { stat: '500+', label: 'Items Available' },
    { stat: '12+',  label: 'Top Brands'      },
    { stat: '4.9★', label: 'Rated Service'   },
  ];

  let current = 0, timer;

  function _activate(idx) {
    slides[current].classList.remove('active');
    if (dots[current]) dots[current].classList.remove('active');
    current = (idx + slides.length) % slides.length;
    slides[current].classList.add('active');
    if (dots[current]) dots[current].classList.add('active');
    if (badgeStat && badgeLabel && badgeData[current]) {
      badgeStat.textContent  = badgeData[current].stat;
      badgeLabel.textContent = badgeData[current].label;
    }
  }

  function _startAuto() { timer = setInterval(() => _activate(current + 1), 4500); }
  function _stopAuto()  { clearInterval(timer); }

  window.goToSlide = function (idx) { _stopAuto(); _activate(idx); _startAuto(); };

  const heroSlider = document.getElementById('heroSlider');
  if (heroSlider) {
    heroSlider.addEventListener('mouseenter', _stopAuto);
    heroSlider.addEventListener('mouseleave', _startAuto);
  }
  _startAuto();
})();

/* ══════════════════════════════════════════════
   SCROLL REVEAL (single observer)
══════════════════════════════════════════════ */
const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.12 });

document.querySelectorAll('.reveal').forEach(el => revealObserver.observe(el));

/* ══════════════════════════════════════════════
   QUICK VIEW MODAL
══════════════════════════════════════════════ */
let currentProduct = { name: null, img: null };

function openQuickView(name, brand, imgUrl, desc, features) {
  currentProduct = { name, img: imgUrl };
  const titleEl = document.getElementById('qvModalTitle');
  const brandEl = document.getElementById('qvBrand');
  const nameEl  = document.getElementById('qvName');
  const descEl  = document.getElementById('qvDesc');
  const imgEl   = document.getElementById('qvImg');
  const ulEl    = document.getElementById('qvFeatures');
  if (titleEl) titleEl.textContent = name;
  if (brandEl) brandEl.textContent = brand;
  if (nameEl)  nameEl.textContent  = name;
  if (descEl)  descEl.textContent  = desc;
  if (imgEl)   { imgEl.src = imgUrl; imgEl.alt = name; }
  if (ulEl)    ulEl.innerHTML = features.map(f => `<li><i class="fa fa-check-circle"></i> ${f}</li>`).join('');
  const rentBtn = document.getElementById('qvRentBtn');
  if (rentBtn) {
    rentBtn.onclick = () => {
      const _qvHide = _getModal('quickViewModal'); if (_qvHide) _qvHide.hide();
      setTimeout(() => openEnquiry(name, imgUrl, null), 350);
    };
  }
  const _qvShow = _getModal('quickViewModal'); if (_qvShow) _qvShow.show();
}

/* ══════════════════════════════════════════════
   MULTI-STEP ENQUIRY MODAL
══════════════════════════════════════════════ */
let _selectedDuration = '1 Week';

function openEnquiry(productName, imgUrl, e) {
  if (e && e.preventDefault) e.preventDefault();
  const name = productName || 'General Enquiry';
  const img  = imgUrl || 'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=300&q=80&auto=format&fit=crop';

  const prodNameEl = document.getElementById('enqProdName');
  const prodImgEl  = document.getElementById('enqProdImg');
  const prodDescEl = document.getElementById('enqProdDesc');
  if (prodNameEl) prodNameEl.textContent = name;
  if (prodImgEl)  { prodImgEl.src = img; prodImgEl.alt = name; }
  if (prodDescEl) prodDescEl.textContent = 'Submit your rental enquiry for ' + name + '. Our team confirms availability within 2 hours.';

  goToStep1(true);

  // Pre-tick camera matching product name
  document.querySelectorAll('#cameraGrid input[type="checkbox"]').forEach(cb => {
    cb.checked = name.toLowerCase().includes(cb.value.toLowerCase().split(' ')[0].toLowerCase());
  });

  // Set min dates
  const today = new Date().toISOString().split('T')[0];
  const fromEl = document.getElementById('rentFrom');
  const toEl   = document.getElementById('rentTo');
  if (fromEl) { fromEl.min = today; fromEl.value = today; }
  if (toEl)   { toEl.min = today; }
  if (fromEl) fromEl.onchange = () => { if (toEl) toEl.min = fromEl.value; };

  const _enqShow = _getModal('enquiryModal'); if (_enqShow) _enqShow.show();
}

// Legacy alias
function submitEnquiry(e) { if (e && e.preventDefault) e.preventDefault(); submitEnquiryFinal(); }

/* ── Step 1 → Step 2 ── */
function goToStep2() {
  const camChecked = document.querySelectorAll('#cameraGrid input:checked').length;
  const lenChecked = document.querySelectorAll('#lensGrid input:checked').length;
  if (camChecked === 0 && lenChecked === 0) {
    alert('Please select at least one camera or lens to continue.');
    return;
  }
  const cams = [...document.querySelectorAll('#cameraGrid input:checked')].map(c => c.value);
  const lens = [...document.querySelectorAll('#lensGrid input:checked')].map(c => c.value);
  const acc  = [...document.querySelectorAll('[name="accessories"]:checked')].map(c => c.value);
  const desc = document.getElementById('enqDescription') ? document.getElementById('enqDescription').value : '';
  let summary = '';
  if (cams.length) summary += '<b>Cameras:</b> ' + cams.join(', ') + '<br>';
  if (lens.length) summary += '<b>Lenses:</b> ' + lens.join(', ') + '<br>';
  if (acc.length)  summary += '<b>Accessories:</b> ' + acc.join(', ') + '<br>';
  summary += '<b>Duration:</b> ' + _selectedDuration;
  if (desc && desc.trim()) summary += '<br><b>Notes:</b> ' + desc.trim();
  const summaryEl = document.getElementById('enqSummary');
  if (summaryEl) summaryEl.innerHTML = summary;

  document.getElementById('enqPanel1').classList.remove('active');
  document.getElementById('enqPanel2').classList.add('active');
  const dot1 = document.getElementById('stepDot1');
  if (dot1) {
    dot1.classList.remove('active'); dot1.classList.add('done');
    dot1.querySelector('.enq-step-num').innerHTML = '<i class="fa fa-check" style="font-size:0.65rem;"></i>';
  }
  const line1 = document.getElementById('stepLine1');
  if (line1) line1.classList.add('done');
  const dot2 = document.getElementById('stepDot2');
  if (dot2) dot2.classList.add('active');
  const titleEl = document.getElementById('enqFormTitle');
  const subEl   = document.getElementById('enqFormSub');
  if (titleEl) titleEl.textContent = 'Almost Done!';
  if (subEl)   subEl.textContent   = 'Step 2 of 2: Enter your details';
}

/* ── Step 2 → Step 1 ── */
function goToStep1(reset) {
  const p1 = document.getElementById('enqPanel1');
  const p2 = document.getElementById('enqPanel2');
  if (p1) p1.classList.add('active');
  if (p2) p2.classList.remove('active');
  const dot1 = document.getElementById('stepDot1');
  if (dot1) {
    dot1.classList.add('active'); dot1.classList.remove('done');
    dot1.querySelector('.enq-step-num').textContent = '1';
  }
  const line1 = document.getElementById('stepLine1');
  if (line1) line1.classList.remove('done');
  const dot2 = document.getElementById('stepDot2');
  if (dot2) dot2.classList.remove('active');
  const titleEl = document.getElementById('enqFormTitle');
  const subEl   = document.getElementById('enqFormSub');
  if (titleEl) titleEl.textContent = 'Rental Enquiry';
  if (subEl)   subEl.textContent   = 'Step 1: Select your gear & dates';
  if (reset) {
    document.querySelectorAll('#cameraGrid input, #lensGrid input, [name="accessories"]').forEach(cb => cb.checked = false);
    const descEl = document.getElementById('enqDescription');
    if (descEl) descEl.value = '';
    document.querySelectorAll('.dur-pill').forEach(p => p.classList.remove('selected'));
    const def = document.querySelector('.dur-pill[onclick*="1 Week"]');
    if (def) def.classList.add('selected');
    _selectedDuration = '1 Week';
    const cd = document.getElementById('customDates');
    if (cd) cd.style.display = 'none';
    const accSec = document.getElementById('accSection');
    if (accSec) accSec.classList.remove('open');
  }
}

/* ── Duration pills ── */
function selectDuration(pill, val) {
  document.querySelectorAll('.dur-pill').forEach(p => p.classList.remove('selected'));
  pill.classList.add('selected');
  _selectedDuration = val;
  const cd = document.getElementById('customDates');
  if (cd) cd.style.display = (val === 'Custom') ? 'flex' : 'none';
}

/* ── Accessories toggle ── */
function toggleAccSection(btn) {
  const sec = document.getElementById('accSection');
  if (!sec) return;
  const isOpen = sec.classList.toggle('open');
  btn.innerHTML = isOpen
    ? '<i class="fa fa-minus-circle"></i> Hide Accessories'
    : '<i class="fa fa-plus-circle"></i> Add Accessories (Optional)';
}

/* ── Final submit (step 2) ── */
function submitEnquiryFinal() {
  const nameEl  = document.getElementById('enqName');
  const phoneEl = document.getElementById('enqPhone');
  const locEl   = document.getElementById('enqLocation');
  const name    = nameEl  ? nameEl.value.trim()  : '';
  const phone   = phoneEl ? phoneEl.value.trim() : '';
  const loc     = locEl   ? locEl.value          : '';
  if (!name)  { if (nameEl)  nameEl.focus();  alert('Please enter your name.'); return; }
  if (!phone) { if (phoneEl) phoneEl.focus(); alert('Please enter your phone number.'); return; }
  if (!loc)   { if (locEl)   locEl.focus();   alert('Please select your city.'); return; }

  const _hideEnq = _getModal('enquiryModal'); if (_hideEnq) _hideEnq.hide();
  const toast = document.getElementById('successToast');
  if (toast) { toast.style.display = 'flex'; setTimeout(() => { toast.style.display = 'none'; }, 5000); }
  setTimeout(() => {
    goToStep1(true);
    ['enqName','enqPhone','enqEmail'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; });
    const locClear = document.getElementById('enqLocation');
    if (locClear) locClear.value = '';
  }, 600);
}

/* ── Shared modal setup (product-detail page) ── */
function setupModal(name, img, camCbId) {
  const prodNameEl = document.getElementById('enqProdName');
  const prodImgEl  = document.getElementById('enqProdImg');
  const prodDescEl = document.getElementById('enqProdDesc');
  if (prodNameEl) prodNameEl.textContent = name;
  if (prodImgEl)  { prodImgEl.src = img; prodImgEl.alt = name; }
  if (prodDescEl) prodDescEl.textContent = 'Enquiry for ' + name + '. Our team confirms availability within 2 hours.';
  document.querySelectorAll('#enquiryModal input[type="checkbox"]').forEach(cb => cb.checked = false);
  if (camCbId) { const cb = document.getElementById(camCbId); if (cb) cb.checked = true; }
  const today = new Date().toISOString().split('T')[0];
  const fromEl = document.getElementById('rentFrom');
  const toEl   = document.getElementById('rentTo');
  if (fromEl) { fromEl.min = today; fromEl.value = today; }
  if (toEl)   { toEl.min = today; }
  if (fromEl) fromEl.onchange = () => { if (toEl) toEl.min = fromEl.value; };
  goToStep1(false);
}

function openEnquiryFor(name, img) { setupModal(name, img, null); }

/* ══════════════════════════════════════════════
   PRODUCT FILTER TABS
══════════════════════════════════════════════ */
function filterProducts(cat, btn) {
  document.querySelectorAll('.ftab').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  document.querySelectorAll('.prod-item').forEach(item => {
    item.style.display = (cat === 'all' || item.dataset.cat === cat) ? '' : 'none';
  });
}

/* ══════════════════════════════════════════════
   BROWSE-BY-CATEGORY → filter + scroll
══════════════════════════════════════════════ */
function filterAndScroll(cat) {
  const target = document.getElementById('products');
  const tab = [...document.querySelectorAll('.ftab')].find(b =>
    b.textContent.trim().toLowerCase().startsWith(
      cat === 'camera' ? 'cam' : cat === 'lens' ? 'len' : 'acc'
    )
  );
  if (tab) filterProducts(cat, tab);
  if (target) target.scrollIntoView({ behavior: 'smooth' });
}

/* ══════════════════════════════════════════════
   CATEGORY PAGE: filterCats, liveSearch, goToListing
══════════════════════════════════════════════ */
function filterCats(filter, btn) {
  document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
  btn.classList.add('active');
  const items = document.querySelectorAll('.cat-item');
  let visible = 0;
  items.forEach(item => {
    const match = filter === 'all' || item.dataset.cat === filter;
    item.style.display = match ? '' : 'none';
    if (match) visible++;
  });
  const lbl = document.getElementById('filterLabel');
  const lblTxt = document.getElementById('filterLabelText');
  if (lbl && lblTxt) {
    if (filter !== 'all') {
      lbl.style.display = 'block';
      lblTxt.textContent = btn.textContent.trim().replace(/\d+/g, '').trim() + ' (' + visible + ' category)';
    } else {
      lbl.style.display = 'none';
    }
  }
  const noRes = document.getElementById('noResults');
  if (noRes) noRes.style.display = visible === 0 ? 'block' : 'none';
}

function liveSearch(query) {
  const q = query.toLowerCase().trim();
  const items = document.querySelectorAll('.cat-item');
  let visible = 0;
  items.forEach(item => {
    const title = item.querySelector('.cat-card-title')?.textContent.toLowerCase() || '';
    const desc  = item.querySelector('.cat-card-desc')?.textContent.toLowerCase()  || '';
    const tags  = item.querySelector('.cat-tag-row')?.textContent.toLowerCase()    || '';
    const match = !q || title.includes(q) || desc.includes(q) || tags.includes(q);
    item.style.display = match ? '' : 'none';
    if (match) visible++;
  });
  if (q) document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
  const noRes = document.getElementById('noResults');
  if (noRes) noRes.style.display = visible === 0 ? 'block' : 'none';
  const lbl = document.getElementById('filterLabel');
  if (lbl) lbl.style.display = 'none';
}

function goToListing(category) {
  const target = document.getElementById('featured');
  if (target) target.scrollIntoView({ behavior: 'smooth' });
}

/* ══════════════════════════════════════════════
   PRODUCT DETAIL PAGE
══════════════════════════════════════════════ */
const PAGE_PROD = {
  name: 'Sony FX3 Cinema Camera',
  img:  'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=300&q=80&auto=format&fit=crop',
  camCbId: 'gc1'
};

function switchImg(thumb, src) {
  const mainImg = document.getElementById('mainImg');
  if (mainImg) mainImg.src = src;
  document.querySelectorAll('.pd-thumb').forEach(t => t.classList.remove('active'));
  thumb.classList.add('active');
}

function selectBoxChip(el) {
  document.querySelectorAll('.pdbb-chip').forEach(c => c.classList.remove('active'));
  el.classList.add('active');
}

function selectChip(el) {
  document.querySelectorAll('.pd-chip').forEach(c => c.classList.remove('active'));
  el.classList.add('active');
}

function switchTab(id, btn) {
  document.querySelectorAll('.pd-tab-pane').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.pd-tab-btn').forEach(b => b.classList.remove('active'));
  const pane = document.getElementById('tab-' + id);
  if (pane) pane.classList.add('active');
  btn.classList.add('active');
}

function toggleWishlist(btn) {
  const saved = btn.innerHTML.includes('fa-solid');
  btn.innerHTML = saved
    ? '<i class="fa-regular fa-heart"></i> Add to Wishlist'
    : '<i class="fa-solid fa-heart" style="color:var(--red)"></i> Saved to Wishlist';
}

/* ══════════════════════════════════════════════
   CONTACT PAGE
══════════════════════════════════════════════ */
function selectSubject(el) {
  document.querySelectorAll('.subj-chip').forEach(c => c.classList.remove('active'));
  el.classList.add('active');
}

function toggleFaq(btn) {
  const answer = btn.nextElementSibling;
  const isOpen = btn.classList.contains('open');
  document.querySelectorAll('.faq-question.open').forEach(q => {
    q.classList.remove('open');
    if (q.nextElementSibling) q.nextElementSibling.classList.remove('open');
  });
  if (!isOpen) {
    btn.classList.add('open');
    if (answer) answer.classList.add('open');
  }
}

function submitForm(e) {
  e.preventDefault();
  let valid = true;
  const name    = document.getElementById('fName');
  const email   = document.getElementById('fEmail');
  const phone   = document.getElementById('fPhone');
  const message = document.getElementById('fMessage');
  if (!name || !email || !phone || !message) return;
  [name, email, phone, message].forEach(f => f.classList.remove('has-error'));
  document.querySelectorAll('.field-error').forEach(el => el.classList.remove('show'));
  if (!name.value.trim()) { name.classList.add('has-error'); const err = document.getElementById('errName'); if (err) err.classList.add('show'); valid = false; }
  const emailRx = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRx.test(email.value.trim())) { email.classList.add('has-error'); const err = document.getElementById('errEmail'); if (err) err.classList.add('show'); valid = false; }
  const phoneClean = phone.value.replace(/\D/g, '');
  if (phoneClean.length < 8) { phone.classList.add('has-error'); const err = document.getElementById('errPhone'); if (err) err.classList.add('show'); valid = false; }
  if (!message.value.trim()) { message.classList.add('has-error'); const err = document.getElementById('errMessage'); if (err) err.classList.add('show'); valid = false; }
  if (!valid) return;
  const btn = e.target.querySelector('.btn-submit');
  if (btn) { btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Sending…'; btn.disabled = true; }
  setTimeout(() => {
    const form = document.getElementById('contactForm');
    const success = document.getElementById('formSuccess');
    if (form) form.style.display = 'none';
    if (success) success.style.display = 'block';
  }, 1500);
}

/* ══════════════════════════════════════════════
   BRANDS PAGE — FILTER & SEARCH
   filterByCategory(cat, btn) → tab buttons call this
   filterBrands()             → search input oninput calls this
   Both work together: search respects active category tab
══════════════════════════════════════════════ */

/* Active category state — updated by tab clicks */
let _activeBrandCat = 'all';

/* Called by category tab buttons: filterByCategory('camera', this) */
function filterByCategory(cat, btn) {
  _activeBrandCat = cat;
  document.querySelectorAll('.bftab').forEach(b => b.classList.remove('active'));
  if (btn) btn.classList.add('active');
  /* Re-run combined filter */
  _applyBrandFilters();
  /* Scroll to grid */
  const brands = document.getElementById('allBrands');
  if (brands) brands.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

/* Called by search input oninput: filterBrands() — no args */
function filterBrands() {
  _applyBrandFilters();
}

/* Shared filter engine: applies both search text AND active category */
function _applyBrandFilters() {
  const searchEl = document.getElementById('brandSearchInput');
  const q = searchEl ? searchEl.value.toLowerCase().trim() : '';
  const cat = _activeBrandCat || 'all';
  const items = document.querySelectorAll('.brand-item');
  let visible = 0;

  items.forEach(item => {
    const itemCat  = item.dataset.category || '';
    const itemName = (item.dataset.name || '').toLowerCase();
    const cardName = (item.querySelector('.brand-card-name')?.textContent || '').toLowerCase();
    const cardMeta = (item.querySelector('.brand-card-meta')?.textContent || '').toLowerCase();

    const catMatch  = cat === 'all' || itemCat === cat;
    const textMatch = !q || itemName.includes(q) || cardName.includes(q) || cardMeta.includes(q);
    const show = catMatch && textMatch;

    item.style.display = show ? '' : 'none';
    if (show) visible++;
  });

  updateBrandCount(visible);
  const noRes = document.getElementById('noResults');
  if (noRes) noRes.style.display = visible === 0 ? 'block' : 'none';
}

function sortBrands(mode) {
  const grid = document.getElementById('brandGrid');
  if (!grid) return;
  const items = [...grid.querySelectorAll('.brand-item')];
  items.sort((a, b) => {
    if (mode === 'az') return a.dataset.name.localeCompare(b.dataset.name);
    if (mode === 'products') {
      const aCount = parseInt(a.querySelector('.brand-prod-count')?.textContent || '0');
      const bCount = parseInt(b.querySelector('.brand-prod-count')?.textContent || '0');
      return bCount - aCount;
    }
    return 0;
  });
  items.forEach(item => grid.appendChild(item));
}

function resetFilters() {
  const input = document.getElementById('brandSearchInput');
  if (input) input.value = '';
  _activeBrandCat = 'all';
  document.querySelectorAll('.brand-item').forEach(item => item.style.display = '');
  document.querySelectorAll('.bftab').forEach(b => b.classList.remove('active'));
  const first = document.querySelector('.bftab');
  if (first) first.classList.add('active');
  updateBrandCount(document.querySelectorAll('.brand-item').length);
  const noRes = document.getElementById('noResults');
  if (noRes) noRes.style.display = 'none';
}

function jumpToLetter(letter) {
  const target = document.getElementById('brand-' + letter);
  if (target) {
    target.scrollIntoView({ behavior: 'smooth', block: 'center' });
    const card = target.querySelector('.brand-card');
    if (card) {
      card.style.boxShadow = '0 0 0 3px rgba(204,0,0,0.3)';
      setTimeout(() => { card.style.boxShadow = ''; }, 1200);
    }
  }
}

function updateBrandCount(count) {
  const el = document.getElementById('brandCount');
  if (el) el.textContent = count + (count === 1 ? ' brand' : ' brands');
}

/* ══════════════════════════════════════════════════════════════
   PRODUCT LISTING PAGE
   (category-listing.html / product-listing.html)
══════════════════════════════════════════════════════════════ */

/* ── Sidebar mobile toggle ── */
function toggleSidebar() {
  const wrapper = document.getElementById('sidebarWrapper');
  const btn     = document.getElementById('sidebarToggleBtn');
  if (!wrapper) return;
  const isOpen = wrapper.classList.toggle('open');
  if (btn) btn.querySelector('i').className = isOpen ? 'fa fa-times me-2' : 'fa fa-sliders me-2';
}

/* ── Sidebar card accordion ── */
function toggleSidebarCard(id) {
  const card = document.getElementById(id);
  if (card) card.classList.toggle('collapsed');
}

/* ── Sidebar filter logic ──
   Uses data-filter / data-value on .filter-item elements.
   Wrapped in DOMContentLoaded so it only binds when the
   product-listing page is actually loaded.
── */
(function initListingFilters() {
  const activeFilters = {}; // { filterKey: Set<value> }

  function applyFilters() {
    const items = document.querySelectorAll('.prod-item-wrapper');
    let visibleCount = 0;
    items.forEach(item => {
      let match = true;
      for (const [key, values] of Object.entries(activeFilters)) {
        if (values.size === 0) continue;
        const itemVal = item.dataset[key] || '';
        if (!values.has(itemVal)) { match = false; break; }
      }
      item.style.display = match ? '' : 'none';
      if (match) visibleCount++;
    });
    const rc = document.getElementById('resultCount');
    if (rc) rc.innerHTML = `<strong>${visibleCount}</strong> product${visibleCount !== 1 ? 's' : ''} found`;
    const nr = document.getElementById('noResults');
    if (nr) nr.style.display = visibleCount === 0 ? 'block' : 'none';
    const cab = document.getElementById('clearAllBtn');
    if (cab) cab.style.display = Object.keys(activeFilters).length > 0 ? 'inline-flex' : 'none';
  }

  function renderFilterTags() {
    const container = document.getElementById('activeFilters');
    if (!container) return;
    container.innerHTML = '';
    for (const [key, values] of Object.entries(activeFilters)) {
      values.forEach(val => {
        const tag = document.createElement('span');
        tag.className = 'filter-tag';
        tag.innerHTML = `${val} <i class="fa fa-times"></i>`;
        tag.onclick = () => removeFilter(key, val);
        container.appendChild(tag);
      });
    }
  }

  function removeFilter(key, val) {
    if (activeFilters[key]) {
      activeFilters[key].delete(val);
      if (activeFilters[key].size === 0) delete activeFilters[key];
      document.querySelectorAll(`.filter-item[data-filter="${key}"][data-value="${val}"]`)
        .forEach(el => el.classList.remove('checked'));
    }
    applyFilters();
    renderFilterTags();
    updateFilterBadge();
  }

  function updateFilterBadge() {
    const total = Object.values(activeFilters).reduce((sum, s) => sum + s.size, 0);
    const badge = document.getElementById('filterBadge');
    if (badge) { badge.textContent = total; badge.style.display = total > 0 ? 'inline' : 'none'; }
  }

  /* Expose to global scope so inline onclick="" attributes can call them */
  window.removeFilter    = removeFilter;
  window.updateFilterBadge = updateFilterBadge;

  window.clearAllFilters = function () {
    Object.keys(activeFilters).forEach(k => delete activeFilters[k]);
    document.querySelectorAll('.filter-item.checked').forEach(el => el.classList.remove('checked'));
    document.querySelectorAll('.prod-item-wrapper').forEach(el => el.style.display = '');
    const af = document.getElementById('activeFilters');
    if (af) af.innerHTML = '';
    const rc = document.getElementById('resultCount');
    if (rc) rc.innerHTML = '<strong>12</strong> products found';
    const nr = document.getElementById('noResults');
    if (nr) nr.style.display = 'none';
    const cab = document.getElementById('clearAllBtn');
    if (cab) cab.style.display = 'none';
    updateFilterBadge();
  };

  /* Bind filter-item click listeners (only if items exist on this page) */
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.filter-item').forEach(item => {
      item.addEventListener('click', () => {
        const filterKey = item.dataset.filter;
        const filterVal = item.dataset.value;
        if (!filterKey || !filterVal) return;
        if (!activeFilters[filterKey]) activeFilters[filterKey] = new Set();
        if (item.classList.contains('checked')) {
          item.classList.remove('checked');
          activeFilters[filterKey].delete(filterVal);
          if (activeFilters[filterKey].size === 0) delete activeFilters[filterKey];
        } else {
          item.classList.add('checked');
          activeFilters[filterKey].add(filterVal);
        }
        applyFilters();
        renderFilterTags();
        updateFilterBadge();
      });
    });
  });
})();

/* ── Grid / List view toggle ── */
function setView(mode) {
  const grid    = document.getElementById('productGrid');
  const gridBtn = document.getElementById('gridBtn');
  const listBtn = document.getElementById('listBtn');
  if (!grid) return;

  if (mode === 'list') {
    grid.classList.add('list-view');
    if (listBtn) listBtn.classList.add('active');
    if (gridBtn) gridBtn.classList.remove('active');
    document.querySelectorAll('.prod-item-wrapper').forEach(el => {
      el.classList.remove('col-lg-4', 'col-md-6', 'col-6');
      el.classList.add('col-12');
    });
  } else {
    grid.classList.remove('list-view');
    if (gridBtn) gridBtn.classList.add('active');
    if (listBtn) listBtn.classList.remove('active');
    document.querySelectorAll('.prod-item-wrapper').forEach(el => {
      el.classList.remove('col-12');
      el.classList.add('col-lg-4', 'col-md-6', 'col-6');
    });
  }
}

/* ── Enquiry modal — product listing page variant ──
   Uses elements: #enquiryProductName, #enquiryProductCat, #enquiryProductImg
   (Different from the multi-step modal on index.html which uses #enqProdName)
── */
function openEnquiryPL(name, category, imgSrc) {
  const nameEl = document.getElementById('enquiryProductName');
  const catEl  = document.getElementById('enquiryProductCat');
  const imgEl  = document.getElementById('enquiryProductImg');
  if (nameEl) nameEl.textContent = name || 'General Enquiry';
  if (catEl)  catEl.textContent  = category
    ? category.charAt(0).toUpperCase() + category.slice(1)
    : 'Equipment Rental';
  if (imgEl) {
    if (imgSrc) { imgEl.src = imgSrc; imgEl.style.display = 'block'; }
    else          imgEl.style.display = 'none';
  }
  const m = _getModal('enquiryModal');
  if (m) m.show();
}

function submitEnquiryPL() {
  const btn = document.querySelector('#enquiryModal .btn-red');
  if (!btn) return;
  btn.innerHTML = '<i class="fa fa-check me-1"></i>Enquiry Sent!';
  btn.style.background   = '#1a7a4a';
  btn.style.borderColor  = '#1a7a4a';
  setTimeout(() => {
    const m = _getModal('enquiryModal');
    if (m) m.hide();
    btn.innerHTML          = '<i class="fa fa-paper-plane me-1"></i>Send Enquiry';
    btn.style.background   = '';
    btn.style.borderColor  = '';
  }, 1800);
}

/* ── Quick view modal — product listing page variant ──
   Uses elements: #qvTitle, #qvName, #qvCategory, #qvDesc, #qvImg, #qvSpecs, #qvRentBtn
   (Different from index.html which uses #qvModalTitle, #qvBrand, #qvFeatures)
── */
function openQuickViewPL(name, category, desc, imgSrc, specs) {
  const titleEl  = document.getElementById('qvTitle');
  const nameEl   = document.getElementById('qvName');
  const catEl    = document.getElementById('qvCategory');
  const descEl   = document.getElementById('qvDesc');
  const imgEl    = document.getElementById('qvImg');
  const specsEl  = document.getElementById('qvSpecs');
  const rentBtn  = document.getElementById('qvRentBtn');

  if (titleEl) titleEl.textContent = name;
  if (nameEl)  nameEl.textContent  = name;
  if (catEl)   catEl.textContent   = category.charAt(0).toUpperCase() + category.slice(1);
  if (descEl)  descEl.textContent  = desc;
  if (imgEl)   { imgEl.src = imgSrc; imgEl.alt = name; }
  if (specsEl) specsEl.innerHTML   = (specs || []).map(s =>
    `<span class="spec-pill"><i class="fa fa-check" style="color:var(--red);font-size:0.55rem;"></i> ${s}</span>`
  ).join('');
  if (rentBtn) rentBtn.onclick = () => {
    const qv = _getModal('quickViewModal');
    if (qv) qv.hide();
    setTimeout(() => openEnquiryPL(name, category, imgSrc), 300);
  };

  const m = _getModal('quickViewModal');
  if (m) m.show();
}

/* ── Sort products (client-side, by name) ── */
function sortProducts(val) {
  const grid = document.getElementById('productGrid');
  if (!grid) return;
  const items = [...grid.querySelectorAll('.prod-item-wrapper:not([style*="display: none"])')];
  items.sort((a, b) => {
    const na = a.querySelector('.prod-name')?.textContent || '';
    const nb = b.querySelector('.prod-name')?.textContent || '';
    if (val === 'name-az') return na.localeCompare(nb);
    if (val === 'name-za') return nb.localeCompare(na);
    return 0;
  });
  items.forEach(el => grid.appendChild(el));
}


/* ══════════════════════════════════════════════
     PAGE-SPECIFIC JAVASCRIPT
     Minimal — only accessories page logic
══════════════════════════════════════════════ */

  /* ─────────────────────────────────────────────
     CATEGORY FILTER
  ───────────────────────────────────────────── */
  // Count products per category on load
  function updateCounts() {
    const allItems = document.querySelectorAll('.product-item');
    const categories = ['all', 'camera', 'lens', 'lighting', 'audio', 'stabilizer', 'tripod'];
    categories.forEach(cat => {
      const el = document.getElementById('count-' + cat);
      if (!el) return;
      if (cat === 'all') {
        el.textContent = allItems.length;
      } else {
        el.textContent = document.querySelectorAll(`.product-item[data-category="${cat}"]`).length;
      }
    });
  }

  function filterProducts(btn, category) {
    // Update active tab
    document.querySelectorAll('.cat-tab').forEach(t => {
      t.classList.remove('active');
      t.setAttribute('aria-selected', 'false');
    });
    btn.classList.add('active');
    btn.setAttribute('aria-selected', 'true');

    const items = document.querySelectorAll('.product-item');
    let visible = 0;

    items.forEach(item => {
      const match = (category === 'all' || item.dataset.category === category);
      item.style.display = match ? '' : 'none';
      if (match) visible++;
    });

    // Update results count
    document.getElementById('visibleCount').textContent = visible;
    const label = document.getElementById('activeCategoryLabel');
    label.textContent = (category === 'all') ? '' : ' in ' + btn.querySelector('i + text, :last-child')?.textContent?.trim() || '';

    // Show/hide empty state
    document.getElementById('emptyState').style.display = (visible === 0) ? 'block' : 'none';
  }

  /* ─────────────────────────────────────────────
     SORT
  ───────────────────────────────────────────── */
  function sortProducts(val) {
    const grid = document.getElementById('productGrid');
    const items = Array.from(grid.querySelectorAll('.product-item'));

    if (val === 'name-az') {
      items.sort((a, b) => a.dataset.name.localeCompare(b.dataset.name));
    } else if (val === 'name-za') {
      items.sort((a, b) => b.dataset.name.localeCompare(a.dataset.name));
    } else {
      // default — restore DOM order by re-reading original index
      items.sort((a, b) => parseInt(a.dataset.index || 0) - parseInt(b.dataset.index || 0));
    }

    items.forEach(item => grid.appendChild(item));
  }

  // Store original DOM order for reset sort
  document.querySelectorAll('.product-item').forEach((item, idx) => {
    item.dataset.index = idx;
  });

  /* ─────────────────────────────────────────────
     HERO SEARCH
  ───────────────────────────────────────────── */
  function heroSearch() {
    const query = document.getElementById('heroSearchInput').value.trim().toLowerCase();
    if (!query) return;

    const items = document.querySelectorAll('.product-item');
    let visible = 0;

    // Reset filter bar active state
    document.querySelectorAll('.cat-tab').forEach(t => {
      t.classList.remove('active');
      t.setAttribute('aria-selected', 'false');
    });
    document.querySelector('.cat-tab[data-filter="all"]').classList.add('active');

    items.forEach(item => {
      const name = (item.dataset.name || '').toLowerCase();
      const brand = (item.querySelector('.acc-card-brand')?.textContent || '').toLowerCase();
      const desc  = (item.querySelector('.acc-card-desc')?.textContent || '').toLowerCase();
      const match = name.includes(query) || brand.includes(query) || desc.includes(query);
      item.style.display = match ? '' : 'none';
      if (match) visible++;
    });

    document.getElementById('visibleCount').textContent = visible;
    document.getElementById('emptyState').style.display = (visible === 0) ? 'block' : 'none';

    // Scroll to listing
    document.getElementById('accessoriesListing').scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  // Allow Enter key in hero search
  document.getElementById('heroSearchInput').addEventListener('keydown', function(e) {
    if (e.key === 'Enter') heroSearch();
  });

  /* ─────────────────────────────────────────────
     QUICK VIEW MODAL
  ───────────────────────────────────────────── */
  function openQuickView(name, brand, category, desc, img, features) {
    document.getElementById('qvModalTitle').textContent = name;
    document.getElementById('qvName').textContent = name;
    document.getElementById('qvBrand').textContent = brand;
    document.getElementById('qvDesc').textContent = desc;
    document.getElementById('qvImg').src = img;
    document.getElementById('qvImg').alt = name;

    const featList = document.getElementById('qvFeatures');
    featList.innerHTML = '';
    features.forEach(f => {
      const li = document.createElement('li');
      li.textContent = f;
      featList.appendChild(li);
    });

    // Wire up Rent Now button inside QV modal
    document.getElementById('qvRentBtn').onclick = function () {
      // Close QV, open enquiry
      bootstrap.Modal.getInstance(document.getElementById('quickViewModal'))?.hide();
      setTimeout(() => {
        openEnquiryForProduct(name, img, desc);
      }, 350);
    };

    new bootstrap.Modal(document.getElementById('quickViewModal')).show();
  }

  /* ─────────────────────────────────────────────
     OPEN ENQUIRY — pre-fill accessory
     Works alongside the shared openEnquiry() from scripts.js
  ───────────────────────────────────────────── */
  function openEnquiryForProduct(productName, productImg, productDesc) {
    // Fill left panel
    if (document.getElementById('enqProdImg'))  document.getElementById('enqProdImg').src = productImg;
    if (document.getElementById('enqProdName')) document.getElementById('enqProdName').textContent = productName;
    if (document.getElementById('enqProdDesc')) document.getElementById('enqProdDesc').textContent = productDesc || 'Submit your enquiry and our team will confirm availability within 2 hours.';

    // Show accessory label in Step 1
    const accLabel = document.getElementById('enqAccessoryLabel');
    if (accLabel) accLabel.textContent = productName;

    // Reset to Step 1
    if (typeof goToStep1 === 'function') goToStep1();

    new bootstrap.Modal(document.getElementById('enquiryModal')).show();
  }

  /* ─────────────────────────────────────────────
     INIT
  ───────────────────────────────────────────── */
  updateCounts();