// AOS Initialization
AOS.init({
  duration: 1200,
});

// Transformation home js
const DGTransformationController = (function () {
  const elements = {
    slider: document.getElementById("dg-reveal-slider"),
    beforeClip: document.getElementById("dg-before-clip"),
    sliderLine: document.getElementById("dg-slider-line"),
    container: document.getElementById("dg-reveal-container"),
    panels: document.querySelectorAll(
      ".dg-transformation-section .glass-panel:not(.pointer-events-none)",
    ),
  };

  const initTransformation = () => {
    if (
      !elements.slider ||
      !elements.beforeClip ||
      !elements.sliderLine ||
      !elements.container
    )
      return;

    const beforeImage = elements.beforeClip.querySelector("img");

    const updateReveal = (value) => {
      const percentage = parseFloat(value);
      elements.beforeClip.style.width = `${percentage}%`;
      elements.sliderLine.style.left = `${percentage}%`;

      if (beforeImage) {
        const parentWidth = elements.container.offsetWidth;
        beforeImage.style.width = `${parentWidth}px`;
      }
    };

    elements.slider.addEventListener("input", (e) => {
      requestAnimationFrame(() => updateReveal(e.target.value));
    });

    // Initial run
    updateReveal(elements.slider.value);

    // Handle resizing for relative positioning
    window.addEventListener("resize", () => {
      requestAnimationFrame(() => updateReveal(elements.slider.value));
    });
  };

  const initParallax = () => {
    if (window.innerWidth < 768) return;

    window.addEventListener("mousemove", (e) => {
      const mouseX = e.clientX / window.innerWidth;
      const mouseY = e.clientY / window.innerHeight;

      elements.panels.forEach((panel) => {
        const rect = panel.getBoundingClientRect();
        if (rect.top < window.innerHeight && rect.bottom > 0) {
          const xOffset = (mouseX - 0.5) * 8;
          const yOffset = (mouseY - 0.5) * 8;
          panel.style.transform = `translate3d(${xOffset}px, ${yOffset}px, 0)`;
        }
      });
    });
  };

  return {
    init: function () {
      initTransformation();
      initParallax();
    },
  };
})();

// Bootstrap on DOM Ready
document.addEventListener("DOMContentLoaded", () => {
  DGTransformationController.init();
});

// Hero js
function initHeroSlider() {
  const slides = document.querySelectorAll(".hero-slider-item");
  const indicatorItems = document.querySelectorAll(
    ".hero-slider-indicator-item",
  );
  const nextBtn = document.getElementById("hero-slider-next");
  const prevBtn = document.getElementById("hero-slider-prev");

  if (!slides.length || !nextBtn || !prevBtn) return;

  let currentSlide = 0;
  const totalSlides = slides.length;
  let autoSlideInterval;

  function updateSlider(index) {
    slides.forEach((slide, i) => {
      if (i === index) {
        slide.style.opacity = "1";
        slide.style.zIndex = "10";
        slide.style.transform = "translateX(0)";
      } else {
        slide.style.opacity = "0";
        slide.style.zIndex = "0";
        slide.style.transform =
          i < index ? "translateX(-20px)" : "translateX(20px)";
      }
    });

    indicatorItems.forEach((indicator, i) => {
      const text = indicator.querySelector("span");
      const bar = indicator.querySelector(".hero-slider-progress-bar");

      if (i === index) {
        indicator.classList.remove("opacity-40");
        text.classList.add("text-lg");
        text.classList.remove("text-sm");
        if (bar) {
          bar.classList.add("h-12", "bg-primary");
          bar.classList.remove("h-8", "bg-white");
        }
      } else {
        indicator.classList.add("opacity-40");
        text.classList.remove("text-lg");
        text.classList.add("text-sm");
        if (bar) {
          bar.classList.remove("h-12", "bg-primary");
          bar.classList.add("h-8", "bg-white");
        }
      }
    });
    currentSlide = index;
  }

  function nextSlide() {
    let next = (currentSlide + 1) % totalSlides;
    updateSlider(next);
  }

  function prevSlide() {
    let prev = (currentSlide - 1 + totalSlides) % totalSlides;
    updateSlider(prev);
  }

  nextBtn.addEventListener("click", () => {
    nextSlide();
    resetAutoSlide();
  });

  prevBtn.addEventListener("click", () => {
    prevSlide();
    resetAutoSlide();
  });

  function startAutoSlide() {
    autoSlideInterval = setInterval(nextSlide, 8000);
  }

  function resetAutoSlide() {
    clearInterval(autoSlideInterval);
    startAutoSlide();
  }

  updateSlider(0);
  startAutoSlide();
}

