/**
 * @param $scope The Widget wrapper element as a jQuery element
 * @param $ The jQuery alias
 */
function initImageHotspot($scope) {
    if (!$scope || $scope.length === 0) return;
    
    const $hotspots = $scope.find('.unlockafe-hotspot');

    // Hide all tooltips initially
    $scope.find('.unlockafe-hotspot-tooltip').hide();

    // Debug: Log when script runs and how many hotspots found
    console.log('[Unlockafe Hotspot] JS loaded. Hotspots found:', $hotspots.length);

    // Show tooltip on hover (desktop) and on click (mobile)
    function isMobile() {
        return window.matchMedia('(max-width: 767px)').matches;
    }

    $hotspots.each(function (i) {
        var $hotspot = $(this);
        var $tooltip = $hotspot.find('.unlockafe-hotspot-tooltip');
        console.log('[Unlockafe Hotspot] Binding events for hotspot', i, $hotspot.get(0));

        if (isMobile()) {
            $hotspot.off('click').on('click', function (e) {
                e.preventDefault();
                $hotspots.not($hotspot).removeClass('open');
                $hotspot.toggleClass('open');
                console.log('[Unlockafe Hotspot] Mobile click. .open toggled:', $hotspot.hasClass('open'));
            });
        } else {
            $hotspot.off('mouseenter mouseleave').on('mouseenter', function () {
                $hotspot.addClass('open');
                console.log('[Unlockafe Hotspot] Desktop mouseenter. .open added:', $hotspot.get(0));
            }).on('mouseleave', function () {
                $hotspot.removeClass('open');
                console.log('[Unlockafe Hotspot] Desktop mouseleave. .open removed:', $hotspot.get(0));
            });
        }
    });

    // Close tooltip when clicking outside
    $(document).on('click', function (e) {
        if (!$(e.target).closest('.unlockafe-hotspot').length) {
            $scope.find('.unlockafe-hotspot-tooltip').fadeOut(200);
        }
    });

    $hotspots.each(function () {
        var $icon = $(this).find('.unlockafe-hotspot-icon');
        var $tooltip = $(this).find('.unlockafe-hotspot-tooltip');
        var bg = $icon.data('bg');
        var icon = $icon.data('icon');
        var hover = $icon.data('hover');
        var pos = $tooltip.data('pos');
        if (bg) $icon.css('--hotspot-bg', bg);
        if (icon) $icon.css('--hotspot-icon', icon);
        if (hover) $icon.css('--hotspot-bg-hover', hover);
        if (pos) $tooltip.attr('data-pos', pos);
    });

    // Enable zoom/pan if enabled in widget settings
    if ($scope.data('enable-zoom-pan')) {
        // Dynamically load panzoom if not present
        if (typeof window.Panzoom === 'undefined') {
            var script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/@panzoom/panzoom@9.4.0/dist/panzoom.min.js';
            script.onload = function() {
                Panzoom($scope.find('img')[0]);
            };
            document.body.appendChild(script);
        } else {
            Panzoom($scope.find('img')[0]);
        }
    }

    // Accessibility: close tooltip on outside click (mobile)
    if (isMobile()) {
        $(document).off('touchstart.unlockafe-hotspot').on('touchstart.unlockafe-hotspot', function(e) {
            if (!$(e.target).closest('.unlockafe-hotspot').length) {
                $hotspots.removeClass('open');
            }
        });
    }
    $hotspots.each(function (i) {
        var $hotspot = $(this);
        var $tooltip = $hotspot.find('.unlockafe-hotspot-tooltip');
        $hotspot.attr('tabindex', 0);
        $hotspot.attr('role', 'button');
        $hotspot.attr('aria-haspopup', 'true');
        $hotspot.attr('aria-expanded', 'false');
        $tooltip.attr('role', 'tooltip');
        $tooltip.attr('aria-hidden', 'true');
        function openTooltip() {
            $hotspots.not($hotspot).removeClass('open').find('.unlockafe-hotspot-tooltip').attr('aria-hidden', 'true').css('display', '');
            $hotspot.addClass('open');
            $hotspot.attr('aria-expanded', 'true');
            $tooltip.attr('aria-hidden', 'false').css('display', '');
        }
        function closeTooltip() {
            $hotspot.removeClass('open');
            $hotspot.attr('aria-expanded', 'false');
            $tooltip.attr('aria-hidden', 'true');
        }
        if (isMobile()) {
            $hotspot.off('click').on('click', function (e) {
                e.preventDefault();
                if ($hotspot.hasClass('open')) {
                    closeTooltip();
                } else {
                    openTooltip();
                }
            });
        } else {
            // Desktop: keep tooltip open if mouse moves from icon to tooltip
            $hotspot.off('mouseenter mouseleave');
            $hotspot.on('mouseenter', function () {
                openTooltip();
            });
            $hotspot.on('mouseleave', function (e) {
                // Only close if mouse is not moving to tooltip
                var relTarget = e.relatedTarget || e.toElement;
                if (!$tooltip.is(relTarget) && !$tooltip.has(relTarget).length) {
                    closeTooltip();
                }
            });
            $tooltip.on('mouseenter', function () {
                openTooltip();
            });
            $tooltip.on('mouseleave', function (e) {
                // Only close if mouse is not moving to icon
                var relTarget = e.relatedTarget || e.toElement;
                if (!$hotspot.is(relTarget) && !$hotspot.has(relTarget).length) {
                    closeTooltip();
                }
            });
        }
        // Keyboard accessibility
        $hotspot.on('focus', function () { openTooltip(); });
        $hotspot.on('blur', function () { closeTooltip(); });
        $hotspot.on('keydown', function (e) {
            if (e.key === 'Escape' || e.keyCode === 27) {
                closeTooltip();
            }
        });
    });
}

