document.addEventListener("DOMContentLoaded", function () {
  // Desktop Mega Menu
  const menuTriggers = document.querySelectorAll(".menu-trigger");
  const megaMenus = document.querySelectorAll(".mega-menu");
  const navItemDropdowns = document.querySelectorAll(".nav-item-dropdown");
  let activeMenuId = null;

  function hideActiveMenu() {
    if (activeMenuId) {
      const menu = document.getElementById(activeMenuId);
      if (menu) menu.classList.add("hidden");
      activeMenuId = null;
    }
  }

  menuTriggers.forEach((trigger) => {
    trigger.addEventListener("click", (event) => {
      event.stopPropagation();
      const menuId = trigger.parentElement.getAttribute("data-menu-id");

      if (activeMenuId === menuId) {
        hideActiveMenu();
      } else {
        hideActiveMenu();
        const menu = document.getElementById(menuId);
        if (menu) {
          menu.classList.remove("hidden");
          activeMenuId = menuId;
        }
      }
    });
  });

  // Close mega menu when hovering away from nav-item-dropdown
  navItemDropdowns.forEach((dropdown) => {
    dropdown.addEventListener("mouseenter", () => {
      const menuId = dropdown.getAttribute("data-menu-id");
      if (menuId) {
        hideActiveMenu();
        const menu = document.getElementById(menuId);
        if (menu) {
          menu.classList.remove("hidden");
          activeMenuId = menuId;
        }
      }
    });

    dropdown.addEventListener("mouseleave", (event) => {
      const menuId = dropdown.getAttribute("data-menu-id");
      const menu = document.getElementById(menuId);

      // Check if mouse is moving to the mega menu
      if (menu && !menu.contains(event.relatedTarget)) {
        setTimeout(() => {
          // Double-check mouse isn't in mega menu
          if (!menu.matches(":hover") && !dropdown.matches(":hover")) {
            hideActiveMenu();
          }
        }, 100);
      }
    });
  });

  // Keep mega menu open when hovering over it
  megaMenus.forEach((menu) => {
    menu.addEventListener("mouseenter", (event) => {
      event.stopPropagation();
    });

    menu.addEventListener("mouseleave", () => {
      hideActiveMenu();
    });
  });

  // Close on click outside
  document.addEventListener("click", hideActiveMenu);

  // Mobile Menu
  const mobileMenuButton = document.getElementById("mobile-menu-button");
  const closeMobileMenuButton = document.getElementById("close-mobile-menu");
  const mobileMenu = document.getElementById("mobile-menu");
  const mobileMenuOverlay = document.getElementById("mobile-menu-overlay");

  function openMobileMenu() {
    mobileMenu.style.transform = "translateX(0)";
    mobileMenuOverlay.style.display = "block";
    document.body.style.overflow = "hidden";
  }

  function closeMobileMenu() {
    mobileMenu.style.transform = "translateX(100%)";
    mobileMenuOverlay.style.display = "none";
    document.body.style.overflow = "";
  }

  mobileMenuButton.addEventListener("click", openMobileMenu);
  closeMobileMenuButton.addEventListener("click", closeMobileMenu);
  mobileMenuOverlay.addEventListener("click", closeMobileMenu);
});

// -----------
// client-section
document.addEventListener("DOMContentLoaded", () => {
  const scroller = document.querySelector(".scroller");

  // If the scroller exists
  if (scroller) {
    // Get all the direct children of the scroller (the logo items)
    const scrollerContent = Array.from(scroller.children);

    // For each item, clone it and add it back to the scroller
    scrollerContent.forEach((item) => {
      const duplicatedItem = item.cloneNode(true);
      // Add an aria-hidden attribute to the cloned items for accessibility,
      // as they are purely decorative duplicates.
      duplicatedItem.setAttribute("aria-hidden", true);
      scroller.appendChild(duplicatedItem);
    });
  }
});

// --------
// about-section
document.addEventListener("DOMContentLoaded", () => {
  const counters = document.querySelectorAll(".stat-number");
  const speed = 200; // The lower the #, the faster the count

  const animateCounter = (counter) => {
    const target = +counter.getAttribute("data-target");
    const suffix = counter.innerText.replace(/[0-9]/g, ""); // Get suffix like +, %, k

    const updateCount = () => {
      const count = +counter.getAttribute("data-count") || 0;
      const increment = target / speed;

      if (count < target) {
        const newCount = Math.ceil(count + increment);
        counter.setAttribute("data-count", newCount);
        // For the '10k' case, we just animate the number 10
        counter.innerText =
          (target === 10 ? newCount : Math.floor(newCount)) + suffix;
        setTimeout(updateCount, 15);
      } else {
        counter.innerText = target + suffix;
      }
    };
    updateCount();
  };

  // Intersection Observer to trigger animation on scroll
  const observer = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          animateCounter(entry.target);
          observer.unobserve(entry.target); // Animate only once
        }
      });
    },
    {
      root: null, // relative to the viewport
      threshold: 0.1, // 10% of the item must be visible
    }
  );

  counters.forEach((counter) => {
    observer.observe(counter);
  });
});

