// Navbar Scroll
const navbar = document.getElementById("navbar");
if (navbar) {
  window.addEventListener("scroll", () => {
    if (window.scrollY > 50) navbar.classList.add("scrolled");
    else navbar.classList.remove("scrolled");
  });
}

// Hero Slider Draggable Logic
let currentSlide = 0;
const slides = document.querySelectorAll(".hero-slide");
const dots = document.querySelectorAll(".dot");
const track = document.getElementById("heroTrack");

let isDragging = false;
let startX = 0;
let currentTranslate = 0;
let prevTranslate = 0;
let animationID = 0;

function setSliderPosition() {
  if (track) {
    track.style.transform = `translateX(${currentTranslate}px)`;
  }
}

function updateSliderOnState() {
  if (!track) return;
  currentTranslate = currentSlide * -track.offsetWidth;
  prevTranslate = currentTranslate;
  setSliderPosition();
  dots.forEach((d, i) => d.classList.toggle("active", i === currentSlide));
}

function showSlide(n) {
  if (slides.length === 0) return;
  currentSlide = (n + slides.length) % slides.length;
  updateSliderOnState();
}

function nextSlide() { showSlide(currentSlide + 1); }
function prevSlide() { showSlide(currentSlide - 1); }
function goToSlide(n) { showSlide(n); }

// Desktop Drag
if (track) {
  track.addEventListener("mousedown", (e) => {
    isDragging = true;
    startX = e.pageX;
    track.style.transition = "none";
    animationID = requestAnimationFrame(animation);
  });

  window.addEventListener("mousemove", (e) => {
    if (!isDragging) return;
    const currentX = e.pageX;
    const diff = currentX - startX;
    currentTranslate = prevTranslate + diff;
  });

  window.addEventListener("mouseup", () => {
    if (!isDragging) return;
    isDragging = false;
    cancelAnimationFrame(animationID);
    const movedBy = currentTranslate - prevTranslate;
    track.style.transition = "transform 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94)";

    if (movedBy < -100) nextSlide();
    else if (movedBy > 100) prevSlide();
    else showSlide(currentSlide);
  });

  // Touch Support
  track.addEventListener("touchstart", (e) => {
    isDragging = true;
    startX = e.touches[0].clientX;
    track.style.transition = "none";
    animationID = requestAnimationFrame(animation);
  }, { passive: true });

  track.addEventListener("touchmove", (e) => {
    if (!isDragging) return;
    const currentX = e.touches[0].clientX;
    const diff = currentX - startX;
    currentTranslate = prevTranslate + diff;
  }, { passive: true });

  track.addEventListener("touchend", () => {
    if (!isDragging) return;
    isDragging = false;
    cancelAnimationFrame(animationID);
    const movedBy = currentTranslate - prevTranslate;
    track.style.transition = "transform 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94)";

    if (movedBy < -100) nextSlide();
    else if (movedBy > 100) prevSlide();
    else showSlide(currentSlide);
  });
}

function animation() {
  setSliderPosition();
  if (isDragging) requestAnimationFrame(animation);
}

// Auto Slide
let autoSlideInterval = setInterval(nextSlide, 5000);
if (track) {
  track.addEventListener("mouseenter", () => clearInterval(autoSlideInterval));
  track.addEventListener("mouseleave", () => autoSlideInterval = setInterval(nextSlide, 5000));
}

let currentProductScroll = 0;

function filterCategory(category, element) {
  // Update active tab
  document
    .querySelectorAll(".category-item")
    .forEach((item) => item.classList.remove("active"));
  if (element) element.classList.add("active");

  // Filter products
  const cards = document.querySelectorAll(".bike-card-clean");
  cards.forEach((card) => {
    if (category === "all" || card.dataset.category === category) {
      card.style.display = "block";
    } else {
      card.style.display = "none";
    }
  });

  // Reset slider position
  currentProductScroll = 0;
  updateSliderPosition();
}

function moveSlider(direction) {
  const track = document.getElementById("bikeGridContainer");
  const container = track.parentElement;
  const cards = Array.from(
    document.querySelectorAll(".bike-card-clean"),
  ).filter((c) => c.style.display !== "none");
  if (cards.length === 0) return;

  // Calculate visible cards based on CSS flex-basis
  const cardWidthWithGap =
    cards[0].offsetWidth + parseInt(window.getComputedStyle(track).gap || 0);
  const visibleCards =
    Math.round(container.offsetWidth / cardWidthWithGap) || 1;

  // Max scroll index is based on visible groups
  const maxScroll = Math.max(0, cards.length - visibleCards);

  // Slide by visible group (or 1 on mobile)
  currentProductScroll += direction * visibleCards;

  // Bounds check
  if (currentProductScroll < 0) currentProductScroll = 0;
  if (currentProductScroll > maxScroll) currentProductScroll = maxScroll;

  updateSliderPosition();
}

