// Primary navigation: desktop aria-expanded on hover/focus (mega dropdowns)
document.addEventListener("DOMContentLoaded", function () {
    var mqDesktopNav = window.matchMedia("(min-width: 1200px)");
    document.querySelectorAll(".header-menu__item--sub").forEach(function (item) {
        var btn = item.querySelector(".header-menu__trigger");
        if (!btn) return;
        item.addEventListener("mouseenter", function () {
            if (!mqDesktopNav.matches) return;
            btn.setAttribute("aria-expanded", "true");
        });
        item.addEventListener("mouseleave", function () {
            if (!mqDesktopNav.matches) return;
            btn.setAttribute("aria-expanded", "false");
        });
        item.addEventListener("focusin", function () {
            if (!mqDesktopNav.matches) return;
            btn.setAttribute("aria-expanded", "true");
        });
        item.addEventListener("focusout", function (e) {
            if (!mqDesktopNav.matches) return;
            if (!item.contains(e.relatedTarget)) {
                btn.setAttribute("aria-expanded", "false");
            }
        });
    });
});

// Primary navigation: mobile drawer + accordion (≤1199px, matches legacy zetwerk-india)
document.addEventListener("DOMContentLoaded", function () {
    var nav = document.querySelector(".header-menu");
    var toggle = document.querySelector(".header-menu__toggle");
    var overlay = document.querySelector(".header-menu__overlay");
    var panel = document.getElementById("header-menu-sheet");
    if (!nav || !toggle || !overlay || !panel) return;

    var mqMobile = window.matchMedia("(max-width: 1199px)");
    var openLabel = toggle.getAttribute("data-menu-open-label") || "Open menu";
    var closeLabel = toggle.getAttribute("data-menu-close-label") || "Close menu";

    function closeMobileSubmenus() {
        nav.querySelectorAll(".header-menu__item--sub.header-menu__item--expanded").forEach(function (el) {
            el.classList.remove("header-menu__item--expanded");
            var b = el.querySelector(".header-menu__trigger");
            if (b) b.setAttribute("aria-expanded", "false");
        });
    }

    function setDrawerOpen(open) {
        nav.classList.toggle("header-menu--open", open);
        toggle.setAttribute("aria-expanded", open ? "true" : "false");
        toggle.setAttribute("aria-label", open ? closeLabel : openLabel);
        overlay.setAttribute("aria-hidden", open ? "false" : "true");
        if (open) {
            document.body.style.overflow = "hidden";
        } else {
            document.body.style.overflow = "";
            closeMobileSubmenus();
        }
    }

    function isMobileNav() {
        return mqMobile.matches;
    }

    toggle.addEventListener("click", function () {
        if (!isMobileNav()) return;
        setDrawerOpen(!nav.classList.contains("header-menu--open"));
    });

    overlay.addEventListener("click", function () {
        if (!isMobileNav()) return;
        setDrawerOpen(false);
    });

    panel.addEventListener("click", function (e) {
        if (!isMobileNav()) return;
        var t = e.target;
        if (t.closest("a") && !t.closest(".header-menu__trigger")) {
            setDrawerOpen(false);
        }
    });

    document.addEventListener("keydown", function (e) {
        if (e.key === "Escape" && nav.classList.contains("header-menu--open")) {
            setDrawerOpen(false);
        }
    });

    mqMobile.addEventListener("change", function () {
        if (!mqMobile.matches) {
            setDrawerOpen(false);
        }
    });

    nav.querySelectorAll(".header-menu__item--sub .header-menu__trigger").forEach(function (btn) {
        btn.addEventListener("click", function (e) {
            if (!isMobileNav()) return;
            e.stopPropagation();
            var item = btn.closest(".header-menu__item--sub");
            if (!item) return;
            var willOpen = !item.classList.contains("header-menu__item--expanded");
            nav.querySelectorAll(".header-menu__item--sub.header-menu__item--expanded").forEach(function (el) {
                if (el !== item) {
                    el.classList.remove("header-menu__item--expanded");
                    var ob = el.querySelector(".header-menu__trigger");
                    if (ob) ob.setAttribute("aria-expanded", "false");
                }
            });
            item.classList.toggle("header-menu__item--expanded", willOpen);
            btn.setAttribute("aria-expanded", willOpen ? "true" : "false");
        });
    });
});

