(function ($) {
  "use strict";

  // ═══════════════════════════════════════════════════
  //  GSAP Navigation Reveal Engine
  // ═══════════════════════════════════════════════════

  var isDesktop = function () { return window.innerWidth >= 1226; };
  var hasGSAP = function () { return typeof gsap !== "undefined"; };

  // ───────────────────────────────────────────────────
  //  1. STAGGERED ENTRANCE — Menu items cascade in
  // ───────────────────────────────────────────────────
  function revealMenuItems() {
    if (!hasGSAP() || !isDesktop()) return;

    initActiveIndicator();
    initDropdownAnim();
    initMegaAnim();
  }



  // ───────────────────────────────────────────────────
  //  3. ACTIVE INDICATOR — Animated underline follows hover
  // ───────────────────────────────────────────────────
  function initActiveIndicator() {
    if (!hasGSAP()) return;

    var $nav = $(".cs-nav_list").first();
    if (!$nav.length) return;

    // Don't re-inject
    if ($nav.find(".cs-nav-indicator").length) return;

    var $indicator = $('<span class="cs-nav-indicator"></span>');
    $nav.css("position", "relative").append($indicator);

    $indicator.css({
      position: "absolute",
      bottom: 0,
      left: 0,
      height: "1px",
      width: "0px",
      background: "currentColor",
      pointerEvents: "none",
      opacity: 0,
      transition: "none"
    });

    var indicator = $indicator[0];
    var $items = $nav.children("li");

    $items.on("mouseenter.csIndicator", function () {
      var $this = $(this);
      var $a = $this.children("a");
      if (!$a.length) return;

      var navRect = $nav[0].getBoundingClientRect();
      var aRect = $a[0].getBoundingClientRect();

      gsap.to(indicator, {
        left: aRect.left - navRect.left,
        width: aRect.width,
        opacity: 0.6,
        duration: 0.4,
        ease: "power3.out",
        overwrite: true
      });
    });

    $nav.on("mouseleave.csIndicator", function () {
      gsap.to(indicator, {
        opacity: 0,
        width: 0,
        duration: 0.3,
        ease: "power2.inOut",
        overwrite: true
      });
    });
  }

  // ───────────────────────────────────────────────────
  //  4. DROPDOWN REVEAL — Standard submenus
  //     Works WITH the CSS opacity/visibility system
  // ───────────────────────────────────────────────────
  function initDropdownAnim() {
    if (!hasGSAP()) return;

    $(".cs-nav_list > li:not(.cs-mega_menu)").each(function () {
      var $li = $(this);
      var $sub = $li.children("ul");
      if (!$sub.length) return;

      var $subItems = $sub.children("li");

      // Pre-set sub-items for stagger animation
      gsap.set($subItems.toArray(), {
        y: 10,
        opacity: 0
      });

      $li.on("mouseenter.csDrop", function () {
        gsap.to($subItems.toArray(), {
          y: 0,
          opacity: 1,
          duration: 0.4,
          stagger: 0.04,
          ease: "power3.out",
          overwrite: true,
          delay: 0.08
        });
      });

      $li.on("mouseleave.csDrop", function () {
        gsap.to($subItems.toArray(), {
          y: 10,
          opacity: 0,
          duration: 0.2,
          stagger: 0.02,
          ease: "power2.in",
          overwrite: true
        });
      });
    });
  }

  // ───────────────────────────────────────────────────
  //  5. MEGA MENU REVEAL — Curtain wipe with column stagger
  // ───────────────────────────────────────────────────
  function initMegaAnim() {
    if (!hasGSAP()) return;

    $(".cs-nav_list > li.cs-mega_menu").each(function () {
      var $li = $(this);
      var $sub = $li.children("ul");
      if (!$sub.length) return;

      var $cols = $sub.children("li");

      gsap.set($cols.toArray(), {
        y: 25,
        opacity: 0
      });

      $li.on("mouseenter.csMega", function () {
        gsap.to($cols.toArray(), {
          y: 0,
          opacity: 1,
          duration: 0.5,
          stagger: 0.06,
          ease: "power4.out",
          overwrite: true,
          delay: 0.1
        });
      });

      $li.on("mouseleave.csMega", function () {
        gsap.to($cols.toArray(), {
          y: 25,
          opacity: 0,
          duration: 0.25,
          stagger: 0.02,
          ease: "power2.in",
          overwrite: true
        });
      });
    });
  }

  // ───────────────────────────────────────────────────
  //  6. MOBILE FULLSCREEN MENU — Modern overlay with stagger
  // ───────────────────────────────────────────────────

  /**
   * Open the mobile fullscreen menu.
   */
  function openMobileMenu($toggle, $list) {
    $toggle.addClass("cs-toggle_active");
    $list.addClass("cs-mobile-menu-open");
    $("body").addClass("cs-mobile-menu-body-lock");

    // Inject backdrop if not present
    if (!$toggle.siblings(".cs-mobile-backdrop").length) {
      $toggle.parent().append('<div class="cs-mobile-backdrop"></div>');
    }
    // Show backdrop after a tick so CSS transition works
    setTimeout(function () {
      $toggle.siblings(".cs-mobile-backdrop").addClass("cs-backdrop-visible");
    }, 10);

    // GSAP stagger items
    if (hasGSAP() && $list.length) {
      var items = $list.children("li").toArray();
      gsap.fromTo(items, {
        x: -30,
        opacity: 0
      }, {
        x: 0,
        opacity: 1,
        duration: 0.5,
        stagger: 0.05,
        ease: "power3.out",
        delay: 0.2
      });
    }
  }

  /**
   * Close the mobile fullscreen menu.
   */
  function closeMobileMenu($toggle, $list) {
    $toggle.removeClass("cs-toggle_active");
    $list.removeClass("cs-mobile-menu-open");
    $("body").removeClass("cs-mobile-menu-body-lock");
    $toggle.siblings(".cs-mobile-backdrop").removeClass("cs-backdrop-visible");

    // Reset any open sub-menus
    $list.find(".menu-dropdown-toggle.active, .menu-dropdown-toggle_1.active").removeClass("active");
    $list.find("ul").removeAttr("style");
    $list.find("li.active").removeClass("active");
  }

  /**
   * Check if mobile menu is open.
   */
  function isMobileMenuOpen() {
    return $("body").hasClass("cs-mobile-menu-body-lock");
  }

  function initMobileReveal() {
    // No-op — mobile stagger is handled inside openMobileMenu
  }

  // ───────────────────────────────────────────────────
  //  CLEANUP — Remove all GSAP injected state
  // ───────────────────────────────────────────────────
  function cleanupGSAP() {
    $(".cs-nav_list > li").off(".csIndicator .csDrop .csMega");
    $(".cs-nav_list").off(".csIndicator");
    $(".cs-nav-indicator").remove();
    $(document).off(".csNavMobile");
  }

  // ═══════════════════════════════════════════════════
  //  Core Navigation Logic
  // ═══════════════════════════════════════════════════

  function initMainNav() {
    if ($(".cs-nav").hasClass("nav-initialized")) return;

    var $nav = $(".cs-nav");
    if (!$nav.length) return;

    var navOffset = $nav.offset().left;
    document.documentElement.style.setProperty("--theme-nav-offset", navOffset + "px");

    $nav.append('<span class="menu_toggle"><span></span></span>');
    $(".menu-item-has-children").append('<span class="menu-dropdown-toggle"></span>');
    $(".menu-item-has-black-section").append('<span class="menu-dropdown-toggle_1"></span>');

    $(".cs-nav").addClass("nav-initialized");
    handleMenuPositioning();

    // Launch GSAP animations
    revealMenuItems();
    initMobileReveal();
  }

  function handleMenuPositioning() {
    function calculatePositions() {
      var windowWidth = window.innerWidth || $(window).width();

      $(".cs-nav_list > li").each(function () {
        var $this = $(this);
        var $subMenu = $this.children("ul");

        if ($subMenu.length) {
          // --- Mega Menu Smart Alignment (v8) ---
          if ($this.hasClass("cs-mega_menu")) {
            var itemOffset = $this.offset().left;

            if (itemOffset < (windowWidth / 2)) {
              $subMenu[0].style.setProperty("left", "0", "important");
              $subMenu[0].style.setProperty("right", "auto", "important");
            } else {
              $subMenu[0].style.setProperty("left", "auto", "important");
              $subMenu[0].style.setProperty("right", "0", "important");
            }

            // Ensure ancestors don't clip the mega menu (overflow:visible)
            $this.parents().each(function () {
              var $parent = $(this);
              if ($parent.is("body") || $parent.is("html")) return;
              if ($parent.css("overflow") === "hidden" || $parent.hasClass("elementor-widget-wrap") || $parent.hasClass("elementor-column")) {
                $parent.addClass("cs-mega-parent-override");
              }
            });
          }
          // --- Standard Dropdown Direction Logic ---
          else {
            var parentCenter = $this.offset().left + ($this.outerWidth() / 2);

            $this.removeClass("cs-open-left");

            if (parentCenter > (windowWidth / 2)) {
              $this.addClass("cs-open-left");
            }
          }
        }
      });
    }

    // Calculate immediately to prevent off-screen items from causing scrollbars
    calculatePositions();

    // Recalculate on hover in case of dynamic layout shifts
    $(".cs-nav_list > li").on("mouseenter", function () {
      calculatePositions();
    });

    // Recalculate when window is resized
    $(window).on("resize", function () {
      calculatePositions();
    });
  }

  // ═══════════════════════════════════════════════════
  //  Event Handlers — Mobile Fullscreen Menu
  // ═══════════════════════════════════════════════════

  // Mobile Menu Toggle — Fullscreen overlay (replaces slideToggle)
  $(document).on("click.csNav", ".menu_toggle", function (e) {
    e.stopPropagation(); // Prevent conflicts with theme main.js
    var $toggle = $(this);
    var $list = $toggle.siblings(".cs-nav_list");

    if ($toggle.hasClass("cs-toggle_active")) {
      closeMobileMenu($toggle, $list);
    } else {
      openMobileMenu($toggle, $list);
    }
  });

  // Backdrop click — close mobile menu
  $(document).on("click.csNav", ".cs-mobile-backdrop", function () {
    var $backdrop = $(this);
    var $toggle = $backdrop.siblings(".menu_toggle");
    var $list = $backdrop.siblings(".cs-nav_list");
    closeMobileMenu($toggle, $list);
  });

  // ESC key — close mobile menu
  $(document).on("keydown.csNav", function (e) {
    if (e.key === "Escape" && isMobileMenuOpen()) {
      var $toggle = $(".menu_toggle.cs-toggle_active");
      var $list = $toggle.siblings(".cs-nav_list");
      closeMobileMenu($toggle, $list);
    }
  });

  // Sub-menu dropdown toggles (accordion inside mobile menu)
  $(document).on("click.csNav", ".menu-dropdown-toggle, .menu-dropdown-toggle_1", function (e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).toggleClass("active").siblings("ul").slideToggle(300);
    $(this).parent().toggleClass("active");
  });

  // Dark mode toggle
  $(document).on("click", ".cs-mode_btn", function () {
    $(this).toggleClass("active");
    $("body").toggleClass("cs-dark");
  });

  // Side menu — open
  $(document).on("click", ".side-menu-toggle", function () {
    $(".cs-side-menu").addClass("active");
  });

  // Side menu — close
  $(document).on("click", ".side-menu-close", function () {
    $(".cs-side-menu").removeClass("active");
  });

  // Side header — open
  $(document).on("click", ".cs_icon_btn, .cs_icon_btn_el", function () {
    $(".cs_side_header").addClass("active");
  });

  // Side header — close
  $(document).on("click", ".cs_close, .cs_side_header_overlay, .cs_side_header_overlay_el", function () {
    $(".cs_side_header").removeClass("active");
  });

  // ═══════════════════════════════════════════════════
  //  Close mobile menu on window resize to desktop
  // ═══════════════════════════════════════════════════
  $(window).on("resize.csNav", function () {
    if (isDesktop() && isMobileMenuOpen()) {
      var $toggle = $(".menu_toggle.cs-toggle_active");
      var $list = $toggle.siblings(".cs-nav_list");
      closeMobileMenu($toggle, $list);
    }
  });

  // ═══════════════════════════════════════════════════
  //  Init
  // ═══════════════════════════════════════════════════

  $(function () {
    initMainNav();
  });

  $(window).on("elementor/frontend/init", function () {
    elementorFrontend.hooks.addAction("frontend/element_ready/sifency-advanced-menu.default", function () {
      $(".cs-nav_list").removeAttr("style").removeClass("cs-mobile-menu-open");
      $(".menu_toggle").removeClass("cs-toggle_active");
      $(".cs-mobile-backdrop").remove();
      $("body").removeClass("cs-mobile-menu-body-lock");

      // Full cleanup for re-initialization
      cleanupGSAP();
      $(".cs-nav").removeClass("nav-initialized");

      initMainNav();
    });
  });

})(jQuery);