// ------------------
// Text Animation
const words = ["Businesses", "India", "Brands"];
let wordIndex = 0;
let charIndex = 0;
let isDeleting = false;
const typingElement = document.getElementById("typing");

function type() {
  const currentWord = words[wordIndex];
  const currentText = currentWord.substring(0, charIndex);
  typingElement.textContent = currentText;

  if (!isDeleting && charIndex < currentWord.length) {
    charIndex++;
    setTimeout(type, 150);
  } else if (isDeleting && charIndex > 0) {
    charIndex--;
    setTimeout(type, 80);
  } else {
    isDeleting = !isDeleting;
    if (!isDeleting) wordIndex = (wordIndex + 1) % words.length;
    setTimeout(type, 1000);
  }
}

document.addEventListener("DOMContentLoaded", type);

// -------------------------------------------
// testimonial-section
document.addEventListener("DOMContentLoaded", function () {
  const testimonials = [
    {
      stars: 5,
      text: "Manak Analytics & Development helped us build a scalable custom software that automated key processes in our logistics business. Their team was highly professional, responsive, and delivered on time. The final product boosted our efficiency and is easy to maintain. Definitely one of the best software development partners we’ve worked with.",
      avatar: "./Images/testimonials/Testimonials-1.png",
      name: "Abdul Hameed",
      // handle: "@siennahewitt",
      role: "PR Officer",
    },
    {
      stars: 5,
      text: "We needed a modern, SEO-optimized website and Manak Analytics delivered exactly that. Their design team built a responsive, fast, and user-friendly site that truly reflects our brand. Our search rankings improved significantly, and we now receive more quality leads. Their service and support were outstanding from start to finish.",
      avatar: "./Images/testimonials/Testimonials-2.jpg",
      name: "Kari Rasmussen",
      // handle: "@itskari",
      role: "Marketing Head",
    },
    {
      stars: 5,
      text: "Manak Analytics created a powerful mobile app for our business that runs smoothly across Android and iOS platforms. The user interface is intuitive, fast, and well-designed. Their developers were proactive with suggestions and updates. I highly recommend them for any business looking for mobile app development services.",
      avatar: "./Images/testimonials/Testimonials-3.png",
      name: "Lucas",
      // handle: "@alaurent_",
      role: "Web Designer",
    },
    {
      stars: 5,
      text: "Thanks to Manak Analytics, our new e-commerce store is secure, feature-rich, and mobile responsive. Their team handled payment gateways, product filters, and performance optimizations with ease. The website loads faster, looks great, and our conversion rate has increased. It’s the perfect solution for online retail growth.",
      avatar: "./Images/testimonials/Testimonials-4.jpg",
      name: "Manoj Jaiswal",
      // handle: "@aliah_ux",
      role: "Owner/Founder",
    },
    {
      stars: 5,
      text: "We collaborated with Manak Analytics to build a custom 2D mobile game. From UI design to game logic and deployment, the team handled everything efficiently. The final result was engaging and bug-free. They truly understand game development and delivered beyond expectations. We’re excited to work on more titles with them.",
      avatar: "./Images/testimonials/Testimonials-5.jpg",
      name: "Robert Kingsley",
      // handle: "@eduardfranz",
      role: "Product Manager",
    },
    {
      stars: 5,
      text: "Manak Analytics & Development built our HR web application with a robust backend and an intuitive frontend. The dashboard is user-friendly, secure, and scalable. They followed all deadlines and ensured smooth data integration. We’re now able to manage all internal HR operations digitally with ease and efficiency.",
      avatar: "./Images/testimonials/Testimonials-6.jpg",
      name: "Isaac Charles",
      // handle: "@lilyrose",
      role: "CEO",
    },
    {
      stars: 5,
      text: "Our WordPress website was slow and outdated until Manak Analytics redesigned it. The new version is lightning-fast, fully responsive, and easy to manage. SEO improvements brought more visitors within a few weeks. Their team provided excellent training and support. A great choice for WordPress development and redesign work.",
      avatar: "./Images/testimonials/Testimonials-7.jpg",
      name: "Ronald Richard ",
      // handle: "@james_o",
      role: "Director",
    },
    {
      stars: 5,
      text: "We rely on Manak Analytics for monthly IT support, server maintenance, and website monitoring. Their quick response time and preventive approach help us avoid issues before they impact operations. They’re dependable and affordable, making them a valuable long-term partner for any company needing professional IT services.",
      avatar: "./Images/testimonials/Testimonials-8.jpg",
      name: "Abhay Raj",
      // handle: "@peterm",
      role: "Director",
    },
  ];

  const track = document.querySelector(".carousel-track");
  const dotsContainer = document.querySelector(".carousel-dots");
  const nextButton = document.querySelector(".carousel-arrow.right");
  const prevButton = document.querySelector(".carousel-arrow.left");

  let currentPage = 0;
  let cardsPerView = 3;

  // --- Star SVG ---
  const starSVG = `<svg viewBox="0 0 20 20" fill="currentColor"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" /></svg>`;
  const verifiedSVG = `<svg fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" /></svg>`;

  // --- Functions ---
  const setCardsPerView = () => {
    if (window.innerWidth <= 768) {
      cardsPerView = 1;
    } else if (window.innerWidth <= 1024) {
      cardsPerView = 2;
    } else {
      cardsPerView = 3;
    }
  };

  const getTotalPages = () => Math.ceil(testimonials.length / cardsPerView);

  const renderContent = () => {
    // Render Cards
    track.innerHTML = "";
    testimonials.forEach((t) => {
      const starsHTML = Array(t.stars).fill(starSVG).join("");
      track.innerHTML += `
                       <div class="testimonial-card">
                           <div class="stars">${starsHTML}</div>
                           <p class="text">${t.text}</p>
                           <div class="author">
                               <img src="${t.avatar}" alt="${t.name}">
                               <div class="author-info">
                                   <span class="name">${t.name}<span class="verified-badge">${verifiedSVG}</span></span>
                                   <span class="handle">${t.role}</span>
                               </div>
                           </div>
                       </div>
                   `;
    });

    // Render Dots
    dotsContainer.innerHTML = "";
    for (let i = 0; i < getTotalPages(); i++) {
      const dot = document.createElement("div");
      dot.classList.add("dot");
      dot.addEventListener("click", () => goToPage(i));
      dotsContainer.appendChild(dot);
    }

    updateUI();
  };

  const updateUI = () => {
    const totalPages = getTotalPages();
    const offset = currentPage * (100 / totalPages); // this doesn't work well with flex basis
    const cardWidth = track.querySelector(".testimonial-card").offsetWidth;
    const gap = 32; // Corresponds to margin 1rem on each side

    track.style.transform = `translateX(-${
      currentPage * (cardWidth * cardsPerView + gap * cardsPerView)
    }px)`;

    // Update dots
    const dots = document.querySelectorAll(".dot");
    dots.forEach((dot, index) => {
      dot.classList.toggle("active", index === currentPage);
    });

    // Update arrows
    prevButton.classList.toggle("disabled", currentPage === 0);
    nextButton.classList.toggle("disabled", currentPage === totalPages - 1);
  };

  const goToPage = (pageNumber) => {
    if (pageNumber < 0 || pageNumber >= getTotalPages()) return;
    currentPage = pageNumber;
    updateUI();
  };

  // --- Event Listeners ---
  prevButton.addEventListener("click", () => goToPage(currentPage - 1));
  nextButton.addEventListener("click", () => goToPage(currentPage + 1));
  window.addEventListener("resize", () => {
    setCardsPerView();
    renderContent(); // Re-render everything to adjust layout
    goToPage(0); // Reset to first page on resize
  });

  // --- Initial Load ---
  setCardsPerView();
  renderContent();
});

