/**
 * Elementor frontend handler for the Before After widget.
 *
 * Drives the comparison divider with Pointer Events ( mouse + touch + pen ),
 * optional follow-on-hover mode and full keyboard control on the ARIA
 * slider ( arrows, Home / End, with aria-valuenow kept 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 CaptwikiBeforeAfterHandler = function ($scope) {

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

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

        var frame = root.querySelector('.captwiki-ba__frame');
        var divider = root.querySelector('.captwiki-ba__divider');
        if (!frame || !divider) return;

        var isVertical = root.classList.contains('captwiki-ba--vertical');
        var hoverMove = root.getAttribute('data-hover-move') === 'yes';
        var position = parseInt(root.getAttribute('data-initial'), 10);
        if (isNaN(position)) position = 50;

        var dragging = false;
        var handlers = [];

        /**
         * Bind an event with automatic teardown registration.
         *
         * @param {Element|Window} 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 a divider position ( clamped 0–100 ).
         *
         * @param {number} value - Position percentage.
         */
        function setPosition(value) {
            position = Math.max(0, Math.min(100, value));
            frame.style.setProperty('--captwiki-ba-pos', position + '%');
            divider.setAttribute('aria-valuenow', String(Math.round(position)));
        }

        /**
         * Translate a pointer event into a divider position.
         *
         * @param {PointerEvent|MouseEvent} e - The pointer event.
         * @return {number} Position percentage.
         */
        function positionFromEvent(e) {
            var rect = frame.getBoundingClientRect();
            if (isVertical) {
                return ((e.clientY - rect.top) / rect.height) * 100;
            }
            return ((e.clientX - rect.left) / rect.width) * 100;
        }

        /* ── Drag ( Pointer Events cover mouse, touch and pen ) ── */
        on(frame, 'pointerdown', function (e) {
            dragging = true;
            if (frame.setPointerCapture) {
                frame.setPointerCapture(e.pointerId);
            }
            setPosition(positionFromEvent(e));
            e.preventDefault();
        });

        on(frame, 'pointermove', function (e) {
            if (dragging || (hoverMove && e.pointerType === 'mouse')) {
                setPosition(positionFromEvent(e));
            }
        });

        on(frame, 'pointerup', function () { dragging = false; });
        on(frame, 'pointercancel', function () { dragging = false; });

        /* ── Keyboard ─────────────────────────────────────── */
        on(divider, 'keydown', function (e) {
            var step = null;

            if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                step = -2;
            } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                step = 2;
            } else if (e.key === 'Home') {
                setPosition(0);
                e.preventDefault();
                return;
            } else if (e.key === 'End') {
                setPosition(100);
                e.preventDefault();
                return;
            }

            if (step !== null) {
                e.preventDefault();
                setPosition(position + step);
            }
        });

        /* ── Init ─────────────────────────────────────────── */
        setPosition(position);

        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-before-after.default',
            CaptwikiBeforeAfterHandler
        );
    });

})(jQuery);
