// Carousel & Slider
const slides = document.querySelectorAll('.slide');
const imageSources = ['images/bg4.jpeg', 'images/bg3.jpeg', 'images/bg2.jpeg'];
let currentSlide = 0;

const thumbnailContainer = document.getElementById('thumbnailContainer');
const numberLine = document.getElementById('numberLine');

function updateThumbnails() {
  thumbnailContainer.innerHTML = '';
  for (let i = 0; i < slides.length; i++) {
    const thumb = document.createElement('div');
    thumb.classList.add('thumbnail');
    if (i === currentSlide) thumb.classList.add('active-thumb');
    thumb.style.backgroundImage = `url('${imageSources[i]}')`;
    thumb.onclick = () => {
      currentSlide = i;
      showSlide(currentSlide);
    };
    thumbnailContainer.appendChild(thumb);
  }
}

function updateNumberLine() {
  numberLine.innerHTML = '';
  for (let i = 0; i < slides.length; i++) {
    const circle = document.createElement('div');
    circle.className = 'number-circle';
    circle.textContent = i + 1;
    if (i === currentSlide) circle.classList.add('active');
    circle.onclick = () => {
      currentSlide = i;
      showSlide(currentSlide);
    };
    numberLine.appendChild(circle);

    if (i < slides.length - 1) {
      const line = document.createElement('div');
      line.className = 'progress-line';
      if (i === currentSlide) line.classList.add('active');
      numberLine.appendChild(line);
    }
  }
}

function showSlide(index) {
  slides.forEach((slide, i) => {
    slide.classList.toggle('active', i === index);
  });
  updateThumbnails();
  updateNumberLine();
}

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

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

// Initialize slider
showSlide(currentSlide);
setInterval(nextSlide, 8000);

// Date & Time
function updateDateTime() {
  const now = new Date();
  const formatted = now.toLocaleString('en-US', {
    weekday: 'short',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
  const dateTimeDisplay = document.getElementById('dateTimeDisplay');
  if (dateTimeDisplay) {
    dateTimeDisplay.textContent = formatted;
  }
}
setInterval(updateDateTime, 1000);
updateDateTime();

// Story progress bars
function animateProgressBars() {
  const bars = document.querySelectorAll('.progress-fill');

  bars.forEach(bar => {
    const target = +bar.getAttribute('data-target');
    let count = 0;

    const updateBar = () => {
      if (count <= target) {
        bar.style.width = count + '%';
        bar.textContent = count + '%';
        count++;
        requestAnimationFrame(updateBar);
      }
    };

    updateBar();
  });
}

let started = false;
window.addEventListener('scroll', () => {
  const section = document.querySelector('.our-story-section');
  if (!section) return;

  const sectionTop = section.getBoundingClientRect().top;
  const screenHeight = window.innerHeight;

  if (!started && sectionTop < screenHeight - 100) {
    animateProgressBars();
    started = true;
  }
});

// Facts counters
const counters = document.querySelectorAll('.counter');

counters.forEach(counter => {
  const target = +counter.getAttribute('data-target');
  let count = 0;

  const updateCount = () => {
    const increment = target / 100;
    if (count < target) {
      count += increment;
      counter.textContent = Math.floor(count);
      requestAnimationFrame(updateCount);
    } else {
      counter.textContent = target;
    }
  };

  updateCount();
});

// Works filtering
const tabs = document.querySelectorAll('.tab');
const cards = document.querySelectorAll('.product-card');
const showMoreBtn = document.getElementById('showMoreBtn');

let currentFilter = 'all';

function filterProducts(filter) {
  currentFilter = filter;
  let shown = 0;

  cards.forEach(card => {
    const match = filter === 'all' || card.dataset.category === filter;
    card.style.display = match ? 'block' : 'none';

    if (filter === 'all' && match) {
      card.classList.toggle('hidden-card', shown >= 8);
      shown++;
    } else {
      card.classList.remove('hidden-card');
    }
  });

  const hasMore = filter === 'all' && shown > 6;
  if (showMoreBtn) {
    showMoreBtn.style.display = hasMore ? 'block' : 'none';
  }
}

if (showMoreBtn) {
  showMoreBtn.addEventListener('click', () => {
    document.querySelectorAll('.product-card.hidden-card').forEach(card => {
      card.classList.remove('hidden-card');
    });
    showMoreBtn.style.display = 'none';
  });
}

tabs.forEach(tab => {
  tab.addEventListener('click', () => {
    tabs.forEach(t => t.classList.remove('active'));
    tab.classList.add('active');
    filterProducts(tab.dataset.filter);
  });
});

filterProducts('all');

// Social Swiper
const socialSwiper = new Swiper('.social-carousel', {
  slidesPerView: 5,
  spaceBetween: 20,
  loop: true,
  autoplay: {
    delay: 2000,
    disableOnInteraction: false,
  },
  breakpoints: {
    1024: {
      slidesPerView: 5,
    },
    768: {
      slidesPerView: 3,
    },
    480: {
      slidesPerView: 2,
    },
  }
});

const socialContainer = document.querySelector('.social-carousel');
if (socialContainer) {
  socialContainer.addEventListener('mouseenter', () => socialSwiper.autoplay.stop());
  socialContainer.addEventListener('mouseleave', () => socialSwiper.autoplay.start());
}

// Quotes Swiper
const quotesSwiper = new Swiper('.quotes-carousel', {
  slidesPerView: 1,
  loop: true,
  autoplay: {
    delay: 4000,
    disableOnInteraction: false,
  },
  effect: 'fade',
  fadeEffect: { crossFade: true },
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
  },
});

// Go to top button
const goTopBtn = document.getElementById("goTopBtn");

window.addEventListener("scroll", () => {
  const aboutSection = document.getElementById("about");
  if (!aboutSection || !goTopBtn) return;

  const aboutTop = aboutSection.getBoundingClientRect().top;

  if (aboutTop < window.innerHeight - 200) {
    goTopBtn.style.display = "block";
  } else {
    goTopBtn.style.display = "none";
  }
});

// Preloader
window.addEventListener("load", function () {
  const preloader = document.getElementById("preloader");
  if (!preloader) return;

  setTimeout(() => {
    preloader.style.opacity = "0";
    preloader.style.visibility = "hidden";
    setTimeout(() => preloader.remove(), 800);
  }, 500);
});

// Contact form AJAX
const contactForm = document.getElementById("contactForm");
if (contactForm) {
  contactForm.addEventListener("submit", function (e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch("contact.php", {
      method: "POST",
      body: formData
    })
      .then(response => response.text())
      .then(result => {
        if (result.trim() === "success") {
          const popup = document.getElementById("successPopup");
          if (popup) {
            popup.style.display = "block";

            setTimeout(() => {
              popup.style.display = "none";
              location.reload();
            }, 3000);
          }
        } else {
          alert("Error sending message. Please try again.");
        }
      })
      .catch(error => {
        alert("There was a problem: " + error.message);
      });
  });
}