function updateSliderPosition() {
  const track = document.getElementById("bikeGridContainer");
  const cards = Array.from(
    document.querySelectorAll(".bike-card-clean"),
  ).filter((c) => c.style.display !== "none");
  if (cards.length === 0) return;

  const cardWidthWithGap =
    cards[0].offsetWidth + parseInt(window.getComputedStyle(track).gap || 0);
  track.style.transform = `translateX(-${currentProductScroll * cardWidthWithGap}px)`;

  // Update Nav Buttons visibility
  const container = track.parentElement;
  const visibleCards =
    Math.round(container.offsetWidth / cardWidthWithGap) || 1;
  const prevBtn = document.querySelector(".product-nav.prev");
  const nextBtn = document.querySelector(".product-nav.next");

  if (prevBtn) prevBtn.style.opacity = currentProductScroll === 0 ? "0.3" : "1";
  if (nextBtn)
    nextBtn.style.opacity =
      currentProductScroll >= cards.length - visibleCards ? "0.3" : "1";
}

// Draggable Product Slider (Home)
const productTrack = document.getElementById("homeProductGrid");
if (productTrack) {
  let isDrag = false;
  let sX = 0;
  let sScroll = 0;
  let trackWidth = productTrack.offsetWidth;

  const startDrag = (e) => {
    isDrag = true;
    sX = e.pageX || e.touches[0].pageX;
    sScroll = currentHomeProductScroll;
    productTrack.style.transition = "none";
    trackWidth = productTrack.offsetWidth;
  };

  const moveDrag = (e) => {
    if (!isDrag) return;
    const x = e.pageX || e.touches[0].pageX;
    const walk = (sX - x);
    
    // Convert pixel drag to index offset
    const cards = Array.from(productTrack.querySelectorAll(".home-catalogue-card")).filter(c => c.style.display !== 'none');
    if (cards.length === 0) return;
    const cardWidth = cards[0].offsetWidth;
    const gap = parseInt(window.getComputedStyle(productTrack).gap || 0);
    const step = cardWidth + gap;
    
    const indexOffset = walk / step;
    currentHomeProductScroll = sScroll + indexOffset;
    
    // Bounds check during drag (with some resistance)
    const container = productTrack.parentElement;
    const visibleItems = Math.round(container.offsetWidth / step) || 1;
    const maxScroll = Math.max(0, cards.length - visibleItems);
    
    if (currentHomeProductScroll < -0.5) currentHomeProductScroll = -0.5;
    if (currentHomeProductScroll > maxScroll + 0.5) currentHomeProductScroll = maxScroll + 0.5;

    updateHomeSliderPosition();
  };

  const endDrag = () => {
    if (!isDrag) return;
    isDrag = false;
    productTrack.style.transition = "transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1)";
    
    // Snap to nearest item
    currentHomeProductScroll = Math.round(currentHomeProductScroll);
    
    // Final bounds check
    const cards = Array.from(productTrack.querySelectorAll(".home-catalogue-card")).filter(c => c.style.display !== 'none');
    const container = productTrack.parentElement;
    const cardWidth = cards[0].offsetWidth;
    const gap = parseInt(window.getComputedStyle(productTrack).gap || 0);
    const visibleItems = Math.round(container.offsetWidth / (cardWidth + gap)) || 1;
    const maxScroll = Math.max(0, cards.length - visibleItems);

    if (currentHomeProductScroll < 0) currentHomeProductScroll = 0;
    if (currentHomeProductScroll > maxScroll) currentHomeProductScroll = maxScroll;
    
    updateHomeSliderPosition();
  };

  productTrack.addEventListener("mousedown", startDrag);
  window.addEventListener("mousemove", (e) => { if(isDrag) moveDrag(e); });
  window.addEventListener("mouseup", endDrag);

  productTrack.addEventListener("touchstart", startDrag, { passive: true });
  productTrack.addEventListener("touchmove", (e) => { if(isDrag) moveDrag(e); }, { passive: true });
  productTrack.addEventListener("touchend", endDrag);
}

// Reset on resize to ensure alignment stays correct
window.addEventListener("resize", () => {
  currentProductScroll = 0;
  currentHomeProductScroll = 0;
  updateSliderPosition();
  updateHomeSliderPosition();
  updateSliderOnState(); // Hero Slider update
});

// Calculator Logic
let term = 48;

function selectBikeForCalc(price, modelName) {
  document.getElementById("inputPrice").value = price;
  const select = document.getElementById("bikeSelect");
  let found = false;
  for (let i = 0; i < select.options.length; i++) {
    if (parseInt(select.options[i].value) === price) {
      select.selectedIndex = i;
      found = true;
      break;
    }
  }
  if (!found) select.value = 0;
  updateDownFromPercent();
  document.getElementById("calculator").scrollIntoView({ behavior: "smooth" });
}

function updatePriceFromSelect() {
  const price = document.getElementById("bikeSelect").value;
  if (price > 0) {
    document.getElementById("inputPrice").value = price;
    updateDownFromPercent();
  }
}

function updateDownFromPercent() {
  const price = parseInt(document.getElementById("inputPrice").value) || 0;
  const percent = parseInt(document.getElementById("downPercentSelect").value);
  const amount = price * (percent / 100);
  document.getElementById("inputDownAmount").value = amount;
  calculateLoan();
}

