/**
 * Elementor frontend handler for the Tabs widget.
 *
 * Handles tab switching, ARIA state, full keyboard navigation (arrow keys,
 * Home/End) and positioning of the moving indicator used by the Animated
 * Underline and Segmented Slider styles. One controller per instance with
 * editor-safe teardown.
 *
 */

(function ($) {
    'use strict';

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

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

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

        var nav = root.querySelector('.captwiki-tabs__nav');
        var tabs = Array.prototype.slice.call(root.querySelectorAll('.captwiki-tabs__tab'));
        var panels = Array.prototype.slice.call(root.querySelectorAll('.captwiki-tabs__panel'));
        var indicator = root.querySelector('.captwiki-tabs__indicator');

        if (tabs.length === 0) return;

        var current = parseInt(root.getAttribute('data-active'), 10) || 0;
        if (current >= tabs.length) current = 0;

        /**
         * Position the moving indicator beneath / behind the active tab.
         * CSS decides whether it is visible (underline & segmented styles only).
         */
        function moveIndicator() {
            if (!indicator) return;
            var tab = tabs[current];
            if (!tab) return;
            indicator.style.left = tab.offsetLeft + 'px';
            indicator.style.top = tab.offsetTop + 'px';
            indicator.style.width = tab.offsetWidth + 'px';
            indicator.style.height = tab.offsetHeight + 'px';
        }

        /**
         * Activate a tab by index and reveal its panel.
         *
         * @param {number} index    - Target tab index.
         * @param {boolean} setFocus - Whether to move focus to the new tab.
         */
        function activate(index, setFocus) {
            current = index;

            tabs.forEach(function (tab, i) {
                var on = i === index;
                tab.classList.toggle('is-active', on);
                tab.setAttribute('aria-selected', on ? 'true' : 'false');
                tab.setAttribute('tabindex', on ? '0' : '-1');
                if (on && setFocus) tab.focus();
            });

            panels.forEach(function (panel, i) {
                var on = i === index;
                panel.classList.toggle('is-active', on);
                if (on) {
                    panel.removeAttribute('hidden');
                } else {
                    panel.setAttribute('hidden', '');
                }
            });

            moveIndicator();
        }

        /* ── Events ────────────────────────────────────────── */
        var handlers = [];

        function on(el, type, fn) {
            if (!el) return;
            el.addEventListener(type, fn);
            handlers.push(function () { el.removeEventListener(type, fn); });
        }

        tabs.forEach(function (tab, i) {
            on(tab, 'click', function () { activate(i, false); });
        });

        on(nav, 'keydown', function (e) {
            var key = e.key;
            var next = null;

            if (key === 'ArrowRight' || key === 'ArrowDown') {
                next = (current + 1) % tabs.length;
            } else if (key === 'ArrowLeft' || key === 'ArrowUp') {
                next = (current - 1 + tabs.length) % tabs.length;
            } else if (key === 'Home') {
                next = 0;
            } else if (key === 'End') {
                next = tabs.length - 1;
            }

            if (next !== null) {
                e.preventDefault();
                activate(next, true);
            }
        });

        /* Reposition the indicator on resize. */
        var onResize = function () { moveIndicator(); };
        on(window, 'resize', onResize);

        /* ── Init ──────────────────────────────────────────── */
        activate(current, false);

        /* Run once more after fonts/layout settle so the indicator is exact. */
        if (window.requestAnimationFrame) {
            window.requestAnimationFrame(moveIndicator);
        }

        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-tabs.default',
            CaptwikiTabsHandler
        );
    });

})(jQuery);