// Header: solid background after scrolling past top (all breakpoints; bar stays visible).
document.addEventListener("DOMContentLoaded", function () {
    var header = document.querySelector(".main-header");
    if (!header) return;

    var ticking = false;
    var topRevealPx = 64;

    function applyScrollHeader() {
        ticking = false;
        var y = window.scrollY || document.documentElement.scrollTop;
        if (y <= topRevealPx) {
            header.classList.remove("main-header--scrolled");
        } else {
            header.classList.add("main-header--scrolled");
        }
    }

    function onScroll() {
        if (!ticking) {
            window.requestAnimationFrame(applyScrollHeader);
            ticking = true;
        }
    }

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

document.addEventListener('DOMContentLoaded', function () {
    function createSplideSlider(selector) {
        var sliderElement = document.querySelector(selector);
        if (!sliderElement) return;

        var isMobile = window.innerWidth <= 768; 
        var splide = new Splide(selector, {
            type       : isMobile ? 'slide' : 'fade',
            heightRatio: 0.5,
            autoplay   : true,
            interval   : 2500,
            arrows     : false,
            pagination : true,
            speed      : 1000,
            pauseOnHover : false
        });

        splide.mount();
    }

    createSplideSlider('#banner-slider');
    createSplideSlider('#about-banner-slider');
});


//----------------- Accordion ------------------------//
/**
 * Recalculate max-height for accordions inside a tab panel (fixes hidden tabs where scrollHeight was 0).
 * @param {Element|null} container
 */
function refreshAccordionsIn(container) {
    if (!container) return;
    container.querySelectorAll('.accordion__item').forEach((item) => {
        const content = item.querySelector('.accordion__item--content');
        if (!content) return;
        if (item.classList.contains('active')) {
            content.style.maxHeight = content.scrollHeight + 'px';
        } else {
            content.style.maxHeight = '0px';
        }
    });
}

document.addEventListener('DOMContentLoaded', function () {
    const headers = document.querySelectorAll('.accordion__item--header');
    if (!headers.length) return;

    document.querySelectorAll('.accordion__item').forEach((item) => {
        const content = item.querySelector('.accordion__item--content');
        if (!content) return;
        if (!item.classList.contains('active')) {
            content.style.maxHeight = '0px';
        } else {
            content.style.maxHeight = content.scrollHeight + 'px';
        }
    });

    headers.forEach((header) => {
        header.addEventListener('click', () => {
            const accordionItem = header.closest('.accordion__item');
            if (!accordionItem) return;
            const accordionRoot = header.closest('.accordion');
            const line = accordionItem.querySelector('.line');
            const accordionContent = accordionItem.querySelector('.accordion__item--content');
            if (!accordionContent) return;

            const scope = accordionRoot || document;

            if (line) line.classList.toggle('hide');
            scope.querySelectorAll('.accordion__item .line').forEach((otherLine) => {
                if (otherLine !== line) otherLine.classList.remove('hide');
            });

            scope.querySelectorAll('.accordion__item.active').forEach((item) => {
                if (item !== accordionItem) {
                    item.classList.remove('active');
                    const c = item.querySelector('.accordion__item--content');
                    if (c) c.style.maxHeight = '0px';
                }
            });

            accordionItem.classList.toggle('active');
            if (accordionItem.classList.contains('active')) {
                accordionContent.style.maxHeight = accordionContent.scrollHeight + 'px';
            } else {
                accordionContent.style.maxHeight = '0px';
            }
        });
    });
});


//----------------- Tabs ------------------------//
document.addEventListener("DOMContentLoaded", function () {
    var tabWrappers = document.querySelectorAll('.tab-wrapper');

    tabWrappers.forEach(function (tabWrapper) {
        var tabBlocks = tabWrapper.querySelectorAll('.tab-block');

        tabBlocks.forEach(function (tabBlock) {
            var tabMnu = tabBlock.querySelectorAll('.tab-menu li');
            var tabContent = tabBlock.querySelectorAll('.tab-content > .tab-items');
            var tabMenuEl = tabBlock.querySelector('.tab-menu');

            tabContent.forEach((content, i) => content.style.display = (i === 0) ? 'block' : 'none');

            tabMnu.forEach((menu, i) => {
                menu.dataset.tab = 'tab' + i;
                if (tabContent[i]) tabContent[i].dataset.tab = 'tab' + i;
            });

            if (!tabMenuEl) return;

            tabMenuEl.addEventListener('click', function (e) {
                var li = e.target.closest('li');
                if (!li || !tabMenuEl.contains(li)) return;

                var tabData = li.dataset.tab;

                tabContent.forEach((content) => (content.style.display = 'none'));

                var activeTabContent = tabBlock.querySelector('.tab-items[data-tab="' + tabData + '"]');
                if (activeTabContent) {
                    activeTabContent.style.display = 'block';
                    requestAnimationFrame(function () {
                        refreshAccordionsIn(activeTabContent);
                    });
                }

                var prevActive = tabMenuEl.querySelector('li.tab-active');
                if (prevActive) prevActive.classList.remove('tab-active');
                li.classList.add('tab-active');
            });
        });
    });
});

//----------------- Readmore content show/hide ------------------------//
document.addEventListener("DOMContentLoaded", function () {
    let readmoreBtns = document.querySelectorAll('.readmore-btn');
    let readmoreContainers = document.querySelectorAll('.read-more-container');
    let downArrows = document.querySelectorAll('.down-arrow');

    readmoreBtns.forEach((btn, index) => {
        btn.addEventListener('click', function () {
            let readmoreCnt = readmoreContainers[index];
            let downArrow = downArrows[index];

            readmoreCnt.classList.toggle('active');

            if (readmoreCnt.classList.contains('active')) {
                readmoreCnt.style.maxHeight = readmoreCnt.scrollHeight + 'px';
                downArrow.style.transform = 'rotate(180deg)';
                btn.childNodes[0].textContent = 'Read Less '; 
            } else {
                readmoreCnt.style.maxHeight = '0';
                downArrow.style.transform = 'rotate(0deg)';
                btn.childNodes[0].textContent = 'Read More ';
            }
        });
    });
});




//----------------- Map hover functionality ------------------------//
document.addEventListener("DOMContentLoaded", () => {
  const map = document.querySelector(".hp-map");
  const scrollLeftButton = document.getElementById("scroll-left");
  const scrollRightButton = document.getElementById("scroll-right");
  const scrollAmount = 100;

  if (scrollLeftButton) {
    scrollLeftButton.addEventListener("click", () => {
      map.scrollLeft -= scrollAmount;
    });
  }
  if (scrollRightButton) {
    scrollRightButton.addEventListener("click", () => {
      map.scrollLeft += scrollAmount;
    });
  }

  const circles = document.querySelectorAll(".blink-circle");

  const hoverElement = document.createElement("div");
  hoverElement.classList.add("hover-text");
  document.body.appendChild(hoverElement);

  const hoverLine = document.createElement("div");
  hoverLine.classList.add("hover-line");
  document.body.appendChild(hoverLine);

  const CirclesHoverData = ACFData.CirclesHoverData;
  let hoverTimeout;
  let autoCycleInterval;
  let currentIndex = 0;
  let isHovering = false;

  const showHoverText = (index) => {
    const circle = circles[index];
    if (!circle) return;

    const hoverText = CirclesHoverData[index];
    hoverElement.innerHTML = hoverText;

    const circleRect = circle.getBoundingClientRect();
    const circleCenterX = circleRect.left + circleRect.width / 2;
    const circleCenterY = circleRect.top + circleRect.height / 2;

    // Position hover text
    hoverElement.style.left = `${circleCenterX}px`;
    hoverElement.style.top = `${circleCenterY - 130}px`;
    hoverElement.style.transform = "translate(-50%, 0)";
    hoverElement.style.display = "block";
    hoverElement.style.opacity = "1";


    
    // Position line
    hoverLine.style.left = `${circleCenterX}px`;
    hoverLine.style.top = `${circleCenterY - 90}px`;
    hoverLine.style.display = "block";
  };

  const hideHoverText = () => {
    hoverElement.style.display = "none";
    hoverElement.style.opacity = "0";
    hoverLine.style.display = "none";
  };

  const startAutoCycle = () => {
    autoCycleInterval = setInterval(() => {
      if (!isHovering) {
        showHoverText(currentIndex);
        currentIndex = (currentIndex + 1) % circles.length;
      }
    }, 2000); 
  };

  const stopAutoCycle = () => {
    clearInterval(autoCycleInterval);
  };

  // Start initial auto cycle
  startAutoCycle();

  circles.forEach((circle, index) => {
    circle.addEventListener("mouseover", () => {
      isHovering = true;
      clearTimeout(hoverTimeout);
      stopAutoCycle();

      hoverTimeout = setTimeout(() => {
        showHoverText(index);
      }, 100);
    });

    circle.addEventListener("mouseout", () => {
      clearTimeout(hoverTimeout);
      hoverTimeout = setTimeout(() => {
        hideHoverText();
        isHovering = false;
        startAutoCycle();
      }, 300);
    });
  });

  window.addEventListener("scroll", () => {
    hideHoverText();
  });

  map.addEventListener("scroll", () => {
    hideHoverText();
  });

});

// Horizontal Scroll Pagination with Dots - .flex-box-2
document.addEventListener('DOMContentLoaded', () => {
    const wrapper = document.querySelector('.flex-box-2');
    const paginationContainer = document.querySelector('.pagination_dots');
    const items = document.querySelectorAll('.grid-item');
  
    if (wrapper && paginationContainer && items.length > 0) {
      items.forEach(() => {
        const dot = document.createElement('span');
        dot.classList.add('dot');
        paginationContainer.appendChild(dot);
      });
  
      const dots = document.querySelectorAll('.pagination_dots .dot');
      const itemWidth = items[0].offsetWidth - 180;
  
      dots[0].classList.add('active');
  
      wrapper.addEventListener('scroll', () => {
        const scrollPosition = wrapper.scrollLeft;
        const activeIndex = Math.round(scrollPosition / itemWidth);
  
        dots.forEach((dot, index) => {
          dot.classList.toggle('active', index === activeIndex);
        });
      });
  
      // Optional: Enable dot click scroll behavior
      // dots.forEach((dot, index) => {
      //   dot.addEventListener('click', () => {
      //     wrapper.scrollTo({ left: index * itemWidth, behavior: 'smooth' });
      //   });
      // });
    }
});


// Scroll Tabs Activation Toggle - .scroll-tab .line
document.addEventListener('DOMContentLoaded', () => {
    const tabs = document.querySelectorAll(".scroll-tab .line");
  
    if (tabs.length > 0) {
      tabs[0].classList.add("active");
    }
  
    tabs.forEach((tab) => {
      tab.addEventListener("click", function () {
        tabs.forEach((t) => t.classList.remove("active"));
        this.classList.add("active");
      });
    });
});


// Text Truncation Utility (Commented)
document.addEventListener('DOMContentLoaded', () => {
    // const elements = document.querySelectorAll(".truncation"); 
    // elements.forEach(el => {
    //   const maxLength = 80;
    //   const text = el.textContent.trim();
    //   if (text.length > maxLength) {
    //     el.textContent = text.substring(0, maxLength) + "..";
    //   }
    // });
});


//Mobile-Only Dot Pagination System (for carousels)
document.addEventListener('DOMContentLoaded', () => {
    function setupPagination(containerSelector, itemSelector, paginationSelector) {
      const container = document.querySelector(containerSelector);
      const paginationContainer = document.querySelector(paginationSelector);
      const items = container ? container.querySelectorAll(itemSelector) : [];
  
      if (!container || !paginationContainer || items.length === 0) return;
  
      if (window.innerWidth <= 768 && paginationContainer.querySelectorAll(".dot").length === 0) {
        items.forEach((item, index) => {
          const dot = document.createElement("span");
          dot.classList.add("dot");
          if (index === 0) dot.classList.add("active");
          dot.dataset.index = index;
          paginationContainer.appendChild(dot);
  
          dot.addEventListener("click", function () {
            const scrollAmount = items[index].offsetLeft - container.offsetLeft;
            container.scrollTo({ left: scrollAmount, behavior: "smooth" });
          });
        });
  
        container.addEventListener("scroll", () => {
          const currentIndex = Math.round(container.scrollLeft / items[0].offsetWidth);
          document.querySelectorAll(`${paginationSelector} .dot`).forEach((dot, i) => {
            dot.classList.toggle("active", i === currentIndex);
          });
        });
      }
    }
  
    // Apply to specific containers
    setupPagination(".right-banner", ".card", ".custom-pagination");
    setupPagination(".grid-coln-4", ".value", ".custom-pagination");
});


// Footer Dropdown Accordion - .footer-toggle
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll(".footer-toggle").forEach(toggle => {
      toggle.addEventListener("click", function () {
        const dropdown = this.nextElementSibling;
  
        document.querySelectorAll(".footer-dropdown").forEach(menu => {
          if (menu !== dropdown) {
            menu.classList.remove("active");
            menu.style.maxHeight = null;
            menu.previousElementSibling.classList.remove("active");
          }
        });
  
        dropdown.classList.toggle("active");
        this.classList.toggle("active");
  
        if (dropdown.classList.contains("active")) {
          dropdown.style.maxHeight = dropdown.scrollHeight + "px";
        } else {
          dropdown.style.maxHeight = null;
        }
      });
    });
});



