/**
 * Elementor frontend handler for the Animated Service Box widget.
 *
 * Adds an on-scroll entrance reveal using IntersectionObserver. The box ships
 * hidden ( via the common CSS ) and the `is-inview` class is added once it
 * enters the viewport. Dependency-free with an editor-safe teardown and a
 * graceful fallback when IntersectionObserver is unavailable.
 *
 * @package captain-widgets-kit
 * @since   1.6.0
 */

(function ($) {
    'use strict';

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

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

        // Re-run safe: clean up a previous observer on editor re-render.
        if (root._cwkAniboxTeardown) {
            root._cwkAniboxTeardown();
        }

        // Nothing to do when the entrance animation is disabled.
        if (!root.classList.contains('captwiki-anibox--animate')) {
            return;
        }

        var reveal = function () {
            root.classList.add('is-inview');
        };

        // Fallback: no IntersectionObserver support — show immediately.
        if (typeof window.IntersectionObserver === 'undefined') {
            reveal();
            return;
        }

        var observer = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    reveal();
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.2,
            rootMargin: '0px 0px -10% 0px'
        });

        observer.observe(root);

        /* ── Teardown ──────────────────────────────────────── */
        root._cwkAniboxTeardown = function () {
            observer.disconnect();
            root._cwkAniboxTeardown = null;
        };
    };

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

})(jQuery);
