/**
 * Elementor frontend handler for the Site Logo widget.
 *
 * Handles:
 *  - Dark mode logo switching (prefers-color-scheme + .dark-mode class)
 *  - Sticky scroll logo switching (IntersectionObserver — no jQuery)
 *
 */

(function ($) {
    'use strict';

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

        var wrapper = $scope[0].querySelector('.captwiki-site-logo[data-dark-logo], .captwiki-site-logo[data-sticky-logo]');
        if (!wrapper) return;

        var img = wrapper.querySelector('img');
        if (!img) return;

        if (!img.dataset.cwkOrigSrc) {
            img.dataset.cwkOrigSrc = img.getAttribute('src');
        }
        var origSrc = img.dataset.cwkOrigSrc;
        var darkSrc = wrapper.getAttribute('data-dark-logo') || '';
        var stickySrc = wrapper.getAttribute('data-sticky-logo') || '';

        /* ── Cleanup previous listeners (editor re-render safety) ─ */
        if (wrapper._cwkAbortCtrl) {
            wrapper._cwkAbortCtrl.abort();
        }
        if (wrapper._cwkSentinel && wrapper._cwkSentinel.parentNode) {
            wrapper._cwkSentinel.parentNode.removeChild(wrapper._cwkSentinel);
            wrapper._cwkSentinel = null;
        }
        if (wrapper._cwkObserver) {
            wrapper._cwkObserver.disconnect();
            wrapper._cwkObserver = null;
        }

        var ctrl = new AbortController();
        var signal = ctrl.signal;
        wrapper._cwkAbortCtrl = ctrl;

        if (darkSrc) {

            /**
             * Determine whether dark mode is currently active.
             * Checks both the OS preference and common class-based toggles
             * used by themes (e.g. Astra, OceanWP, GeneratePress, Divi).
             *
             * @returns {boolean}
             */
            function isDarkModeActive() {
                return window.matchMedia('(prefers-color-scheme: dark)').matches
                    || document.body.classList.contains('dark-mode')
                    || document.documentElement.classList.contains('dark-mode')
                    || document.body.classList.contains('dark')
                    || document.documentElement.classList.contains('dark');
            }

            /**
             * Apply the correct logo based on current dark mode state.
             * Only mutates src when necessary to avoid unnecessary repaints.
             */
            function applyDarkLogo() {
                var newSrc = isDarkModeActive() ? darkSrc : origSrc;
                if (img.getAttribute('src') !== newSrc) {
                    img.setAttribute('src', newSrc);
                }
            }

            /* Run immediately */
            applyDarkLogo();

            /* Listen for OS-level dark mode toggle */
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener(
                'change',
                applyDarkLogo,
                { signal: signal }
            );

            var mutObs = new MutationObserver(function (mutations) {
                mutations.forEach(function (m) {
                    if (m.attributeName === 'class') {
                        applyDarkLogo();
                    }
                });
            });
            mutObs.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
            mutObs.observe(document.body, { attributes: true, attributeFilter: ['class'] });

            /* Tie MutationObserver teardown to AbortController */
            signal.addEventListener('abort', function () {
                mutObs.disconnect();
            });
        }

        /* ── Sticky scroll logo (IntersectionObserver) ──────────── */
        if (stickySrc) {

            var sentinel = document.createElement('div');
            sentinel.setAttribute('aria-hidden', 'true');
            sentinel.style.cssText = 'position:absolute;top:0;left:0;height:1px;width:1px;pointer-events:none;visibility:hidden;';
            document.body.prepend(sentinel);
            wrapper._cwkSentinel = sentinel;

            var observer = new IntersectionObserver(
                function (entries) {
                    /* Sentinel out of view → page scrolled past top */
                    var newSrc = entries[0].isIntersecting ? origSrc : stickySrc;

                    if (img.getAttribute('src') !== newSrc) {
                        img.setAttribute('src', newSrc);
                    }
                },
                { threshold: 0, rootMargin: '0px' }
            );

            observer.observe(sentinel);
            wrapper._cwkObserver = observer;

            /* Disconnect observer when AbortController fires */
            signal.addEventListener('abort', function () {
                observer.disconnect();
                if (sentinel.parentNode) {
                    sentinel.parentNode.removeChild(sentinel);
                }
            });
        }
    };

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

})(jQuery);