function updateDownFromAmount() {
  calculateLoan();
}

function setTerm(btn, months) {
  term = months;
  document
    .querySelectorAll(".term-btn")
    .forEach((b) => b.classList.remove("active"));
  btn.classList.add("active");
  calculateLoan();
}

function calculateLoan() {
  const price = parseInt(document.getElementById("inputPrice").value) || 0;
  const downAmount =
    parseInt(document.getElementById("inputDownAmount").value) || 0;
  const yearlyRate =
    parseFloat(document.getElementById("inputInterest").value) || 0;

  const downAmountDisplay = document.getElementById("downAmountDisplay");
  if (downAmountDisplay)
    downAmountDisplay.innerText = downAmount.toLocaleString() + " บาท";

  if (price > 0) {
    const finance = price - downAmount;
    const totalInterest = finance * (yearlyRate / 100) * (term / 12);
    const total = finance + totalInterest;
    const monthly = Math.ceil(total / term);

    const loanAmountDisplay = document.getElementById("loanAmountDisplay");
    const monthlyPayment = document.getElementById("monthlyPayment");

    if (loanAmountDisplay)
      loanAmountDisplay.innerText = finance.toLocaleString() + " บาท";
    if (monthlyPayment) monthlyPayment.innerText = monthly.toLocaleString();
  }
}
updateDownFromPercent();

// Mobile Promotions Auto-Scroll
function initPromoAutoScroll() {
  const promoContainer = document.querySelector(".promo-masonry");
  if (!promoContainer) return;

  setInterval(() => {
    if (window.innerWidth <= 576) {
      const scrollWidth = promoContainer.offsetWidth;
      const maxScroll = promoContainer.scrollWidth - scrollWidth;

      if (promoContainer.scrollLeft >= maxScroll - 10) {
        promoContainer.scrollTo({ left: 0, behavior: "smooth" });
      } else {
        promoContainer.scrollBy({ left: scrollWidth, behavior: "smooth" });
      }
    }
  }, 10000);
}

let currentHomeProductScroll = 0;

function moveHomeSlider(direction) {
  const track = document.getElementById("homeProductGrid");
  if (!track) return;
  const container = track.parentElement;
  const cards = Array.from(
    track.querySelectorAll(".home-catalogue-card"),
  ).filter((c) => c.style.display !== "none");
  if (cards.length === 0) return;

  // Calculate visible items based on width
  const containerWidth = container.offsetWidth;
  const cardWidth = cards[0].offsetWidth;
  const gap = parseInt(window.getComputedStyle(track).gap || 0);
  const visibleItems = Math.round(containerWidth / (cardWidth + gap)) || 1;

  // Max scroll index
  const maxScroll = Math.max(0, cards.length - visibleItems);

  currentHomeProductScroll += direction;

  if (currentHomeProductScroll < 0) currentHomeProductScroll = 0;
  if (currentHomeProductScroll > maxScroll)
    currentHomeProductScroll = maxScroll;

  updateHomeSliderPosition();
}

function updateHomeSliderPosition() {
  const track = document.getElementById("homeProductGrid");
  if (!track) return;
  const cards = Array.from(
    track.querySelectorAll(".home-catalogue-card"),
  ).filter((c) => c.style.display !== "none");
  if (cards.length === 0) return;

  const cardWidth = cards[0].offsetWidth;
  const gap = parseInt(window.getComputedStyle(track).gap || 0);
  const offset = currentHomeProductScroll * (cardWidth + gap);

  track.style.transform = `translateX(-${offset}px)`;

  // Update Nav Buttons visibility
  const container = track.parentElement.parentElement; // .home-slider-container
  const prevBtn = container.querySelector(".home-slider-nav.prev");
  const nextBtn = container.querySelector(".home-slider-nav.next");

  const containerWidth = track.parentElement.offsetWidth;
  const visibleItems = Math.round(containerWidth / (cardWidth + gap)) || 1;

  if (prevBtn)
    prevBtn.style.opacity = currentHomeProductScroll === 0 ? "0.3" : "1";
  if (nextBtn)
    nextBtn.style.opacity =
      currentHomeProductScroll >= cards.length - visibleItems ? "0.3" : "1";
}

// Reset home slider on resize
window.addEventListener("resize", () => {
  // Also handle previous slider if exists
  if (document.getElementById("bikeGridContainer")) {
    currentProductScroll = 0;
    updateSliderPosition();
  }

  currentHomeProductScroll = 0;
  updateHomeSliderPosition();
});




window.addEventListener("load", () => {
  if (typeof updateSliderPosition === "function") updateSliderPosition();
  if (typeof updateHomeSliderPosition === "function") updateHomeSliderPosition();
  if (typeof initPromoAutoScroll === "function") initPromoAutoScroll();
});

function closeWelcomePopup() {
  const popup = document.getElementById("welcomePopup");
  if (popup) {
    popup.classList.remove("active");
    document.body.style.overflow = "";
  }
}