// Scrollable Tabs with Section Navigation
document.addEventListener('DOMContentLoaded', () => {
    const scrollContainer = document.querySelector(".scroll-tab");
    const tabs = document.querySelectorAll(".scroll-link");
  
    tabs.forEach(tab => {
      tab.addEventListener("click", function (event) {
        event.preventDefault();
  
        const targetId = this.getAttribute("data-target");
        const targetSection = document.getElementById(targetId);
  
        tabs.forEach(t => t.classList.remove("active"));
        this.classList.add("active");
  
        this.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
  
        setTimeout(() => {
          if (targetSection) {
            targetSection.scrollIntoView({ behavior: "smooth" });
          }
        }, 500); 
      });
    });
  
    if (scrollContainer) {
      scrollContainer.style.overflowX = "auto";
      scrollContainer.style.scrollBehavior = "smooth";
    }
});

// Number Slider
document.addEventListener("DOMContentLoaded", function () {
    if (!document.querySelector(".highlighted-stats-slider")) return;

    new Splide(".highlighted-stats-slider", {
        type: "loop",
        perPage: 5,
        perMove: 1,
        arrows: false,
        pagination: false,
        drag: false,
        gap: "90px",
        keyboard: true,
        autoScroll: {
            speed: 1.5,
            pauseOnHover: false,
        },
        breakpoints: {
            1200: {
                perPage: 4,
                gap: "40px",
            },
            1024: {
                perPage: 3,
                gap: "40px",
            },
            768: {
                perPage: 2,
                gap: "40px",
            },
        },
    }).mount({ AutoScroll: window.splide.Extensions.AutoScroll });
});

