/**
 * Elementor frontend handler for the Sticky Promo Bar widget.
 *
 * Handles three jobs on the frontend ( the editor preview renders the bar
 * statically in place ):
 *  1. Dismissal — slide the bar away on close and, when a "stay hidden"
 *     period is set, remember it in localStorage so it stays gone.
 *  2. Push content — add body padding equal to the bar height so a fixed
 *     bar never covers the page, kept in sync on resize.
 *  3. Respect a previous dismissal before the bar is shown.
 * 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 CaptwikiPromoBarHandler = function ($scope) {

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

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

        var isEditor = bar.classList.contains('captwiki-promo--editor');
        var isFixed = bar.classList.contains('captwiki-promo--fixed');
        var isBottom = bar.classList.contains('captwiki-promo--bottom');
        var pushContent = bar.getAttribute('data-push') === 'yes';
        var rememberDays = parseInt(bar.getAttribute('data-remember'), 10) || 0;
        var storeKey = 'captwiki-promo-' + (bar.getAttribute('data-promo-id') || 'bar');
        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); });
        }

        /**
         * Read the stored "hidden until" timestamp, if any.
         *
         * @return {number} Epoch ms, or 0 when not stored / storage blocked.
         */
        function hiddenUntil() {
            try {
                return parseInt(window.localStorage.getItem(storeKey), 10) || 0;
            } catch (e) {
                return 0;
            }
        }

        /**
         * Apply body padding so the fixed bar does not cover page content.
         */
        function applyOffset() {
            if (!isFixed || bar.hasAttribute('hidden')) return;
            var height = bar.offsetHeight + 'px';
            if (isBottom) {
                document.body.style.paddingBottom = height;
            } else {
                document.body.style.paddingTop = height;
            }
        }

        /**
         * Remove the body padding again ( after dismissal / teardown ).
         */
        function clearOffset() {
            if (!isFixed || !pushContent) return;
            if (isBottom) {
                document.body.style.paddingBottom = '';
            } else {
                document.body.style.paddingTop = '';
            }
        }

        /* ── Previously dismissed? Bail out before showing anything. ── */
        if (!isEditor && rememberDays > 0 && Date.now() < hiddenUntil()) {
            bar.setAttribute('hidden', '');
            return;
        }

        /* ── Push content ─────────────────────────────────── */
        if (!isEditor && pushContent) {
            applyOffset();
            on(window, 'resize', applyOffset);
        }

        /* ── Dismiss ──────────────────────────────────────── */
        var closeBtn = bar.querySelector('.captwiki-promo__close');

        if (closeBtn) {
            on(closeBtn, 'click', function () {
                bar.classList.add('is-dismissed');
                clearOffset();

                window.setTimeout(function () {
                    bar.setAttribute('hidden', '');
                }, 380);

                if (!isEditor && rememberDays > 0) {
                    try {
                        window.localStorage.setItem(storeKey, String(Date.now() + rememberDays * 86400000));
                    } catch (e) {
                        /* Storage unavailable — the bar simply returns next load. */
                    }
                }
            });
        }

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

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

})(jQuery);
