/**
 * Elementor frontend handler for the Image Hotspot widget.
 *
 * Drives marker toggling: in click mode it opens / closes tooltips ( one at
 * a time ), and in hover mode it still handles taps for touch users. Keeps
 * aria-expanded in sync, closes on outside click and on Escape.
 * Editor-safe teardown per instance.
 *
 * @package captain-widgets-kit
 * @since   1.7.0
 */

(function ($) {
    'use strict';

    /**
     * Per-instance handler — called by Elementor for every widget instance.
     *
     * @param {jQuery} $scope - The widget wrapper element.
     */
    var CaptwikiHotspotHandler = function ($scope) {

        var root = $scope[0].querySelector('.captwiki-hotspot');
        if (!root) return;

        if (root._cwkTeardown) {
            root._cwkTeardown();
        }

        var points = Array.prototype.slice.call(root.querySelectorAll('.captwiki-hotspot__point'));
        if (points.length === 0) return;

        var handlers = [];

        /**
         * Bind an event with automatic teardown registration.
         *
         * @param {Element|Document} el - Target element.
         * @param {string}  type - Event type.
         * @param {Function} fn  - Listener.
         */
        function on(el, type, fn) {
            el.addEventListener(type, fn);
            handlers.push(function () { el.removeEventListener(type, fn); });
        }

        /**
         * Apply the open state to one point.
         *
         * @param {Element} point - The hotspot point element.
         * @param {boolean} open  - Target state.
         */
        function setOpen(point, open) {
            var marker = point.querySelector('.captwiki-hotspot__marker');
            point.classList.toggle('is-open', open);
            if (marker) {
                marker.setAttribute('aria-expanded', open ? 'true' : 'false');
            }
        }

        /**
         * Close every hotspot except the given one.
         *
         * @param {Element|null} except - Point to keep open.
         */
        function closeAll(except) {
            points.forEach(function (point) {
                if (point !== except) setOpen(point, false);
            });
        }

        /* ── Marker clicks ( both modes — covers touch ) ──── */
        points.forEach(function (point) {
            var marker = point.querySelector('.captwiki-hotspot__marker');
            if (!marker) return;

            on(marker, 'click', function (e) {
                e.stopPropagation();
                var willOpen = !point.classList.contains('is-open');
                closeAll(point);
                setOpen(point, willOpen);
            });
        });

        /* ── Outside click & Escape close everything ──────── */
        var onDocClick = function (e) {
            if (!root.contains(e.target)) closeAll(null);
        };
        var onDocKey = function (e) {
            if (e.key === 'Escape') closeAll(null);
        };
        on(document, 'click', onDocClick);
        on(document, 'keydown', onDocKey);

        root._cwkTeardown = function () {
            handlers.forEach(function (off) { off(); });
            handlers = [];
            root._cwkTeardown = null;
        };
    };

    /* ── Register with Elementor frontend ───────────────────── */
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/captwiki-image-hotspot.default',
            CaptwikiHotspotHandler
        );
    });

})(jQuery);