//Our Customers Logos Sliders
document.addEventListener("DOMContentLoaded", function () {
    let sliders = document.querySelectorAll(".elect_oc_slider, .associate-partners-slider, .hp-client-slider, .abt_oc_slider, .commo_oc_slider");

    if (!sliders.length) return;

    sliders.forEach((slider) => {
        const slideCount = slider.querySelectorAll(".splide__slide").length;
        if (slideCount < 4) {
            slider.classList.add("logo-slider-static");
            return;
        }

        let perPageSetting = 4; 

        if (slider.classList.contains("abt_oc_slider")) {
            perPageSetting = 5; 
        } else if (slider.classList.contains("commo_oc_slider")) {
            perPageSetting = 3; 
        }

        new Splide(slider, {
            type: "loop",
            perPage: perPageSetting,
            perMove: 1,
            arrows: false,
            pagination: false,
            drag: false,
            gap: "60px",
            keyboard: true,
            autoScroll: {
                speed: 1.5,
                pauseOnHover: false, 
                pauseOnFocus: false, 
            },
            breakpoints: {
                1200: { perPage: slider.classList.contains("commo_oc_slider") ? 2 : 4 },
                768: { perPage: 1 },
                576: { 
                    perPage: 2,
                gap: "40px",
                },
            },
        }).mount({ AutoScroll: window.splide.Extensions.AutoScroll });
    });
});

//Image Hover Effect Slider
document.addEventListener("DOMContentLoaded", function () {
    if (!document.querySelector(".business_model_slider")) return;

    new Splide(".business_model_slider", {
        type: "loop",
        perPage: 3,
        perMove: 1,
        arrows: false, 
        pagination: false,
        drag: false,
        gap: "30px",
        keyboard: true,
        breakpoints: {
            1200: {
                perPage: 1.5,
                drag: true,
            },
            768: {
                perPage: 1,
                drag: true,
                pagination: true,
            },
        },
    }).mount({});
});

//WHY ZETWERK SLIDER
document.addEventListener("DOMContentLoaded", function () {
    const slider = document.querySelector(".wz_gvp_slider");
    if (!slider || typeof Splide === 'undefined') return;

    new Splide(slider, {
        type: "slide",
        perPage: 4,
        perMove: 1,
        arrows: false,
        pagination: false,
        drag: false,
        keyboard: true,
        gap: '30px',
        breakpoints: {
            1200: {
                perPage: 2,
                drag: true,
                pagination: true,
            },
            768: {
                perPage: 1,
                drag: true,
                pagination: true,
            },
        },
    }).mount(); 
});

//Custom Pagination
document.addEventListener("DOMContentLoaded", () => {
    const sections = [
        ".industries-we-serve-wrap",
        ".why_choose_zetwerk_electronics_wrap",
        ".our_capabilities_wrapper",
        ".p-wcz-wrapper",
        ".p-jtm-wrapper",
        ".p-za-cards-wrapper",
        ".ks-advantage-wrap",
        ".prod-tza-wrapper",
        ".abt_ov_wrapper",
        ".card-container",
        ".hp_banner_insights",
        ".capabilities_zmd_wrapper",
        ".og-key-offerings-wrap",
        ".gf-scn-wrap",
    ];

    sections.forEach((selector) => {
        const wrapper = document.querySelector(selector);
        if (!wrapper) return;

        const scrollableContainer = wrapper.closest(".scrollable-container");
        if (!scrollableContainer) return;

        const paginationContainer = scrollableContainer.querySelector(".pagination_dots");
        if (!paginationContainer) return;

        const items = wrapper.children;
        if (items.length === 0) return;

        paginationContainer.innerHTML = ""; 

        Array.from(items).forEach(() => {
            const dot = document.createElement("span");
            dot.classList.add("dot");
            paginationContainer.appendChild(dot);
        });

        const dots = paginationContainer.querySelectorAll(".dot");
        if (dots.length > 0) dots[0].classList.add("active");

        const itemWidth = items[0].offsetWidth + 20;

        wrapper.addEventListener("scroll", () => {
            const scrollPosition = wrapper.scrollLeft;
            const activeIndex = Math.round(scrollPosition / itemWidth);

            dots.forEach((dot, index) => {
                dot.classList.toggle("active", index === activeIndex);
            });
        });

        dots.forEach((dot, index) => {
            dot.addEventListener("click", () => {
                wrapper.scrollTo({
                    left: index * itemWidth,
                    behavior: "smooth",
                });
            });
        });
    });
});

//Capabilities Slider
document.addEventListener("DOMContentLoaded", function () {
    const sliders = document.querySelectorAll(".capabilities_zmd_slider"); // Select all sliders

    if (!sliders.length) return;

    sliders.forEach((sliderElement) => {
        if (sliderElement.splide) {
            sliderElement.splide.destroy();
        }

        const splide = new Splide(sliderElement, {
            type: "loop",
            perPage: 4,
            perMove: 1,
            arrows: false,
            pagination: false,
            drag: false,
            gap: "30px",
            keyboard: true,
            breakpoints: {
                1200: {
                    perPage: 2,
                    padding: "10%",
                    drag: true,
                },
                768: {
                    perPage: 1,
                    drag: true,
                    pagination: true,
                },
            },
        });

        splide.mount(); 
    });
});