// ---------------------------------------
// process-section
document.addEventListener("DOMContentLoaded", function () {
  const steps = document.querySelectorAll(".process-step");
  const progressFill = document.querySelector(".progress-fill");
  const totalSteps = steps.length;

  // Check if mobile view
  function isMobile() {
    return window.innerWidth <= 768;
  }

  // Calculate progress
  function getProgressValue(stepIndex) {
    const mobile = isMobile();

    if (mobile) {
      // Mobile: calculate vertical distance between circles
      if (stepIndex === 0) return 0;

      const firstCircle = steps[0].querySelector(".step-circle");
      const targetCircle = steps[stepIndex].querySelector(".step-circle");

      if (firstCircle && targetCircle) {
        const firstTop = firstCircle.getBoundingClientRect().top;
        const targetTop = targetCircle.getBoundingClientRect().top;
        const distance = targetTop - firstTop;
        return Math.max(0, distance);
      }
      return 0;
    } else {
      // Desktop: horizontal percentage
      return (stepIndex / (totalSteps - 1)) * 66.66;
    }
  }

  // Activate steps sequentially
  function activateStep(index) {
    if (index < totalSteps) {
      steps[index].classList.add("active");

      // Update progress line
      const progress = getProgressValue(index);

      if (isMobile()) {
        progressFill.style.width = "3px";
        progressFill.style.height = progress + "px";
      } else {
        progressFill.style.height = "3px";
        progressFill.style.width = progress + "%";
      }
    }
  }

  // Initial animation sequence
  setTimeout(() => activateStep(0), 400);
  setTimeout(() => activateStep(1), 1200);
  setTimeout(() => activateStep(2), 2000);

  // Handle window resize for responsive behavior
  let resizeTimer;
  window.addEventListener("resize", () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
      const activeSteps =
        document.querySelectorAll(".process-step.active").length - 1;

      if (activeSteps >= 0) {
        const progress = getProgressValue(activeSteps);

        if (isMobile()) {
          progressFill.style.width = "3px";
          progressFill.style.height = progress + "px";
        } else {
          progressFill.style.height = "3px";
          progressFill.style.width = progress + "%";
        }
      }
    }, 100);
  });
});

