(function($) {
    const initPopupTrigger = function($scope, $) {
        // Avoid double-binding
        if ($scope.hasClass('okthemes-popup-init')) return;
        $scope.addClass('okthemes-popup-init');

        const openTriggers = $scope.find('.popup-open-trigger');
        const closeTriggers = $scope.find('.popup-close-trigger');

        openTriggers.each(function() {
            const navBtn = this;

            navBtn.addEventListener("mouseover", () => {
                gsap.to(navBtn.querySelector(".middle-line"), { x: 30, duration: 0.3, ease: "power4" });
                gsap.to(navBtn.querySelectorAll(".top-line, .bottom-line"), { x: -20, duration: 0.3, ease: "power4" });
            });

            navBtn.addEventListener("mouseout", () => {
                gsap.to(navBtn.querySelector(".middle-line"), { x: 0, duration: 0.3, ease: "power4" });
                gsap.to(navBtn.querySelectorAll(".top-line, .bottom-line"), { x: 0, duration: 0.3, ease: "power4" });
            });
        });

        closeTriggers.each(function() {
            const closeBtn = this;

            closeBtn.addEventListener("mouseover", () => {
                gsap.to(closeBtn.querySelectorAll(".close-line-1, .close-line-2"), { rotate: "+=10", duration: 0.3, ease: "power4" });
            });

            closeBtn.addEventListener("mouseout", () => {
                gsap.to(closeBtn.querySelectorAll(".close-line-1, .close-line-2"), { rotate: "-=10", duration: 0.3, ease: "power4" });
            });
        });

        // Click handling
        $scope.find('.popup-trigger').on('click', function() {
            const popupId = $(this).data('popup');
            const action = $(this).data('action');

            if (!popupId) {
                console.warn('[OKThemes PopupTrigger] No popup ID defined on trigger:', this);
                return;
            }

            if (action === 'open') {
                openPopup(popupId);
            } else if (action === 'close') {
                closePopup(popupId);
            }
        });

    };

    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/okthemes-popup-trigger-widget.default', initPopupTrigger);
    });
})(jQuery);
