(function ($) {
  "use strict";

  /* ==========================================================================
     Shared State
     ========================================================================== */

  var $win = $(window);
  var $body = $("body");
  var $header = $("[data-as-header]");
  var aboutSwiper = null;
  var companySwiper = null;

  /* ==========================================================================
     Theme Mode
     ========================================================================== */

  function initThemeMode() {
    var savedMode = window.localStorage ? window.localStorage.getItem("as-theme-mode") : null;

    if (savedMode === "dark") {
      $body.addClass("as-dark-mode");
    }

    updateThemeIcon();

    $(".as-theme-toggle").on("click", function () {
      $body.addClass("as-theme-transitioning");
      $body.toggleClass("as-dark-mode");

      if (window.localStorage) {
        window.localStorage.setItem("as-theme-mode", $body.hasClass("as-dark-mode") ? "dark" : "light");
      }

      updateThemeIcon();

      window.setTimeout(function () {
        $body.removeClass("as-theme-transitioning");
      }, 700);
    });
  }

  /* Theme Toggle Icon */

  function updateThemeIcon() {
    var $icon = $(".as-theme-toggle i");
    var isDarkMode = $body.hasClass("as-dark-mode");
    var $logos = $(".as-brand-logo, .as-nav-drawer-logo");
    var nextLogo = isDarkMode ? $logos.first().data("dark-logo") : $logos.first().data("light-logo");

    $icon.toggleClass("fa-regular", !isDarkMode);
    $icon.toggleClass("fa-solid", isDarkMode);
    $icon.toggleClass("fa-sun", isDarkMode);
    $icon.toggleClass("fa-moon", !isDarkMode);

    if ($body.hasClass("as-theme-transitioning") && typeof gsap !== "undefined") {
      gsap.to($logos, {
        opacity: 0,
        duration: 0.16,
        ease: "power2.out",
        onComplete: function () {
          $logos.attr("src", nextLogo);
          gsap.to($logos, { opacity: 1, duration: 0.28, ease: "power2.out" });
        }
      });
      return;
    }

    $logos.attr("src", nextLogo);
  }

  /* ==========================================================================
     Navbar Scroll Effect
     ========================================================================== */

  function updateHeader() {
    $header.toggleClass("as-header-scrolled", $win.scrollTop() > 12);
  }

  /* ==========================================================================
     Header Interactions
     ========================================================================== */

  function bindMenu() {
    var $nav = $(".as-main-nav");
    var $menuButton = $("[data-as-menu]");
    var $languageWrap = $(".as-language-wrap");
    var $themeToggle = $(".as-theme-toggle");
    var $headerActions = $(".as-header-actions").first();
    var $navHome = $nav.parent();
    var mobileQuery = window.matchMedia("(max-width: 1024px)");
    var lastFocusedElement = null;

    if ($nav.length && !$nav.attr("id")) {
      $nav.attr("id", "as-primary-navigation");
    }

    $menuButton.attr({
      "aria-controls": $nav.attr("id"),
      "aria-expanded": "false"
    });

    var themeData = window.alfasmartTheme || {};
    var homeUrl = themeData.homeUrl || "/";
    var lightLogo = themeData.lightLogo || "";
    var darkLogo = themeData.darkLogo || lightLogo;

    if (!$nav.find(".as-nav-drawer-head").length) {
      $nav.prepend(
        '<div class="as-nav-drawer-head">' +
          '<a class="as-nav-drawer-brand" href="' + homeUrl + '" aria-label="ALFA Smart home">' +
            '<img src="' + lightLogo + '" data-light-logo="' + lightLogo + '" data-dark-logo="' + darkLogo + '" alt="ALFA Smart" class="as-nav-drawer-logo">' +
          '</a>' +
          '<div class="as-nav-drawer-tools">' +
            '<div class="as-nav-drawer-controls"></div>' +
            '<button class="as-nav-close" type="button" aria-label="Close menu" data-as-menu-close>' +
              '<i class="fa-solid fa-xmark" aria-hidden="true"></i>' +
            '</button>' +
          '</div>' +
        '</div>'
      );
    }

    var $drawerControls = $nav.find(".as-nav-drawer-controls");
    function syncDrawerHeaderAssets() {
      var $siteLogo = $(".as-brand-logo").first();
      var $drawerLogo = $nav.find(".as-nav-drawer-logo");

      if (!$siteLogo.length || !$drawerLogo.length) {
        return;
      }

      $drawerLogo.attr({
        src: $siteLogo.attr("src"),
        "data-light-logo": $siteLogo.attr("data-light-logo"),
        "data-dark-logo": $siteLogo.attr("data-dark-logo")
      });
    }

    function syncActiveNavigation() {
      function normalizePath(path) {
        path = (path || "/").replace(/\/+$/, "") || "/";
        return decodeURIComponent(path).toLowerCase();
      }

      function lastPathSegment(path) {
        var cleaned = normalizePath(path).replace(/^\/|\/$/g, "");
        var parts = cleaned ? cleaned.split("/") : [];

        return parts.length ? parts[parts.length - 1] : "";
      }

      function pathsMatch(targetPath, activePath) {
        var targetLast = lastPathSegment(targetPath);
        var activeLast = lastPathSegment(activePath);

        return targetPath === activePath || (targetLast && activeLast && targetLast === activeLast);
      }

      var currentPath = normalizePath(window.location.pathname);
      var currentMatch = currentPath + window.location.search;
      var themeData = window.alfasmartTheme || {};
      var homeUrl = new URL(themeData.homeUrl || "/", window.location.href);
      var homePath = normalizePath(homeUrl.pathname);
      var isHome = currentPath === homePath && !window.location.search;
      var bestMatch = null;
      var bestLength = -1;

      $(".as-main-nav .as-nav-link").each(function () {
        var $link = $(this);
        var href = ($link.attr("href") || "").split("#")[0];
        var wasServerActive = $link.is("[data-current-nav='true'], .current-menu-item, .current_page_item");
        $link.removeClass("as-nav-active").removeAttr("aria-current");

        if (!href) {
          return;
        }

        var targetUrl = new URL(href, window.location.href);
        var targetPath = normalizePath(targetUrl.pathname);
        var targetMatch = targetPath + targetUrl.search;

        if (isHome) {
          if (targetPath === homePath && !targetUrl.search && !bestMatch) {
            bestMatch = $link;
            bestLength = targetPath.length;
          }
          return;
        }

        if (targetMatch === currentMatch && targetMatch.length > bestLength) {
          bestMatch = $link;
          bestLength = targetMatch.length;
          return;
        }

        if (targetPath !== "/" && pathsMatch(targetPath, currentPath) && targetPath.length > bestLength) {
          bestMatch = $link;
          bestLength = targetPath.length;
          return;
        }

        if (wasServerActive && bestLength < 0) {
          bestMatch = $link;
          bestLength = targetPath.length;
        }
      });

      if (bestMatch) {
        bestMatch.addClass("as-nav-active").attr("aria-current", "page");
      }
    }

    function getFocusableItems() {
      return $nav
        .find('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])')
        .filter(":visible");
    }

    function moveNode($node, $target, method) {
      if ($node.length && !$node.parent().is($target)) {
        $node.detach()[method]($target);
      }
    }

    function openMenu() {
      if ($body.hasClass("as-menu-open")) {
        return;
      }

      lastFocusedElement = document.activeElement;
      $body.addClass("as-menu-open");
      $nav.attr("aria-hidden", "false");
      $menuButton.attr("aria-expanded", "true");

      window.setTimeout(function () {
        var $focusTarget = getFocusableItems().first();

        if (mobileQuery.matches && $focusTarget.length) {
          $focusTarget.trigger("focus");
        }
      }, 120);
    }

    function closeMenu(restoreFocus) {
      if (!$body.hasClass("as-menu-open")) {
        return;
      }

      $body.removeClass("as-menu-open");
      $nav.attr("aria-hidden", mobileQuery.matches ? "true" : "false");
      $menuButton.attr("aria-expanded", "false");

      if (restoreFocus && lastFocusedElement && typeof lastFocusedElement.focus === "function") {
        window.setTimeout(function () {
          lastFocusedElement.focus();
        }, 80);
      }
    }

    function syncMenuMode() {
      closeMenu(false);

      if (mobileQuery.matches) {
        moveNode($nav, $body, "appendTo");
      } else if ($navHome.length && !$nav.parent().is($navHome)) {
        $nav.detach().insertBefore($headerActions);
      }

      if (mobileQuery.matches) {
        moveNode($themeToggle, $drawerControls, "prependTo");
        moveNode($languageWrap, $drawerControls, "appendTo");
      } else {
        moveNode($themeToggle, $headerActions, "prependTo");
        if ($languageWrap.length && !$languageWrap.parent().is($headerActions)) {
          $languageWrap.detach().insertAfter($themeToggle);
        }
      }

      $nav.attr("aria-hidden", mobileQuery.matches ? "true" : "false");
      syncDrawerHeaderAssets();
    }

    syncActiveNavigation();
    syncMenuMode();

    $menuButton.on("click", function (event) {
      event.stopPropagation();

      if ($body.hasClass("as-menu-open")) {
        closeMenu(true);
      } else {
        openMenu();
      }
    });

    $nav.on("click", "[data-as-menu-close]", function () {
      closeMenu(true);
    });

    $nav.on("click", "a", function () {
      closeMenu(false);
    });

    $("[data-as-language]").on("click", function (event) {
      event.stopPropagation();
      $languageWrap.not($(this).closest(".as-language-wrap")).removeClass("as-language-open");
      $(this).closest(".as-language-wrap").toggleClass("as-language-open");
    });

    $(".as-language-menu").on("click", function (event) {
      event.stopPropagation();
    });

    $(document).on("mousedown", function (event) {
      var clickedInsideNav = $nav[0] && $nav[0].contains(event.target);
      var clickedMenuButton = $menuButton[0] && $menuButton[0].contains(event.target);

      if ($body.hasClass("as-menu-open") && !clickedInsideNav && !clickedMenuButton) {
        closeMenu(false);
      }
    });

    $(document).on("click", function () {
      $languageWrap.removeClass("as-language-open");
    });

    $(document).on("keydown", function (event) {
      if (event.key === "Escape") {
        closeMenu(true);
        $languageWrap.removeClass("as-language-open");
      }

      if (event.key === "Tab" && $body.hasClass("as-menu-open") && mobileQuery.matches) {
        var $focusable = getFocusableItems();
        var firstItem = $focusable[0];
        var lastItem = $focusable[$focusable.length - 1];

        if (!$focusable.length) {
          return;
        }

        if (event.shiftKey && document.activeElement === firstItem) {
          event.preventDefault();
          lastItem.focus();
        } else if (!event.shiftKey && document.activeElement === lastItem) {
          event.preventDefault();
          firstItem.focus();
        }
      }
    });

    if (mobileQuery.addEventListener) {
      mobileQuery.addEventListener("change", syncMenuMode);
    } else if (mobileQuery.addListener) {
      mobileQuery.addListener(syncMenuMode);
    }
  }

  /* ==========================================================================
     About Vision Slider
     ========================================================================== */

  function initAboutSwiper() {
    if (typeof Swiper === "undefined" || aboutSwiper) {
      return;
    }

    function updateAboutVisionContent(swiper) {
      var $activeSlide = $(swiper.slides[swiper.activeIndex]);
      var title = $activeSlide.data("vision-title");
      var copy = $activeSlide.data("vision-copy");
      var $cardContent = $(".as-vision-card-title, .as-vision-card-copy");

      if (!title || !copy) {
        return;
      }

      if (typeof gsap !== "undefined") {
        gsap.to($cardContent, {
          opacity: 0,
          y: -4,
          duration: 0.18,
          ease: "power2.out",
          onComplete: function () {
            $(".as-vision-card-title").text(title);
            $(".as-vision-card-copy").text(copy);
            gsap.to($cardContent, {
              opacity: 1,
              y: 0,
              duration: 0.26,
              ease: "power2.out"
            });
          }
        });
      } else {
        $(".as-vision-card-title").text(title);
        $(".as-vision-card-copy").text(copy);
      }
    }

    aboutSwiper = new Swiper(".as-about-swiper", {
      slidesPerView: 1,
      speed: 620,
      loop: true,
      grabCursor: true,
      effect: "creative",
      creativeEffect: {
        prev: {
          opacity: 0,
          translate: ["-6%", 0, -80]
        },
        next: {
          opacity: 0,
          translate: ["6%", 0, -80]
        }
      },
      autoplay: {
        delay: 2000,
        disableOnInteraction: false
      },
      pagination: {
        el: ".as-about-swiper-pagination",
        clickable: true
      },
      on: {
        init: function () {
          updateAboutVisionContent(this);
        },
        slideChangeTransitionStart: function () {
          updateAboutVisionContent(this);
        }
      }
    });
  }

  /* ==========================================================================
     Companies Slider
     ========================================================================== */

  function initCompanySwiper() {
    if (typeof Swiper === "undefined") {
      return;
    }

    var shouldUseSwiper = window.matchMedia("(max-width: 1024px)").matches;

    if (shouldUseSwiper && !companySwiper) {
      companySwiper = new Swiper(".as-company-swiper", {
        slidesPerView: 1.08,
        spaceBetween: 18,
        speed: 750,
        grabCursor: true,
        resistanceRatio: 0.78,
        watchSlidesProgress: true,
        keyboard: {
          enabled: true
        },
        mousewheel: {
          forceToAxis: true,
          sensitivity: 0.5
        },
        breakpoints: {
          640: {
            slidesPerView: 2.05,
            spaceBetween: 22
          },
          900: {
            slidesPerView: 3.05,
            spaceBetween: 24
          }
        }
      });
    }

    if (!shouldUseSwiper && companySwiper) {
      companySwiper.destroy(true, true);
      companySwiper = null;
    }
  }

  /* ==========================================================================
     GSAP Animations
     ========================================================================== */

  function initGsap() {
    if (typeof gsap === "undefined") {
      $(".as-reveal").css({ opacity: 1, transform: "none" });
      return;
    }

    if (typeof ScrollTrigger !== "undefined") {
      gsap.registerPlugin(ScrollTrigger);
    }

    /* GSAP Reveal Animation */

    gsap.set(".as-reveal", { y: 34, opacity: 0 });

    $(".as-reveal").each(function () {
      var revealConfig = {
        y: 0,
        opacity: 1,
        duration: 0.95,
        ease: "power3.out"
      };

      if (typeof ScrollTrigger !== "undefined") {
        revealConfig.scrollTrigger = {
          trigger: this,
          start: "top 86%",
          once: true
        };
      }

      gsap.to(this, revealConfig);
    });

    /* Hero Intro Animation */

    gsap.fromTo(".as-hero-bg", { scale: 1.06 }, {
      scale: 1,
      duration: 1.65,
      ease: "power2.out"
    });

    if (typeof ScrollTrigger !== "undefined") {
      /* Hero Parallax */

      gsap.to(".as-hero-bg", {
        yPercent: 9,
        ease: "none",
        scrollTrigger: {
          trigger: ".as-hero-section",
          start: "top top",
          end: "bottom top",
          scrub: true
        }
      });

      $win.on("load", function () {
        ScrollTrigger.refresh();
      });

      /* Value Banner Parallax */

      gsap.to(".as-value-bg", {
        yPercent: 5,
        ease: "none",
        scrollTrigger: {
          trigger: ".as-value-banner",
          start: "top bottom",
          end: "bottom top",
          scrub: true
        }
      });

      /* Orbit Section Parallax */

      gsap.to(".as-orbit-arc", {
        y: -42,
        ease: "none",
        scrollTrigger: {
          trigger: ".as-orbit-section",
          start: "top bottom",
          end: "bottom top",
          scrub: true
        }
      });
    }
  }

  /* ==========================================================================
     Animated Counters
     ========================================================================== */

  function initCounters() {
    var counters = $("[data-as-counter]").toArray();

    if (!counters.length) {
      return;
    }

    function animateCounter(counter) {
      if (counter.dataset.counted === "true") {
        return;
      }

      counter.dataset.counted = "true";

      var target = Number(counter.dataset.target || counter.textContent.replace(/\D/g, ""));
      var state = { value: 0 };

      if (typeof gsap !== "undefined") {
        gsap.to(state, {
          value: target,
          duration: 1.55,
          ease: "power3.out",
          onUpdate: function () {
            counter.textContent = Math.floor(state.value).toLocaleString("en-US");
          },
          onComplete: function () {
            counter.textContent = target.toLocaleString("en-US");
          }
        });
        return;
      }

      counter.textContent = target.toLocaleString("en-US");
    }

    if (typeof ScrollTrigger !== "undefined") {
      counters.forEach(function (counter) {
        ScrollTrigger.create({
          trigger: counter.closest("[data-as-counter-scope]") || counter,
          start: "top 92%",
          once: true,
          onEnter: function () {
            animateCounter(counter);
          }
        });
      });
      return;
    }

    var observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          $(entry.target).find("[data-as-counter]").addBack("[data-as-counter]").each(function () {
            animateCounter(this);
          });
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.18 });

    counters.forEach(function (counter) {
      observer.observe(counter.closest("[data-as-counter-scope]") || counter);
    });
  }

  /* ==========================================================================
     Fancybox Video Modal
     ========================================================================== */

  function initFancybox() {
    if (typeof Fancybox === "undefined") {
      return;
    }

    Fancybox.bind("[data-fancybox]", {
      animated: true,
      dragToClose: true,
      hideScrollbar: false,
      Html: {
        video: {
          autoplay: true,
          controls: true
        }
      },
      Toolbar: {
        display: {
          left: [],
          middle: [],
          right: ["close"]
        }
      }
    });
  }

  /* ==========================================================================
     Magnetic Hover Interaction
     ========================================================================== */

  function bindMagneticHover() {
    if (window.matchMedia("(pointer: coarse)").matches || typeof gsap === "undefined") {
      return;
    }

    $(".as-magnetic").each(function () {
      var element = this;
      var $element = $(element);

      $element.on("mousemove", function (event) {
        var rect = element.getBoundingClientRect();
        var moveX = (event.clientX - rect.left - rect.width / 2) * 0.2;
        var moveY = (event.clientY - rect.top - rect.height / 2) * 0.28;

        gsap.to(element, {
          x: moveX,
          y: moveY,
          duration: 0.35,
          ease: "power3.out"
        });
      });

      $element.on("mouseleave", function () {
        gsap.to(element, {
          x: 0,
          y: 0,
          duration: 0.55,
          ease: "elastic.out(1, 0.45)"
        });
      });
    });
  }

  /* ==========================================================================
     Card Hover Tilt
     ========================================================================== */

  function bindCardTilt() {
    if (window.matchMedia("(pointer: coarse)").matches || typeof gsap === "undefined") {
      return;
    }

    $(".as-feature-card, .as-company-card, .as-service-card, .as-service-detail-card, .as-service-choice-card, .as-service-plan-card").on("mousemove", function (event) {
      var rect = this.getBoundingClientRect();
      var rotateX = -((event.clientY - rect.top) / rect.height - 0.5) * 3.5;
      var rotateY = ((event.clientX - rect.left) / rect.width - 0.5) * 3.5;

      gsap.to(this, {
        y: -5,
        scale: 1.006,
        rotateX: rotateX,
        rotateY: rotateY,
        transformPerspective: 900,
        transformOrigin: "center",
        duration: 0.35,
        ease: "power2.out"
      });
    }).on("mouseleave", function () {
      gsap.to(this, {
        y: 0,
        scale: 1,
        rotateX: 0,
        rotateY: 0,
        duration: 0.5,
        ease: "power3.out"
      });
    });
  }

  /* ==========================================================================
     Contact Form Interaction
     ========================================================================== */

  function bindContactForm() {
    $(".as-contact-form").not(".wpcf7-form").on("submit", function (event) {
      event.preventDefault();

      var $button = $(this).find(".as-form-button");
      var originalText = $button.text();

      $button.text("Message Ready").prop("disabled", true);

      if (typeof gsap !== "undefined") {
        gsap.fromTo($button, { scale: 0.985 }, { scale: 1, duration: 0.45, ease: "elastic.out(1, 0.45)" });
      }

      window.setTimeout(function () {
        $button.text(originalText).prop("disabled", false);
      }, 1800);
    });
  }

  /* ==========================================================================
     View Transition Fallback
     ========================================================================== */

  function initPageTransitions() {
    var reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    if (reduceMotion) {
      return;
    }

    $(document).on("click", "a[href]", function (event) {
      var link = this;
      var href = link.getAttribute("href");

      if (!href || href.charAt(0) === "#" || link.target || link.hasAttribute("download") || $(link).is("[data-fancybox]")) {
        return;
      }

      if (/^(mailto:|tel:|javascript:)/i.test(href)) {
        return;
      }

      var targetUrl = new URL(href, window.location.href);

      if (targetUrl.href === window.location.href || targetUrl.origin !== window.location.origin || targetUrl.pathname === window.location.pathname && targetUrl.hash) {
        return;
      }

      if ("startViewTransition" in document) {
        return;
      }

      event.preventDefault();
      $body.addClass("as-page-leaving");

      window.setTimeout(function () {
        window.location.href = targetUrl.href;
      }, 180);
    });
  }

  /* ==========================================================================
     Initialization
     ========================================================================== */

  $(function () {
    initThemeMode();
    updateHeader();
    bindMenu();
    initPageTransitions();
    bindContactForm();
    initAboutSwiper();
    initCompanySwiper();
    initGsap();
    initCounters();
    initFancybox();
    bindMagneticHover();
    bindCardTilt();

    $win.on("scroll", updateHeader);
    $win.on("resize", initCompanySwiper);
  });
})(jQuery);
