// Toggle menú hamburguesa (móvil)
const navToggle = document.getElementById("navToggle");
const nav = document.querySelector(".nav");

if (navToggle) {
  navToggle.addEventListener("click", () => {
    nav.classList.toggle("open");
  });
}

// Mega menú "Autos nuevos"
const btnAutosNuevos = document.getElementById("btnAutosNuevos");
const megaMenuAutos = document.getElementById("megaMenuAutos");

if (btnAutosNuevos && megaMenuAutos) {
  btnAutosNuevos.addEventListener("click", (e) => {
    e.stopPropagation();
    megaMenuAutos.classList.toggle("open");
  });

  // Cerrar mega menú al hacer clic fuera
  document.addEventListener("click", (e) => {
    const isClickInside =
      megaMenuAutos.contains(e.target) || btnAutosNuevos.contains(e.target);
    if (!isClickInside) {
      megaMenuAutos.classList.remove("open");
    }
  });
}

/* ===========================
   SLIDER INFERIOR
   =========================== */
const slides = document.querySelectorAll(".slide");
const prevBtn = document.getElementById("prevSlide");
const nextBtn = document.getElementById("nextSlide");
const dotsContainer = document.getElementById("sliderDots");

let currentIndex = 0;
let autoPlayInterval;

// Crear puntos
slides.forEach((_, index) => {
  const dot = document.createElement("button");
  dot.classList.add("slider-dot");
  dot.dataset.index = index;
  dotsContainer.appendChild(dot);
});

const dots = dotsContainer.querySelectorAll(".slider-dot");

function updateSlider(index) {
  slides.forEach((slide) => slide.classList.remove("active"));
  dots.forEach((dot) => dot.classList.remove("active"));

  slides[index].classList.add("active");
  dots[index].classList.add("active");
  currentIndex = index;
}

function nextSlide() {
  const newIndex = (currentIndex + 1) % slides.length;
  updateSlider(newIndex);
}

function prevSlideFn() {
  const newIndex = (currentIndex - 1 + slides.length) % slides.length;
  updateSlider(newIndex);
}

// Eventos de flechas
if (nextBtn) nextBtn.addEventListener("click", nextSlide);
if (prevBtn) prevBtn.addEventListener("click", prevSlideFn);

// Eventos de puntos
dots.forEach((dot) =>
  dot.addEventListener("click", () => {
    const index = parseInt(dot.dataset.index, 10);
    updateSlider(index);
  })
);

// Auto play
function startAutoPlay() {
  autoPlayInterval = setInterval(nextSlide, 6000);
}

function stopAutoPlay() {
  clearInterval(autoPlayInterval);
}

const sliderWrapper = document.querySelector(".slider-wrapper");
if (sliderWrapper) {
  sliderWrapper.addEventListener("mouseenter", stopAutoPlay);
  sliderWrapper.addEventListener("mouseleave", startAutoPlay);
}

// Inicializar
if (slides.length > 0) {
  updateSlider(0);
  startAutoPlay();
}
