/**
 * Elementor frontend handler for the Flipbox widget.
 *
 * Hover-triggered boxes flip via pure CSS; this handler only drives the
 * click trigger — toggling the flipped state on click / Enter / Space and
 * keeping aria-pressed in sync. 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 CaptwikiFlipboxHandler = function ($scope) {

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

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

        if (box.getAttribute('data-trigger') !== 'click') {
            return;
        }

        var handlers = [];

        /**
         * Bind an event with automatic teardown registration.
         *
         * @param {Element} 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); });
        }

        /**
         * Toggle the flipped state and mirror it onto aria-pressed.
         */
        function toggle() {
            var flipped = box.classList.toggle('is-flipped');
            box.setAttribute('aria-pressed', flipped ? 'true' : 'false');
        }

        on(box, 'click', function (e) {
            /* Let the CTA button work without un-flipping the box. */
            if (e.target.closest('.captwiki-flipbox__btn')) return;
            toggle();
        });

        on(box, 'keydown', function (e) {
            if (e.key !== 'Enter' && e.key !== ' ') return;
            if (e.target.closest('.captwiki-flipbox__btn')) return;
            e.preventDefault();
            toggle();
        });

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

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

})(jQuery);
