(function ($) {
    jQuery(window).on('elementor:init', function () {
        if (!elementor || !elementor.hooks) {
            console.error('Elementor hooks are not available.');
            return;
        }
        if (myWidgetSettings.isProActive) {
            return;
        }
        if (typeof myWidgetSettings === 'undefined') {
            console.error('myWidgetSettings is not defined.');
            return;
        }

        function applyLock($panel) {
            var $lockedControls = $panel.find('.pro-locked-control');
            if (!$lockedControls.length || myWidgetSettings.isProActive) {
                return;
            }

            $lockedControls.each(function () {
                var $lockedControl = $(this);
                var $inputWrapper = $lockedControl.find('.elementor-control-input-wrapper');
                var $input = $inputWrapper.find('input, select, textarea, button');
                var $title = $lockedControl.find('.elementor-control-title, .elementor-control-tag-area');

                $title.css('opacity', '0.5');
                if ($inputWrapper.find('.lock-icon').length) {
                    return;
                }
                $inputWrapper.find('.e-global__popover-toggle.elementor-control-unit-1').css('display', 'none');
                if ($input.length) {
                    $inputWrapper
                        .css('position', 'relative')
                        .append('<span class="lock-icon">🔒</span>')
                        .find('input, select, textarea, button')
                        .prop('disabled', true)
                        .css('background', '#f5f5f5');
                }
            });
        }

        var allowedWidgets = ['rswpthemes_awt_full_width_books_slider', 'rswpthemes_awt_book_gallery', 'rswpthemes_awt_book_carousel'];
        let observer;

        elementor.hooks.addAction('panel/open_editor/widget', function (panel, model) {
            var widgetType = model.get('widgetType');
            if (!allowedWidgets.includes(widgetType)) {
                return;
            }

            var currentPanel = panel.$el;
            setTimeout(() => applyLock(currentPanel), 500);

            if (!observer) {
                observer = new MutationObserver((mutations) => {
                    let hasRelevantChange = mutations.some(mutation => mutation.addedNodes.length || mutation.removedNodes.length);
                    if (hasRelevantChange) {
                        applyLock(currentPanel);
                    }
                });

                let elementorPanel = $('.elementor-panel')[0];
                if (elementorPanel) {
                    observer.observe(elementorPanel, { childList: true, subtree: true });
                }
            }
        });

        if (!$('#pro-popup').length) {
            $('body').append(`
                <div id="pro-popup" style="display:none; position:fixed; background:#fff; padding:20px; border-radius:5px; box-shadow:0 0 10px rgba(0,0,0,0.3); z-index:10000;">
                    <h3>Pro Feature</h3>
                    <p>This feature is available in the Pro version.</p>
                    <a href="${myWidgetSettings.upgradeLink}" target="_blank">Upgrade to Pro</a>
                    <button id="close-popup">Close</button>
                </div>
            `);
        }

        function updatePopupPosition($triggerElement) {
            let $elementorPanel = $('.elementor-panel');
            if ($elementorPanel.length && $triggerElement.length) {
                let panelOffset = $elementorPanel.offset();
                let triggerOffset = $triggerElement.offset();
                let panelWidth = $elementorPanel.outerWidth();

                $('#pro-popup').css({
                    top: triggerOffset.top + 10, // Slightly below the clicked control
                    left: panelOffset.left + panelWidth + 10, // Next to Elementor panel
                    display: 'block'
                });
            }
        }

        $(window).on('resize', function () {
            let $activeTrigger = $('.pro-locked-control.active');
            if ($activeTrigger.length) {
                updatePopupPosition($activeTrigger);
            }
        });

        $('body').on('click', '.pro-locked-control', function (e) {
            e.preventDefault();
            e.stopPropagation();
            $('.pro-locked-control').removeClass('active'); // Remove active class from others
            $(this).addClass('active'); // Mark current one as active

            updatePopupPosition($(this));
        });

        $(document).on('click', function (e) {
            if (!$(e.target).closest('#pro-popup, .pro-locked-control').length) {
                $('#pro-popup').fadeOut();
                $('.pro-locked-control').removeClass('active'); // Remove active state when closed
            }
        });

        $('body').on('click', '#close-popup', function () {
            $('#pro-popup').fadeOut();
            $('.pro-locked-control').removeClass('active'); // Remove active state when closed
        });

        elementor.hooks.addAction('panel/close_editor', function () {
            $('.lock-icon').remove();
            $('#pro-popup').remove();
            $('body').off('click', '.pro-locked-control');
            $('body').off('click', '#close-popup');
            $(document).off('click');

            if (observer) {
                observer.disconnect();
                observer = null;
            }
        });
    });
})(jQuery);