document.addEventListener("DOMContentLoaded", function () {
    const sliders = document.querySelectorAll(".pc_gallery_slider");

    sliders.forEach(function(slider) {
        new Splide(slider, {
            type: "loop",
            perPage: 3,
            perMove: 1,
            arrows: false,
            pagination: false,
            drag: true,
            gap: "30px",
            keyboard: true,
            breakpoints: {
                768: {
                    perPage: 1,
                    pagination: true,
                },
            },
        }).mount({});
    });
});


const listItems = document.querySelectorAll('.pd-hz-wrapper > li');

listItems.forEach(item => {
    const index = item.getAttribute('data-index');
    const correspondingGroup = document.querySelector(`svg g[data-index="${index}"]`);

    item.addEventListener('mouseenter', () => {
        if (correspondingGroup) {
            const pathFill = correspondingGroup.querySelector('.hc-change');
            const pathElements = correspondingGroup.querySelectorAll('.hc-path path, .hc-path rect');
            const circleElement = correspondingGroup.querySelector('.hc-path circle');

            if (pathFill) pathFill.style.fill = '#020B36'; 
            pathElements.forEach(el => {
                el.style.stroke = '#FFFFFF'; 
            });

            if (circleElement) {
                circleElement.style.stroke = '#FFFFFF'; 
            }
        }
    });

    item.addEventListener('mouseleave', () => {
        if (correspondingGroup) {
            const pathFill = correspondingGroup.querySelector('.hc-change');
            const pathElements = correspondingGroup.querySelectorAll('.hc-path path, .hc-path rect');
            const circleElement = correspondingGroup.querySelector('.hc-path circle');

            if (pathFill) pathFill.style.fill = ''; 
            pathElements.forEach(el => {
                el.style.stroke = ''; 
            });

            if (circleElement) {
                circleElement.style.stroke = '#020B36'; 
            }
        }
    });
});

// Homepage advantage section: mobile-only overlay slider (icon, text, pagination, arrows)
document.addEventListener("DOMContentLoaded", function () {
    const el = document.querySelector("#advantage-mobile-slider");
    if (!el || typeof Splide === "undefined") return;

    const mq = window.matchMedia("(max-width: 991px)");
    let instance = null;

    var advantageArrowSvg =
        '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="6" viewBox="0 0 14 6" fill="none" aria-hidden="true">' +
        '<path d="M13.2073 2.85156H0.707275" stroke="currentColor"/>' +
        '<path d="M3.20728 0.355469L0.707275 2.85156L3.20728 5.35156" stroke="currentColor"/>' +
        "</svg>";

    function patchAdvantageMobileArrows(root) {
        var prev = root.querySelector(".splide__arrow--prev");
        var next = root.querySelector(".splide__arrow--next");
        if (prev) {
            prev.innerHTML = advantageArrowSvg;
        }
        if (next) {
            next.innerHTML = advantageArrowSvg;
        }
    }

    function setupAdvantageMobileSplide() {
        if (mq.matches) {
            if (!instance) {
                instance = new Splide(el, {
                    type: "slide",
                    rewind: true,
                    perPage: 1,
                    perMove: 1,
                    arrows: true,
                    pagination: true,
                    gap: "12px",
                    speed: 400,
                }).mount();
                patchAdvantageMobileArrows(el);
            } else {
                instance.refresh();
                patchAdvantageMobileArrows(el);
            }
        } else if (instance) {
            instance.destroy();
            instance = null;
        }
    }

    setupAdvantageMobileSplide();
    mq.addEventListener("change", setupAdvantageMobileSplide);
});

//Homepage Insights Dropdown Mobile
document.addEventListener("DOMContentLoaded", function () {
    const dropdownToggle = document.querySelector(".dropdown-toggle");
    const tabMenu = document.querySelector(".tab-menu");

    if (!dropdownToggle || !tabMenu) {
        return;
    }

    const menuItems = tabMenu.querySelectorAll("li"); 

    dropdownToggle.addEventListener("click", function () {
        if (tabMenu.style.maxHeight === "0px" || tabMenu.style.maxHeight === "") {
            tabMenu.style.maxHeight = tabMenu.scrollHeight + "px"; 
        } else {
            tabMenu.style.maxHeight = "0px"; 
        }
    });

    document.addEventListener("click", function (event) {
        if (!dropdownToggle.contains(event.target) && !tabMenu.contains(event.target)) {
            tabMenu.style.maxHeight = "0px"; 
        }
    });

    menuItems.forEach(item => {
        item.addEventListener("click", function () {
            tabMenu.style.maxHeight = "0px"; 
        });
    });


});

//Insights Footer Header Links
document.addEventListener("DOMContentLoaded", function () {
    setTimeout(function () {
        var urlParams = new URLSearchParams(window.location.search);
        var activeTab = urlParams.get("tab"); 

        if (activeTab) {
            var targetTab = document.getElementById(activeTab);
            var contentWrapper = document.querySelector(".insights_content_wrapper"); 

            if (targetTab) {
                targetTab.click(); 
            }

            if (contentWrapper) {
                setTimeout(function () {
                    contentWrapper.scrollIntoView({ behavior: "smooth", block: "start" });
                }, 300); 
            }
        }
    }, 500); 
});

//Insights Filter and Load More Functionality
function fetchPosts(page = 1, industryId = '') {
    var activeTab = jQuery(".post-type-tab.active").data("type");
    var button = jQuery('.load-more-btn[data-post-type="' + activeTab + '"]');

    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        data: {
            action: "load_more_posts",
            page: page,
            post_type: activeTab,
            industry: industryId 
        },
        beforeSend: function () {
            button.text("Loading...");
        },
        success: function (response) {
            if (page === 1) {
                jQuery(".tab-items." + activeTab + " .insights_content_items").html(response);
            } else {
                jQuery(".tab-items." + activeTab + " .insights_content_items").append(response);
            }

            button.text("Load More");

            var maxPages = button.data("max-pages");

            if (!response.trim() || page >= maxPages) {
                button.hide();
            } else {
                button.show().data("page", page);
            }
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", status, error);
            alert("An error occurred while loading posts. Please try again.");
        }
    });
}