// ---------------------------------------
// service-section
// const categories = document.querySelectorAll(".category");
// const subcategories = document.querySelectorAll(".subcategory");
// const serviceContents = document.querySelectorAll(".service-content");

// categories.forEach((category) => {
//   const header = category.querySelector(".category-header");
//   header.addEventListener("click", () => {
//     const wasActive = category.classList.contains("active");

//     categories.forEach((cat) => cat.classList.remove("active"));

//     if (!wasActive) {
//       category.classList.add("active");
//     }
//   });
// });

// subcategories.forEach((sub) => {
//   sub.addEventListener("click", (e) => {
//     e.stopPropagation();
//     const serviceId = sub.dataset.service;

//     subcategories.forEach((s) => s.classList.remove("active"));
//     sub.classList.add("active");

//     serviceContents.forEach((content) => {
//       content.classList.remove("active");
//     });

//     document.getElementById(serviceId).classList.add("active");
//   });
// });

// ------------------------
// contact-us
document.addEventListener("DOMContentLoaded", function () {
  const contactForm = document.getElementById("contactForm");
  const formMessageEl = document.getElementById("form-message");

  /**
   * Handles form submission: validation and displaying feedback.
   */
  contactForm.addEventListener("submit", function (event) {
    // 1. Prevent the default form submission (page reload)
    event.preventDefault();

    // 2. Clear previous messages and error styles
    clearErrors();
    formMessageEl.textContent = "";
    formMessageEl.className = "form-message"; // Reset classes

    // 3. Get form data
    const formData = new FormData(contactForm);
    const formValues = Object.fromEntries(formData.entries());
    let hasError = false;

    // 4. Validation Logic
    for (const key in formValues) {
      const inputEl = document.getElementById(key);
      if (
        inputEl &&
        inputEl.hasAttribute("required") &&
        !formValues[key].trim()
      ) {
        showError(inputEl);
        hasError = true;
      }
    }

    // Specific validation for email
    const emailInput = document.getElementById("email");
    if (emailInput.value && !isValidEmail(emailInput.value)) {
      showError(emailInput);
      hasError = true;
      displayMessage("Please enter a valid email address.", "error");
      return; // Stop further processing
    }

    if (hasError) {
      displayMessage("Please fill out all required fields.", "error");
      return; // Stop if any required field is empty
    }

    // 5. If Validation Passes (Success)
    console.log("Form Submitted Successfully:", formValues);
    displayMessage("Thank you! Your message has been sent.", "success");
    contactForm.reset();
  });

  // --- Helper Functions ---

  /** Adds the 'error' class to an input element. */
  function showError(inputElement) {
    if (inputElement) {
      inputElement.classList.add("error");
    }
  }

  /** Removes the 'error' class from all input elements in the form. */
  function clearErrors() {
    contactForm
      .querySelectorAll(".form-input")
      .forEach((el) => el.classList.remove("error"));
  }

  /** Checks if a string is a valid email format using a simple regex. */
  function isValidEmail(email) {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
  }

  /** Displays a message in the designated message element. */
  function displayMessage(message, type) {
    formMessageEl.textContent = message;
    formMessageEl.classList.add(type);
  }
});

