document.addEventListener("DOMContentLoaded", () => {
  // --- Draggable Comparison Slider ---
  const slider = document.getElementById("comparison-slider");
  const handle = document.getElementById("comparison-handle");
  const afterImage = document.querySelector(".comparison-figure.after");

  let isDragging = false;

  function startDrag(e) {
    isDragging = true;
    slider.classList.add("dragging"); // Optional: Add class for styling during drag
    // Prevent default only for touch events to allow scrolling on desktop if needed
    if (e.type === "touchstart") {
      e.preventDefault();
    }
  }

  function stopDrag() {
    if (isDragging) {
      isDragging = false;
      slider.classList.remove("dragging"); // Optional: Remove class
    }
  }

  function moveDrag(e) {
    if (!isDragging) return;

    // Get the X coordinate, handling both mouse and touch events
    let clientX = e.clientX;
    if (e.type === "touchmove") {
      clientX = e.touches[0].clientX;
      e.preventDefault(); // Prevent scrolling while dragging on touch
    }

    // Get slider boundaries
    const sliderRect = slider.getBoundingClientRect();
    const sliderLeft = sliderRect.left;
    const sliderWidth = sliderRect.width;

    // Calculate position relative to the slider container
    let newPosition = clientX - sliderLeft;

    // Constrain position within the slider bounds (0 to sliderWidth)
    newPosition = Math.max(0, Math.min(newPosition, sliderWidth));

    // Convert position to percentage
    const newPositionPercent = (newPosition / sliderWidth) * 100;

    // Update handle position and after image width
    handle.style.left = `${newPositionPercent}%`;
    afterImage.style.width = `${newPositionPercent}%`;
  }

  if (slider && handle && afterImage) {
    // Mouse Events
    handle.addEventListener("mousedown", startDrag);
    document.addEventListener("mousemove", moveDrag); // Listen on document for smoother dragging
    document.addEventListener("mouseup", stopDrag);

    // Touch Events
    handle.addEventListener("touchstart", startDrag, { passive: false }); // passive: false allows preventDefault
    document.addEventListener("touchmove", moveDrag, { passive: false }); // passive: false allows preventDefault
    document.addEventListener("touchend", stopDrag);
    document.addEventListener("touchcancel", stopDrag); // Handle cancelled touches

    // Also allow starting drag by clicking/tapping anywhere on the slider
    slider.addEventListener("mousedown", (e) => {
      if (e.target === slider) {
        // Only if click is directly on slider, not handle/image
        startDrag(e);
        moveDrag(e); // Immediately move handle to click position
      }
    });
    slider.addEventListener(
      "touchstart",
      (e) => {
        if (e.target === slider) {
          startDrag(e);
          moveDrag(e); // Immediately move handle to touch position
        }
      },
      { passive: false }
    );

    // Initial setup (optional, if you don't want 50% default)
    // const initialPercent = 50;
    // handle.style.left = `${initialPercent}%`;
    // afterImage.style.width = `${initialPercent}%`;
  }
  // --- End Draggable Comparison Slider ---

  // --- "AI" Recommendation Form ---
  const recommendationForm = document.getElementById("recommendation-form");
  const recommendationResultDiv = document.getElementById(
    "recommendation-result"
  );

  if (recommendationForm && recommendationResultDiv) {
    recommendationForm.addEventListener("submit", (e) => {
      e.preventDefault(); // Prevent actual form submission

      const skinType = document.getElementById("skin-type").value;
      const skinConcern = document.getElementById("skin-concern").value;
      const desiredOutcome = document.getElementById("desired-outcome").value;

      let recommendation =
        "Based on your selections, we recommend exploring our general ";
      let specificTreatment = "";

      // --- Simple Recommendation Logic (SIMULATION) ---
      if (
        skinType === "dry" ||
        skinConcern === "dryness" ||
        desiredOutcome === "hydration"
      ) {
        specificTreatment =
          "Hydrating Herbal Facial or a Nourishing Body Wrap.";
      } else if (skinConcern === "aging" || desiredOutcome === "anti-aging") {
        specificTreatment = "Rejuvenating Organic Facial with Rosehip Oil.";
      } else if (skinConcern === "acne" || desiredOutcome === "clearing") {
        specificTreatment = "Purifying Facial with Tea Tree and Clay Mask.";
      } else if (
        skinType === "sensitive" ||
        skinConcern === "redness" ||
        desiredOutcome === "soothing"
      ) {
        specificTreatment = "Calming Chamomile Facial for Sensitive Skin.";
      } else if (
        skinConcern === "pigmentation" ||
        desiredOutcome === "brightening"
      ) {
        specificTreatment = "Brightening Vitamin C Facial.";
      } else if (skinType === "oily") {
        specificTreatment = "Balancing Facial with Witch Hazel.";
      } else {
        // Default / fallback
        specificTreatment =
          "Organic Facials. Please consult with our therapist for the best fit!";
      }
      // --- End of Simple Logic ---

      recommendationResultDiv.innerHTML = `<h4>Recommendation:</h4><p>${recommendation} ${specificTreatment}</p>`;
      recommendationResultDiv.style.display = "block"; // Show the result div

      // Scroll smoothly to the result
      recommendationResultDiv.scrollIntoView({
        behavior: "smooth",
        block: "center",
      });
    });
  }

  // --- Chatbot ---
  const chatbotButton = document.getElementById("chatbot-button");
  const chatbotPopup = document.getElementById("chatbot-popup");
  const closeChatbotButton = document.getElementById("close-chatbot");

  if (chatbotButton && chatbotPopup && closeChatbotButton) {
    chatbotButton.addEventListener("click", () => {
      chatbotPopup.classList.toggle("active");
    });

    closeChatbotButton.addEventListener("click", () => {
      chatbotPopup.classList.remove("active");
    });

    // Optional: Close chatbot if clicked outside
    document.addEventListener("click", (event) => {
      if (
        !chatbotPopup.contains(event.target) &&
        !chatbotButton.contains(event.target)
      ) {
        chatbotPopup.classList.remove("active");
      }
    });
  }

  // --- Footer Year ---
  const currentYearSpan = document.getElementById("current-year");
  if (currentYearSpan) {
    currentYearSpan.textContent = new Date().getFullYear();
  }

  // --- Smooth Scrolling for Nav Links ---
  document.querySelectorAll('nav a[href^="#"]').forEach((anchor) => {
    anchor.addEventListener("click", function (e) {
      e.preventDefault();
      const targetId = this.getAttribute("href");
      const targetElement = document.querySelector(targetId);
      if (targetElement) {
        // Calculate offset for fixed header
        const headerOffset =
          document.querySelector("header").offsetHeight || 70; // Get header height or fallback
        const elementPosition = targetElement.getBoundingClientRect().top;
        const offsetPosition =
          elementPosition + window.pageYOffset - headerOffset;

        window.scrollTo({
          top: offsetPosition,
          behavior: "smooth",
        });
      }
    });
  });

  // --- Hamburger Menu Toggle ---
  const hamburgerButton = document.getElementById("hamburger-button");
  const navLinks = document.getElementById("nav-links");

  if (hamburgerButton && navLinks) {
    hamburgerButton.addEventListener("click", () => {
      navLinks.classList.toggle("active"); // Toggle visibility of nav links
      hamburgerButton.classList.toggle("active"); // Toggle hamburger animation

      // Accessibility: Update aria-expanded attribute
      const isExpanded = navLinks.classList.contains("active");
      hamburgerButton.setAttribute("aria-expanded", isExpanded);
    });

    // Optional: Close menu when a link is clicked
    const allNavLinks = navLinks.querySelectorAll("a");
    allNavLinks.forEach((link) => {
      link.addEventListener("click", () => {
        if (navLinks.classList.contains("active")) {
          navLinks.classList.remove("active");
          hamburgerButton.classList.remove("active");
          hamburgerButton.setAttribute("aria-expanded", "false");
        }
      });
    });
  }
  // --- End Hamburger Menu Toggle ---
}); // End DOMContentLoaded