jQuery(document).ready(function ($) {
    // Helper to extract query params from URL
    function getUrlParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(window.location.search);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    $(document).on("change", "#industry-filter", function () {
        var selectedIndustry = $(this).val();
        fetchPosts(1, selectedIndustry); 
    });

    $(document).on("click", ".load-more-btn", function () {
        var nextPage = parseInt($(this).data("page")) + 1;
        var selectedIndustry = $("#industry-filter").val();
        fetchPosts(nextPage, selectedIndustry);
        $(this).data("page", nextPage);
    });

    fetchPosts(1);

    $(document).on("click", ".video-popup-trigger", function (e) {
        e.preventDefault();
        let videoUrl = $(this).attr("data-video-url");
    
        if (videoUrl) {
            $(".video-popup iframe").attr("src", videoUrl + "?autoplay=1&rel=0&mute=1");
            $(".video-popup").fadeIn().css("display", "flex");
        } else {
            console.error("Error: Video URL missing.");
        }
    });

    $(document).on("click", ".close-popup", function () {
        $(".video-popup").fadeOut();
        $(".video-popup iframe").attr("src", "");
    });

    $(document).on("click", ".video-popup", function (e) {
        if (!$(e.target).closest(".video-popup-content").length) {
            $(".video-popup").fadeOut();
            $(".video-popup iframe").attr("src", ""); 
        }
    });

    // On page load, check for industry parameter in URL
    function initializeWithUrlParams() {
        let initialIndustry = getUrlParameter('industry');
        if (initialIndustry) {
            $('#industry-filter').val(initialIndustry);
        }
    
        setTimeout(() => {
            let selectedIndustry = $('#industry-filter').val();
            fetchPosts(1, selectedIndustry);
        }, 100); 
    }
    
    initializeWithUrlParams();
});

// Vanilla JS to handle tab switching + sync filters
document.addEventListener('DOMContentLoaded', function() {
    const tabs = document.querySelectorAll('.post-type-tab');
    const tabItems = document.querySelectorAll('.tab-items');
    const industryFilter = document.getElementById('industry-filter'); 
    const selectedIndustries = {};

    if (industryFilter) {
        industryFilter.addEventListener('change', function () {
            const activeTab = document.querySelector('.post-type-tab.active');
            const tabType = activeTab ? activeTab.getAttribute('data-type') : '';
            if (tabType) {
                selectedIndustries[tabType] = industryFilter.value;
            }
        });
    }

    tabs.forEach(tab => {
        tab.addEventListener('click', function () {
            const tabType = tab.getAttribute('data-type');

            tabs.forEach(t => t.classList.remove('active'));
            tab.classList.add('active');

            tabItems.forEach(item => item.style.display = 'none');
            const activeTabItems = document.querySelector(`.tab-items.${tabType}`);
            if (activeTabItems) {
                activeTabItems.style.display = 'block';
            }

            if (industryFilter) {
                const savedFilter = selectedIndustries[tabType] || industryFilter.value;
                industryFilter.value = savedFilter;
                fetchPosts(1, savedFilter); 
            } else {
                fetchPosts(1, ''); 
            }
        });
    });

    // Initialize first tab active and load content
    const firstTab = document.querySelector('.post-type-tab');
    if (firstTab) {
        firstTab.classList.add('active');
        const firstTabItems = document.querySelector(`.tab-items.${firstTab.getAttribute('data-type')}`);
        if (firstTabItems) {
            firstTabItems.style.display = 'block';
        }
    }
});

//Insights Scroll to section
document.addEventListener("DOMContentLoaded", function () {
    const hash = window.location.hash;
    if (hash === "#insights-scroll") {
        const scrollTarget = document.querySelector(hash);
        if (scrollTarget) {

            setTimeout(() => {
                scrollTarget.scrollIntoView({
                    behavior: "smooth"
                });
            }, 300);
        }
    }
});


//Zetvidz Video Popup
document.addEventListener("DOMContentLoaded", function () {
    const popup = document.getElementById("videoPopup");
    const videoFrame = document.getElementById("popupVideo");
    const closeBtn = document.querySelector(".close-popup");

    document.body.addEventListener("click", function (event) {
        const target = event.target.closest(".video-popup-trigger");
        if (target) {
            event.preventDefault();
            const videoUrl = target.getAttribute("data-video-url");
            if (videoUrl) {
                videoFrame.src = videoUrl + "?autoplay=1";
                popup.classList.add("show");
            }
        }
    });

    // Close popup
    closeBtn.addEventListener("click", function () {
        popup.classList.remove("show");
        videoFrame.src = ""; 
    });

    // Close on clicking outside the modal
    popup.addEventListener("click", function (event) {
        if (event.target === popup) {
            popup.classList.remove("show");
            videoFrame.src = ""; 
        }
    });
});


//About Our Team Load More
document.addEventListener("DOMContentLoaded", function () {
    let readMoreBtn = document.getElementById("read-more-btn");
    let showLessBtn = document.getElementById("show-less-btn");
    let teamItems = document.querySelectorAll(".our_team_items");

    let isExpanded = false;

    function getInitialCount() {
        return window.innerWidth <= 1200 ? 8 : 10;
    }

    let initialCount = getInitialCount();

    function showInitialItems() {
        teamItems.forEach((item, index) => {
            item.style.display = index < initialCount ? "flex" : "none";
        });
        if (readMoreBtn) readMoreBtn.style.display = "flex";
        if (showLessBtn) showLessBtn.style.display = "none";
    }

    function showAllItems() {
        teamItems.forEach(item => item.style.display = "flex");
        if (readMoreBtn) readMoreBtn.style.display = "none";
        if (showLessBtn) showLessBtn.style.display = "flex";
    }

    if (readMoreBtn) {
        readMoreBtn.addEventListener("click", function () {
            isExpanded = true;
            showAllItems();
        });
    }

    if (showLessBtn) {
        showLessBtn.addEventListener("click", function () {
            isExpanded = false;
            showInitialItems();
        });
    }

    window.addEventListener("resize", function () {
        initialCount = getInitialCount();
        if (!isExpanded) {
            showInitialItems();
        }
    });

    showInitialItems();
});


