/* ═══════════════════════════════════════════════
   main.js — Core Functionality
   ═══════════════════════════════════════════════ */

"use strict";

// ── Initialize AOS ──
AOS.init({
  duration: 700,
  easing: "ease-out-cubic",
  once: true,
  offset: 80,
});

// ── Scroll Progress Bar ──
(function initProgressBar() {
  const bar = document.createElement("div");
  bar.id = "progressBar";
  document.body.prepend(bar);

  window.addEventListener(
    "scroll",
    () => {
      const scrollTop = window.scrollY;
      const docHeight =
        document.documentElement.scrollHeight - window.innerHeight;
      const progress = docHeight > 0 ? (scrollTop / docHeight) * 100 : 0;
      bar.style.width = progress + "%";
    },
    { passive: true },
  );
})();

// ── Quote Form Handler ──
function handleQuote(e) {
  e.preventDefault();
  const form = e.target;
  const success = document.getElementById("formSuccess");

  form.style.opacity = "0";
  form.style.transform = "translateY(-10px)";

  setTimeout(() => {
    form.classList.add("d-none");
    success.classList.remove("d-none");
    success.style.animation = "fadeIn 0.5s ease forwards";
  }, 300);
}

// ── Smooth Scroll for anchor links ──
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener("click", function (e) {
    const target = document.querySelector(this.getAttribute("href"));
    if (!target) return;
    e.preventDefault();
    const offset = 80; // navbar height
    const top = target.getBoundingClientRect().top + window.scrollY - offset;
    window.scrollTo({ top, behavior: "smooth" });
  });
});

// ── Active nav link on scroll ──
(function initActiveNav() {
  const sections = document.querySelectorAll("section[id]");
  const navLinks = document.querySelectorAll('.pv-navbar .nav-link[href^="#"]');

  function updateActiveLink() {
    const scrollPos = window.scrollY + 120;
    sections.forEach((section) => {
      if (
        scrollPos >= section.offsetTop &&
        scrollPos < section.offsetTop + section.offsetHeight
      ) {
        navLinks.forEach((l) => l.classList.remove("active"));
        const activeLink = document.querySelector(
          `.pv-navbar .nav-link[href="#${section.id}"]`,
        );
        if (activeLink) activeLink.classList.add("active");
      }
    });
  }

  window.addEventListener("scroll", updateActiveLink, { passive: true });
  updateActiveLink();
})();

// ── Animate numbers on enter ──
(function initCountUp() {
  const nums = document.querySelectorAll(".pv-trust-num");
  const targets = { "1000+": 1000, "5★": 5, "10yr": 10 };

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const el = entry.target;
          el.style.animation = "slideInLeft 0.5s ease forwards";
          observer.unobserve(el);
        }
      });
    },
    { threshold: 0.5 },
  );

  nums.forEach((n) => observer.observe(n));
})();

// ── PV Gallery ──
//wrap in a function

function initPvGallery() {
  const pvGalleryItems = document.querySelectorAll(".pv-gallery-trigger");

  const pvBeforeImage = document.querySelector(".pv-before-image");

  const pvAfterImage = document.querySelector(".pv-after-image");

  const pvAfterLayer = document.querySelector(".pv-after-layer");

  const pvSliderHandle = document.querySelector(".pv-slider-handle");

  const pvNextSlide = document.querySelector(".pv-next-slide");

  const pvPrevSlide = document.querySelector(".pv-prev-slide");

  const pvCompareBox = document.querySelector(".pv-compare-box");

  let pvCurrentIndex = 0;

  let pvDragging = false;

  /* LOAD */

  function loadPvSlide(index) {
    const item = pvGalleryItems[index];

    const before = item.getAttribute("data-before");

    const after = item.getAttribute("data-after");

    pvBeforeImage.style.backgroundImage = `url(${before})`;

    pvAfterImage.style.backgroundImage = `url(${after})`;

    pvAfterLayer.style.clipPath = "inset(0 50% 0 0)";

    pvSliderHandle.style.left = "50%";
  }

  /* OPEN */

  pvGalleryItems.forEach((item, index) => {
    item.addEventListener("click", () => {
      pvCurrentIndex = index;

      loadPvSlide(index);
    });
  });

  /* NEXT */

  pvNextSlide.addEventListener("click", () => {
    pvCurrentIndex++;

    if (pvCurrentIndex >= pvGalleryItems.length) {
      pvCurrentIndex = 0;
    }

    loadPvSlide(pvCurrentIndex);
  });

  /* PREV */

  pvPrevSlide.addEventListener("click", () => {
    pvCurrentIndex--;

    if (pvCurrentIndex < 0) {
      pvCurrentIndex = pvGalleryItems.length - 1;
    }

    loadPvSlide(pvCurrentIndex);
  });

  /* SLIDER */

  function movePvSlider(clientX) {
    const rect = pvCompareBox.getBoundingClientRect();

    let percent = ((clientX - rect.left) / rect.width) * 100;

    percent = Math.max(0, Math.min(100, percent));

    pvAfterLayer.style.clipPath = `inset(0 ${100 - percent}% 0 0)`;

    pvSliderHandle.style.left = percent + "%";
  }

  function startPvDrag() {
    pvDragging = true;
  }

  function stopPvDrag() {
    pvDragging = false;
  }

  pvSliderHandle.addEventListener("mousedown", startPvDrag);

  window.addEventListener("mouseup", stopPvDrag);

  window.addEventListener("mousemove", (e) => {
    if (!pvDragging) return;

    movePvSlider(e.clientX);
  });

  /* TOUCH */

  pvSliderHandle.addEventListener("touchstart", startPvDrag, {
    passive: true,
  });

  window.addEventListener("touchend", stopPvDrag);

  window.addEventListener(
    "touchmove",
    (e) => {
      if (!pvDragging) return;

      movePvSlider(e.touches[0].clientX);
    },
    { passive: true },
  );
}

initPvGallery();