// Elementor Frontend Hook
$(window).on("elementor/frontend/init", function () {
    elementorFrontend.hooks.addAction(
        "frontend/element_ready/unlockafe-image-hotspot.default",
        function ($scope) {
            initImageHotspot($scope);
        }
    );
});

// Fallback: Initialize on document ready (for non-Elementor pages or if hook doesn't fire)
$(document).ready(function() {
    // Wait a bit for Elementor to initialize
    setTimeout(function() {
        $('.unlockafe-image-hotspot-wrapper').each(function() {
            var $wrapper = $(this);
            // Only init if not already initialized
            if (!$wrapper.data('hotspot-initialized')) {
                $wrapper.data('hotspot-initialized', true);
                initImageHotspot($wrapper);
            }
        });
    }, 100);
});
            const $hotspots = $scope.find('.unlockafe-hotspot');

            // Hide all tooltips initially
            $scope.find('.unlockafe-hotspot-tooltip').hide();

            // Debug: Log when script runs and how many hotspots found
            console.log('[Unlockafe Hotspot] JS loaded. Hotspots found:', $hotspots.length);

            // Show tooltip on hover (desktop) and on click (mobile)
            function isMobile() {
                return window.matchMedia('(max-width: 767px)').matches;
            }

            $hotspots.each(function (i) {
                var $hotspot = $(this);
                var $tooltip = $hotspot.find('.unlockafe-hotspot-tooltip');
                console.log('[Unlockafe Hotspot] Binding events for hotspot', i, $hotspot.get(0));

                if (isMobile()) {
                    $hotspot.off('click').on('click', function (e) {
                        e.preventDefault();
                        $hotspots.not($hotspot).removeClass('open');
                        $hotspot.toggleClass('open');
                        console.log('[Unlockafe Hotspot] Mobile click. .open toggled:', $hotspot.hasClass('open'));
                    });
                } else {
                    $hotspot.off('mouseenter mouseleave').on('mouseenter', function () {
                        $hotspot.addClass('open');
                        console.log('[Unlockafe Hotspot] Desktop mouseenter. .open added:', $hotspot.get(0));
                    }).on('mouseleave', function () {
                        $hotspot.removeClass('open');
                        console.log('[Unlockafe Hotspot] Desktop mouseleave. .open removed:', $hotspot.get(0));
                    });
                }
            });

            // Close tooltip when clicking outside
            $(document).on('click', function (e) {
                if (!$(e.target).closest('.unlockafe-hotspot').length) {
                    $scope.find('.unlockafe-hotspot-tooltip').fadeOut(200);
                }
            });

            $hotspots.each(function () {
                var $icon = $(this).find('.unlockafe-hotspot-icon');
                var $tooltip = $(this).find('.unlockafe-hotspot-tooltip');
                var bg = $icon.data('bg');
                var icon = $icon.data('icon');
                var hover = $icon.data('hover');
                var pos = $tooltip.data('pos');
                if (bg) $icon.css('--hotspot-bg', bg);
                if (icon) $icon.css('--hotspot-icon', icon);
                if (hover) $icon.css('--hotspot-bg-hover', hover);
                if (pos) $tooltip.attr('data-pos', pos);
            });

            // Enable zoom/pan if enabled in widget settings
            if ($scope.data('enable-zoom-pan')) {
                // Dynamically load panzoom if not present
                if (typeof window.Panzoom === 'undefined') {
                    var script = document.createElement('script');
                    script.src = 'https://cdn.jsdelivr.net/npm/@panzoom/panzoom@9.4.0/dist/panzoom.min.js';
                    script.onload = function() {
                        Panzoom($scope.find('img')[0]);
                    };
                    document.body.appendChild(script);
                } else {
                    Panzoom($scope.find('img')[0]);
                }
            }

            // Accessibility: close tooltip on outside click (mobile)
            if (isMobile()) {
                $(document).off('touchstart.unlockafe-hotspot').on('touchstart.unlockafe-hotspot', function(e) {
                    if (!$(e.target).closest('.unlockafe-hotspot').length) {
                        $hotspots.removeClass('open');
                    }
                });
            }
            $hotspots.each(function (i) {
                var $hotspot = $(this);
                var $tooltip = $hotspot.find('.unlockafe-hotspot-tooltip');
                $hotspot.attr('tabindex', 0);
                $hotspot.attr('role', 'button');
                $hotspot.attr('aria-haspopup', 'true');
                $hotspot.attr('aria-expanded', 'false');
                $tooltip.attr('role', 'tooltip');
                $tooltip.attr('aria-hidden', 'true');
                function openTooltip() {
                    $hotspots.not($hotspot).removeClass('open').find('.unlockafe-hotspot-tooltip').attr('aria-hidden', 'true').css('display', '');
                    $hotspot.addClass('open');
                    $hotspot.attr('aria-expanded', 'true');
                    $tooltip.attr('aria-hidden', 'false').css('display', '');
                }
                function closeTooltip() {
                    $hotspot.removeClass('open');
                    $hotspot.attr('aria-expanded', 'false');
                    $tooltip.attr('aria-hidden', 'true');
                }
                if (isMobile()) {
                    $hotspot.off('click').on('click', function (e) {
                        e.preventDefault();
                        if ($hotspot.hasClass('open')) {
                            closeTooltip();
                        } else {
                            openTooltip();
                        }
                    });
                } else {
                    // Desktop: keep tooltip open if mouse moves from icon to tooltip
                    $hotspot.off('mouseenter mouseleave');
                    $hotspot.on('mouseenter', function () {
                        openTooltip();
                    });
                    $hotspot.on('mouseleave', function (e) {
                        // Only close if mouse is not moving to tooltip
                        var relTarget = e.relatedTarget || e.toElement;
                        if (!$tooltip.is(relTarget) && !$tooltip.has(relTarget).length) {
                            closeTooltip();
                        }
                    });
                    $tooltip.on('mouseleave', function (e) {
                        // Only close if mouse is not moving to icon
                        var relTarget = e.relatedTarget || e.toElement;
                        if (!$hotspot.is(relTarget) && !$hotspot.has(relTarget).length) {
                            closeTooltip();
                        }
                    });
                }
                // Keyboard accessibility
                $hotspot.on('focus', function () { openTooltip(); });
                $hotspot.on('blur', function () { closeTooltip(); });
                $hotspot.on('keydown', function (e) {
                    if (e.key === 'Escape' || e.keyCode === 27) {
                        closeTooltip();
                    }
                });
            });
        }
    );
});