document.addEventListener("DOMContentLoaded", () => {
  initHeroSlider();
});

// Services
function slide(direction) {
  const slider = document.getElementById("serviceSlider");
  const card = slider.querySelector(".prism-card");
  if (!card) return;

  // Single card increment logic: card width + the 16px gap
  const scrollAmount = card.offsetWidth + 16;

  if (direction === "left") {
    slider.scrollBy({ left: -scrollAmount, behavior: "smooth" });
  } else {
    slider.scrollBy({ left: scrollAmount, behavior: "smooth" });
  }
}

// Testimonaisl js
(function () {
  /**
   * Lumina Floating Shards Slider Module
   * Encapsulated to prevent global namespace pollution.
   */
  const initializeFloatingShards = () => {
    const sliderRoot = document.querySelector(".dg-floating-shards-slider");
    if (!sliderRoot) return;

    // Slider Logic Scope
    const setupSlider = () => {
      const trackElement = document.getElementById("sliderTrack");
      const prevButton = document.getElementById("prevBtn");
      const nextButton = document.getElementById("nextBtn");
      const dotsContainer = document.getElementById("paginationDots");

      if (!trackElement || !prevButton || !nextButton || !dotsContainer) return;

      const sliderItems = trackElement.children;
      let currentSliderIndex = 0;
      let visibleItemCount = 1;

      const calculateVisibleCount = () => {
        if (window.innerWidth >= 1024) visibleItemCount = 4;
        else if (window.innerWidth >= 768) visibleItemCount = 2;
        else visibleItemCount = 1;
      };

      const renderPaginationDots = () => {
        dotsContainer.innerHTML = "";
        const totalDotPages = sliderItems.length - visibleItemCount + 1;
        for (let i = 0; i < totalDotPages; i++) {
          const dotElement = document.createElement("div");
          dotElement.className = `dot ${i === currentSliderIndex ? "active" : ""}`;
          dotElement.onclick = () => scrollToSlide(i);
          dotsContainer.appendChild(dotElement);
        }
      };

      const scrollToSlide = (targetIndex) => {
        const maxPossibleIndex = sliderItems.length - visibleItemCount;
        currentSliderIndex = Math.max(
          0,
          Math.min(targetIndex, maxPossibleIndex),
        );

        const singleItemWidth = sliderItems[0].offsetWidth + 24; // Width + gap
        trackElement.style.transform = `translateX(-${currentSliderIndex * singleItemWidth}px)`;
        renderPaginationDots();
      };

      prevButton.onclick = () => scrollToSlide(currentSliderIndex - 1);
      nextButton.onclick = () => scrollToSlide(currentSliderIndex + 1);

      window.addEventListener("resize", () => {
        calculateVisibleCount();
        scrollToSlide(currentSliderIndex);
      });

      calculateVisibleCount();
      renderPaginationDots();
    };

    // Background Bubbles Animation Scope
    const setupAmbientBubbles = () => {
      const bubbleRootContainer = document.getElementById("bubble-container");
      if (!bubbleRootContainer) return;

      const totalBubbleCount = 20;
      const activeBubblesList = [];

      for (let i = 0; i < totalBubbleCount; i++) {
        const bubbleEl = document.createElement("div");
        bubbleEl.className = "bubble";
        const randomSize = Math.random() * 60 + 20;
        bubbleEl.style.width = `${randomSize}px`;
        bubbleEl.style.height = `${randomSize}px`;

        bubbleRootContainer.appendChild(bubbleEl);
        activeBubblesList.push({
          el: bubbleEl,
          posX: Math.random() * window.innerWidth,
          posY: Math.random() * 700,
          velX: (Math.random() - 0.5) * 0.8,
          velY: (Math.random() - 0.5) * 0.8,
        });
      }

      const updateBubblePositions = () => {
        activeBubblesList.forEach((bubble) => {
          bubble.posX += bubble.velX;
          bubble.posY += bubble.velY;

          if (bubble.posX < -100) bubble.posX = window.innerWidth + 100;
          if (bubble.posX > window.innerWidth + 100) bubble.posX = -100;
          if (bubble.posY < -100) bubble.posY = 800;
          if (bubble.posY > 800) bubble.posY = -100;

          bubble.el.style.transform = `translate(${bubble.posX}px, ${bubble.posY}px)`;
        });
        requestAnimationFrame(updateBubblePositions);
      };
      updateBubblePositions();
    };

    setupSlider();
    setupAmbientBubbles();
  };

  // Run initialization on DOM load
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initializeFloatingShards);
  } else {
    initializeFloatingShards();
  }
})();

