
document.addEventListener("DOMContentLoaded", () => {
  const toggle = document.getElementById("menuToggle");
  const menu = document.getElementById("mainMenu");
  if(toggle && menu){ toggle.addEventListener("click", () => menu.classList.toggle("open")); }

  const carousel = document.querySelector("[data-carousel3d]");
  if(carousel){
    const slides = Array.from(carousel.querySelectorAll(".slide3d"));
    const dotsWrap = carousel.querySelector("[data-dots]");
    let active = 0, timer;
    function state(i){
      const n = slides.length, d = (i - active + n) % n;
      if(d === 0) return "active";
      if(d === 1) return "next";
      if(d === 2) return "farnext";
      if(d === n-1) return "prev";
      if(d === n-2) return "farprev";
      return "";
    }
    function render(){
      slides.forEach((s,i)=>{ s.className = "slide3d " + state(i); });
      if(dotsWrap){ Array.from(dotsWrap.children).forEach((d,i)=>d.classList.toggle("active", i===active)); }
    }
    function go(i){ active = (i + slides.length) % slides.length; render(); }
    if(dotsWrap){
      slides.forEach((_,i)=>{
        const b = document.createElement("button");
        b.className = "dot3d" + (i===0 ? " active" : "");
        b.type = "button";
        b.addEventListener("click", ()=>{ go(i); restart(); });
        dotsWrap.appendChild(b);
      });
    }
    carousel.querySelector("[data-prev]")?.addEventListener("click",()=>{ go(active-1); restart(); });
    carousel.querySelector("[data-next]")?.addEventListener("click",()=>{ go(active+1); restart(); });
    function restart(){ clearInterval(timer); timer = setInterval(()=>go(active+1), 3400); }
    render(); restart();
  }

  document.querySelectorAll("[data-gallery]").forEach(gallery => {
    const main = gallery.querySelector("[data-main-image]");
    gallery.querySelectorAll("[data-thumb]").forEach(btn => {
      btn.addEventListener("click", () => {
        if(main){ main.src = btn.dataset.src; main.alt = btn.dataset.alt || main.alt; }
        gallery.querySelectorAll("[data-thumb]").forEach(x => x.classList.remove("active"));
        btn.classList.add("active");
      });
    });
  });

  const filterBtns = document.querySelectorAll("[data-filter]");
  const cards = document.querySelectorAll("[data-product-card]");
  if(filterBtns.length && cards.length){
    filterBtns.forEach(btn => {
      btn.addEventListener("click", () => {
        const target = btn.dataset.filter;
        filterBtns.forEach(b => b.classList.remove("active"));
        btn.classList.add("active");
        cards.forEach(card => { card.style.display = (target === "all" || card.dataset.category === target) ? "" : "none"; });
      });
    });
  }
});