// Careers Slider
document.addEventListener("DOMContentLoaded", function () {
    const sliders = document.querySelectorAll(".mtz_slider");

    sliders.forEach(function(slider) {
        new Splide(slider, {
            type: "loop",
            perPage: 1,
            perMove: 1,
            focus: "center",
            arrows: false,
            pagination: false,
            drag: true,
            gap: "120px",
            keyboard: true,
            padding: '16%',
            autoplay: true,          
            interval: 3000,          
            pauseOnHover: true,      
            pauseOnFocus: false,    
            resetProgress: false,   
            speed: 800, 
            autoHeight: true, 
            breakpoints: {
                768: {
                    perPage: 1,
                    padding: '5%',
                    arrows: false,
                    pagination: true,
                },
            },
        }).mount();
    });
});


document.addEventListener("DOMContentLoaded", function () {
    const sliders = document.querySelectorAll(".career-hfz-slider");

    sliders.forEach(function (slider) {
        const slides = slider.querySelectorAll('.splide__slide');
        const arrowPrev = slider.querySelector('.splide__arrow--prev');
        const arrowNext = slider.querySelector('.splide__arrow--next');
        const totalSlides = slides.length;

        const splide = new Splide(slider, {
            type: "loop",
            perPage: 5,
            perMove: 1,
            arrows: true, 
            pagination: false,
            drag: false,
            gap: "30px",
            keyboard: true,
            breakpoints: {
                1200: {
                    perPage: 2.5,
                    drag: true,
                },
                768: {
                    perPage: 1,
                    arrows: false, 
                    pagination: true,
                    drag: true,
                },
            },
        });

        function toggleArrows() {
            const perPage = splide.options.perPage;
            const shouldShow = totalSlides > perPage;

            if (arrowPrev && arrowNext) {
                arrowPrev.style.display = shouldShow ? "block" : "none";
                arrowNext.style.display = shouldShow ? "block" : "none";
            }
        }

        splide.on('mounted resize', toggleArrows);
        splide.mount();
    });
});

//Current Job Openings - Careers
document.addEventListener('DOMContentLoaded', () => {
    const departmentFilter = document.getElementById('departmentFilter');
    const locationFilter = document.getElementById('locationFilter');

    if (departmentFilter) departmentFilter.addEventListener('change', filterJobs);
    if (locationFilter) locationFilter.addEventListener('change', filterJobs);

    function filterJobs() {
        const department = departmentFilter ? departmentFilter.value : 'all';
        const location = locationFilter ? locationFilter.value : 'all';
        const jobs = document.querySelectorAll('.job-listing');

        jobs.forEach(job => {
            const jobDepartment = job.getAttribute('data-department');
            const jobLocation = job.getAttribute('data-location');

            if ((department === 'all' || jobDepartment === department) &&
                (location === 'all' || jobLocation === location)) {
                job.style.display = 'flex';
            } else {
                job.style.display = 'none';
            }
        });
    }
});

//Career banner job search
function searchJobs() {
    var query = document.getElementById("jobSearch").value.trim();
    query = query.replace(/[^a-zA-Z0-9\s-]/g, "");

    if (query) {
        var searchUrl = `https://zetwerk.sensehq.com/careers/jobs?page=0&pageSize=10&department=&location=&title=${encodeURIComponent(query)}&sortBy=&orderBy=ASC&minExp=0&maxExp=100&jobType=&workplaceType=`;
        window.open(searchUrl, '_blank');
    }
}

function handleKeyPress(event) {
    if (event.key === "Enter") {
        searchJobs();
    }
}

// Career job list view more
document.addEventListener('DOMContentLoaded', function () {
    const viewMoreBtn = document.getElementById('viewMoreBtn');
    if (viewMoreBtn) {
        viewMoreBtn.addEventListener('click', function () {
            document.querySelectorAll('.hidden-job').forEach(el => {
                el.classList.remove('hidden-job');
            });

            document.querySelector('.upload-resume-container').classList.remove('career-hidden');
            viewMoreBtn.style.display = 'none';
        });
    }
});


// Zetwerk Milestones - Read More Button
document.addEventListener("DOMContentLoaded", () => {
    const list = document.getElementById("milestoneList");
    const btn = document.getElementById("readMoreBtn");
    const btnText = btn.querySelector(".btn-text");
    const maxVisibleItems = 7;
  
    if (list.children.length <= maxVisibleItems) {
      btn.style.display = "none";
    } else {
      list.classList.add("collapsed");
    }
  
    btn.addEventListener("click", () => {
      list.classList.toggle("collapsed");
      btn.classList.toggle("expanded");
  
      const isCollapsed = list.classList.contains("collapsed");
      btnText.textContent = isCollapsed ? "Read More" : "Show Less";
    });
});

// Electronics Map Mob Read More Button
document.addEventListener("DOMContentLoaded", () => {
    const mapList = document.getElementById("electroMapList");
    const mapBtn = document.getElementById("mapReadMoreBtn");
    const mapBtnText = mapBtn.querySelector(".btn-text");
    const maxVisibleItems = 3;
  
    if (mapList.children.length <= maxVisibleItems) {
      mapBtn.style.display = "none";
    } else {
      mapList.classList.add("collapsed");
    }
  
    mapBtn.addEventListener("click", () => {
      mapList.classList.toggle("collapsed");
      mapBtn.classList.toggle("expanded");
  
      const isCollapsed = mapList.classList.contains("collapsed");
      mapBtnText.textContent = isCollapsed ? "Read More" : "Show Less";
    });
});