// navbar js
document.addEventListener("DOMContentLoaded", () => {
  // Desktop Elements
  const servicesTrigger = document.getElementById("dg-nav-services-trigger");
  const megaMenu = document.getElementById("dg-nav-mega-dropdown");
  const expandIcon = document.getElementById("dg-nav-expand-icon");

  // Mobile Elements
  const mobileToggle = document.getElementById("dg-nav-mobile-toggle");
  const mobileClose = document.getElementById("dg-nav-mobile-close");
  const mobileDrawer = document.getElementById("dg-nav-drawer");
  const overlay = document.getElementById("dg-nav-overlay");
  const mobileAccordionBtn = document.getElementById(
    "dg-nav-mobile-accordion-btn",
  );
  const mobileAccordion = document.getElementById("dg-nav-mobile-accordion");
  const mobileExpandIcon = document.getElementById("dg-nav-mobile-expand-icon");

  /**
   * State Handlers
   */
  const setMegaMenuState = (isActive) => {
    if (megaMenu) {
      megaMenu.classList.toggle("is-active", isActive);
    }
    if (expandIcon) {
      expandIcon.style.transform = isActive ? "rotate(180deg)" : "rotate(0deg)";
    }
    document.body.style.overflow = isActive ? "hidden" : "";
  };

  const setMobileDrawerState = (isActive) => {
    if (mobileDrawer) mobileDrawer.classList.toggle("is-active", isActive);
    if (overlay) overlay.classList.toggle("is-active", isActive);
    document.body.style.overflow = isActive ? "hidden" : "";
  };

  /**
   * Desktop Listeners
   */
  if (servicesTrigger && megaMenu) {
    const handleEnter = () => setMegaMenuState(true);
    const handleLeave = (e) => {
      const target = e.relatedTarget;
      if (!megaMenu.contains(target) && !servicesTrigger.contains(target)) {
        setMegaMenuState(false);
      }
    };

    servicesTrigger.addEventListener("mouseenter", handleEnter);
    servicesTrigger.addEventListener("mouseleave", handleLeave);
    megaMenu.addEventListener("mouseenter", handleEnter);
    megaMenu.addEventListener("mouseleave", handleLeave);
  }

  /**
   * Mobile Listeners
   */
  if (mobileToggle)
    mobileToggle.addEventListener("click", () => setMobileDrawerState(true));
  if (mobileClose)
    mobileClose.addEventListener("click", () => setMobileDrawerState(false));
  if (overlay)
    overlay.addEventListener("click", () => setMobileDrawerState(false));

  if (mobileAccordionBtn && mobileAccordion) {
    mobileAccordionBtn.addEventListener("click", () => {
      const isOpen = mobileAccordion.classList.toggle("is-open");
      if (mobileExpandIcon) {
        mobileExpandIcon.style.transform = isOpen
          ? "rotate(180deg)"
          : "rotate(0deg)";
      }
      mobileAccordionBtn.classList.toggle("text-primary", isOpen);
    });
  }

  /**
   * Utilities
   */
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      setMegaMenuState(false);
      setMobileDrawerState(false);
    }
  });

  window.addEventListener("resize", () => {
    if (window.innerWidth >= 1024) {
      setMobileDrawerState(false);
    } else {
      setMegaMenuState(false);
    }
  });
});

// FAQ
function initDGFaqSystem() {
  const faqItems = document.querySelectorAll(".dg-faq-item");
  const heroImage = document.querySelector(".dg-faq-hero-img");

  // Sequential reveal for FAQ items
  faqItems.forEach((item, index) => {
    item.style.opacity = "0";
    item.style.transform = "translateY(20px)";
    setTimeout(
      () => {
        item.style.transition = "all 0.6s cubic-bezier(0.23, 1, 0.32, 1)";
        item.style.opacity = "1";
        item.style.transform = "translateY(0)";
      },
      200 + index * 100,
    );

    // Interaction Logic
    const trigger = item.querySelector(".dg-faq-trigger");
    const icon = item.querySelector(".dg-faq-icon");

    if (trigger) {
      trigger.addEventListener("click", () => {
        const isActive = item.classList.contains("dg-faq-item-active");

        // Optional: Close others
        // faqItems.forEach(i => i.classList.remove('dg-faq-item-active'));

        if (isActive) {
          item.classList.remove("dg-faq-item-active");
          if (icon) icon.classList.remove("rotate-45");
        } else {
          item.classList.add("dg-faq-item-active");
          if (icon) icon.classList.add("rotate-45");
        }
      });
    }
  });

  // Parallax Interaction for cinematic hero
  if (heroImage) {
    window.addEventListener("mousemove", (e) => {
      const x = (window.innerWidth / 2 - e.pageX) / 45;
      const y = (window.innerHeight / 2 - e.pageY) / 45;
      heroImage.style.transform = `scale(1.1) translate(${x}px, ${y}px)`;
    });
  }
}