// ----------------------------------------------------------
// document.addEventListener("DOMContentLoaded", () => {
//   const faqItems = document.querySelectorAll(".faq-item");

//   faqItems.forEach((item) => {
//     const button = item.querySelector(".faq-question-button");

//     button.addEventListener("click", () => {
//       const isOpening = !item.classList.contains("active");

//       // 1. Close all other open items (Single-open accordion)
//       faqItems.forEach((otherItem) => {
//         if (otherItem !== item && otherItem.classList.contains("active")) {
//           otherItem.classList.remove("active");
//           otherItem
//             .querySelector(".faq-question-button")
//             .setAttribute("aria-expanded", "false");
//         }
//       });

//       // 2. Toggle the clicked item's state
//       if (isOpening) {
//         item.classList.add("active");
//         button.setAttribute("aria-expanded", "true");
//       } else {
//         item.classList.remove("active");
//         button.setAttribute("aria-expanded", "false");
//       }
//     });
//   });
// });

document.addEventListener("DOMContentLoaded", () => {
  // ---- FAQ Accordion ----
  const faqItems = document.querySelectorAll(".faq-item");

  faqItems.forEach((item) => {
    const button = item.querySelector(".faq-question-button");

    button.addEventListener("click", () => {
      const isOpening = !item.classList.contains("active");

      // Close all other items (single-open accordion)
      faqItems.forEach((otherItem) => {
        if (otherItem !== item && otherItem.classList.contains("active")) {
          otherItem.classList.remove("active");
          otherItem
            .querySelector(".faq-question-button")
            .setAttribute("aria-expanded", "false");
        }
      });

      // Toggle clicked item
      if (isOpening) {
        item.classList.add("active");
        button.setAttribute("aria-expanded", "true");
      } else {
        item.classList.remove("active");
        button.setAttribute("aria-expanded", "false");
      }
    });
  });

  // ---- Category / Subcategory Toggle ----
  const categories = document.querySelectorAll(".category");
  const subcategories = document.querySelectorAll(".subcategory");
  const serviceContents = document.querySelectorAll(".service-content");

  let activeCategory = null;
  let activeSubcategory = null;

  // Category click
  categories.forEach((category) => {
    const header = category.querySelector(".category-header");
    header.addEventListener("click", () => {
      const wasActive = category.classList.contains("active");

      if (wasActive) {
        category.classList.remove("active");
        activeCategory = null;
      } else {
        if (activeCategory) activeCategory.classList.remove("active");

        category.classList.add("active");
        activeCategory = category;
      }
    });
  });

  // Subcategory click
  subcategories.forEach((sub) => {
    sub.addEventListener("click", (e) => {
      e.stopPropagation();
      const serviceId = sub.dataset.service;

      if (activeSubcategory) activeSubcategory.classList.remove("active");
      sub.classList.add("active");
      activeSubcategory = sub;

      serviceContents.forEach((content) => content.classList.remove("active"));
      const targetContent = document.getElementById(serviceId);
      if (targetContent) targetContent.classList.add("active");
    });
  });
});

// ---------------------
// blog-details-view
const copyBtn = document.getElementById("copyBtn");

copyBtn.addEventListener("click", () => {
  const url = window.location.href;
  navigator.clipboard.writeText(url).then(() => {
    const originalText = copyBtn.innerHTML;
    copyBtn.innerHTML = '<i class="ri-check-line"></i> Link Copied!';

    setTimeout(() => {
      copyBtn.innerHTML = originalText;
    }, 2000);
  });
});

// Social share buttons
document.querySelector(".twitter").addEventListener("click", () => {
  const url = window.location.href;
  const text = document.querySelector(".article-title").textContent;
  window.open(
    `https://twitter.com/intent/tweet?url=${encodeURIComponent(
      url
    )}&text=${encodeURIComponent(text)}`,
    "_blank"
  );
});

document.querySelector(".facebook").addEventListener("click", () => {
  const url = window.location.href;
  window.open(
    `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
    "_blank"
  );
});

document.querySelector(".linkedin").addEventListener("click", () => {
  const url = window.location.href;
  window.open(
    `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(
      url
    )}`,
    "_blank"
  );
});