// Infrastructure Accordion
document.addEventListener("DOMContentLoaded", () => {
  const accordionWraps = document.querySelectorAll(".pc-accordion-wrap");

  accordionWraps.forEach(wrap => {
    const accordionHeaders = wrap.querySelectorAll(".accordion__item--header");
    const imageEl = wrap.querySelector(".main-accordion-image");

    if (!imageEl) return;

    accordionHeaders.forEach(header => {
      header.addEventListener("click", () => {
        const newImage = header.getAttribute("data-image");
        if (!newImage || newImage === imageEl.src) return;

        imageEl.classList.add("fade-out");

        const onImageLoad = () => {
          imageEl.classList.remove("fade-out");
          imageEl.removeEventListener("load", onImageLoad);
        };

        setTimeout(() => {
          imageEl.src = newImage;
          imageEl.addEventListener("load", onImageLoad, { once: true });
        }, 300);
      });
    });
  });
});

// Og Milestone Slider (only pair tab menus with panels inside the same .tab-wrapper that contains .og-slider).
// A previous global `.tab-items` query hid every panel site-wide except the first — breaking multi-tab pages (e.g. Capabilities).
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll(".tab-wrapper").forEach(function (tabWrapper) {
    if (!tabWrapper.querySelector(".og-slider")) return;

    var tabMenus = tabWrapper.querySelectorAll(".tab-menu li");
    var tabItems = tabWrapper.querySelectorAll(".tab-content > .tab-items");
    if (!tabMenus.length || !tabItems.length) return;

    tabItems.forEach(function (item, index) {
      item.style.display = index === 0 ? "block" : "none";
    });

    tabMenus.forEach(function (tab, index) {
      tab.addEventListener("click", function () {
        tabMenus.forEach(function (t) {
          t.classList.remove("tab-active");
        });
        tab.classList.add("tab-active");

        tabItems.forEach(function (item, i) {
          item.style.display = i === index ? "block" : "none";
        });

        var panel = tabItems[index];
        if (!panel) return;
        panel.querySelectorAll(".og-slider").forEach(function (sliderEl) {
          var splideInstance = sliderEl.splide;
          if (splideInstance) splideInstance.refresh();
        });
      });
    });
  });

  const allSliders = document.querySelectorAll(".og-slider");

  allSliders.forEach(function (slider) {
    const slides = slider.querySelectorAll(".splide__slide");
    const slideCount = slides.length;
    const arrowsElement = slider.querySelector(".splide__arrows");
  
    const options = {
      type: slideCount > 4 ? "loop" : "slide",
      perPage: 4,
      perMove: 1,
      arrows: true, // always enable in config, control visibility via JS
      pagination: false,
      drag: false,
      keyboard: true,
      gap: '30px',
      breakpoints: {
        1200: {
          perPage: 2,
          drag: true,
          arrows: true,
        },
        768: {
          perPage: 1,
          drag: true,
          arrows: true,
        },
      },
    };
  
    const splide = new Splide(slider, options);
    slider.splide = splide;
    splide.mount();
  
    // Custom arrow visibility control
    function updateArrowsVisibility() {
      const isMobile = window.innerWidth <= 1200;
      if (arrowsElement) {
        if (slideCount <= 4 && !isMobile) {
          arrowsElement.style.display = "none";
        } else {
          arrowsElement.style.display = "";
        }
      }
    }
  
    updateArrowsVisibility();
    window.addEventListener("resize", updateArrowsVisibility);
  });
});

// Tab color change — infrastructure page only (do not attach to every .tab-menu on the site).
document.addEventListener('DOMContentLoaded', function () {
    var section = document.querySelector('.infrastructure-tab');
    if (!section) return;

    var tabs = section.querySelectorAll('.tab-menu li');
    if (!tabs.length) return;

    function updateTabColors() {
      var activeIndex = Array.prototype.slice.call(tabs).findIndex(function (tab) {
        return tab.classList.contains('tab-active');
      });

      section.classList.remove('dark-bg', 'light-bg');

      if (activeIndex === 0 || activeIndex === 1) {
        section.classList.add('dark-bg');
      } else {
        section.classList.add('light-bg');
      }
    }

    updateTabColors();

    tabs.forEach(function (tab) {
      tab.addEventListener('click', function () {
        tabs.forEach(function (t) {
          t.classList.remove('tab-active');
        });
        tab.classList.add('tab-active');
        updateTabColors();
      });
    });
});


//Tab Nested 
document.querySelectorAll('.lspd-wrapper, .hp-wrapper').forEach(wrapper => {
  const tabs = wrapper.querySelectorAll('.projectTabs li');
  const contents = wrapper.querySelectorAll('.gf-tab-content');

  tabs.forEach(tab => {
    tab.addEventListener('click', function() {
      // Remove active class from all tabs in this wrapper
      tabs.forEach(el => el.classList.remove('tab-active'));
      this.classList.add('tab-active');

      // Hide all content blocks in this wrapper
      contents.forEach(content => content.classList.remove('active'));

      // Show corresponding content block in this wrapper
      const target = this.getAttribute('data-target');
      const targetContent = wrapper.querySelector(`#${target}`);
      if (targetContent) targetContent.classList.add('active');
    });
  });
});

//Oil Gas Slider
document.addEventListener("DOMContentLoaded", function () {
    const sliders = document.querySelectorAll(".oil-gas-slider");

    sliders.forEach(function (slider) {
        const splideInstance = new Splide(slider, {
            type: "loop",
            perPage: 4,
            perMove: 1,
            arrows: true,
            pagination: false,
            keyboard: true,
            gap: '30px',
            breakpoints: {
                1200: {
                    perPage: 2,
                    drag: true,
                },
                768: {
                    perPage: 1,
                    drag: true,
                },
            },
        }).mount();

        // Attach instance to DOM node
        slider.splide = splideInstance;
    });

    // Use MutationObserver to detect visibility changes of .tab-items
    const tabContents = document.querySelectorAll(".tab-content .tab-items");

    const observer = new MutationObserver(function (mutationsList) {
        mutationsList.forEach(function (mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                const target = mutation.target;
                if (target.style.display !== 'none') {
                    const splides = target.querySelectorAll(".splide");
                    splides.forEach(function (sliderEl) {
                        if (sliderEl.splide) {
                            sliderEl.splide.refresh();
                        }
                    });
                }
            }
        });
    });

    tabContents.forEach(function (tabItem) {
        observer.observe(tabItem, { attributes: true, attributeFilter: ['style'] });
    });
});