// Boot system on DOM load
document.addEventListener("DOMContentLoaded", initDGFaqSystem);

// Form Signature JS
(function () {
  // Form Submission
  const form = document.getElementById("dg-dental-history-form");
  form.addEventListener("submit", (e) => {
    e.preventDefault();
    alert(
      "Your Clinical Dental History has been encrypted and securely transmitted.",
    );
  });

  // Signature Logic
  const canvas = document.getElementById("signature-canvas");
  const clearBtn = document.getElementById("clear-signature");
  const ctx = canvas.getContext("2d");

  // Adjust canvas resolution for high-fidelity
  function resizeCanvas() {
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * window.devicePixelRatio;
    canvas.height = rect.height * window.devicePixelRatio;
    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    ctx.lineWidth = 2;
    ctx.lineCap = "round";
    ctx.strokeStyle = "#00355f";
  }

  window.addEventListener("resize", resizeCanvas);
  resizeCanvas();

  let drawing = false;

  function startDrawing(e) {
    drawing = true;
    draw(e);
  }

  function stopDrawing() {
    drawing = false;
    ctx.beginPath();
  }

  function draw(e) {
    if (!drawing) return;

    const rect = canvas.getBoundingClientRect();
    let x, y;

    if (e.touches) {
      x = e.touches[0].clientX - rect.left;
      y = e.touches[0].clientY - rect.top;
    } else {
      x = e.clientX - rect.left;
      y = e.clientY - rect.top;
    }

    ctx.lineTo(x, y);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x, y);
  }

  canvas.addEventListener("mousedown", startDrawing);
  canvas.addEventListener("mousemove", draw);
  window.addEventListener("mouseup", stopDrawing);

  canvas.addEventListener("touchstart", startDrawing);
  canvas.addEventListener("touchmove", draw);
  canvas.addEventListener("touchend", stopDrawing);

  clearBtn.addEventListener("click", () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  });

  console.log(
    "David Gouett Clinical Systems: Initialization sequence complete.",
  );
})();

// Form dropdown js
function handleDropdown(menuId, iconId, action) {
  const menu = document.getElementById(menuId);
  const icon = document.getElementById(iconId);
  const closeBtn = document.getElementById("mobileCloseBtn");
  if (!menu) return;

  const isMobileMenu = menuId === "mobileMenu";

  // Determine target execution state
  let shouldShow = false;
  if (action === "show") {
    shouldShow = true;
  } else if (action === "hide") {
    shouldShow = false;
  } else if (action === "toggle") {
    shouldShow = isMobileMenu
      ? menu.classList.contains("pointer-events-none")
      : menu.classList.contains("hidden");
  }

  if (shouldShow) {
    if (isMobileMenu) {
      // Mobile Animation: Slide open grid row height boundaries and fade layout parameters
      menu.classList.remove(
        "grid-rows-[0fr]",
        "opacity-0",
        "pointer-events-none",
      );
      menu.classList.add("grid-rows-[1fr]", "opacity-100");
      closeBtn?.classList.remove("hidden");
    } else {
      menu.classList.remove("hidden");
    }
    icon?.classList.add("rotate-180");
  } else {
    if (isMobileMenu) {
      // Mobile Animation: Collapse height boundaries tightly shut
      menu.classList.remove("grid-rows-[1fr]", "opacity-100");
      menu.classList.add("grid-rows-[0fr]", "opacity-0", "pointer-events-none");
      closeBtn?.classList.add("hidden");
    } else {
      menu.classList.add("hidden");
    }
    icon?.classList.remove("rotate-180");
  }
}

// Footer forms dropdown
function handleFooterDropdown(menuId, iconId, action) {
  const menu = document.getElementById(menuId);
  const icon = document.getElementById(iconId);
  if (!menu) return;

  if (action === "show") {
    // Smoothly float upwards and fade in
    menu.classList.remove(
      "invisible",
      "opacity-0",
      "translate-y-2",
      "pointer-events-none",
    );
    menu.classList.add("visible", "opacity-100", "translate-y-0");
    icon?.classList.add("rotate-180");
  } else if (action === "hide") {
    // Smoothly slide down slightly and fade out
    menu.classList.remove("visible", "opacity-100", "translate-y-0");
    menu.classList.add(
      "invisible",
      "opacity-0",
      "translate-y-2",
      "pointer-events-none",
    );
    icon?.classList.remove("rotate-180");
  }
}
