(function() {
    /**
     * Lazy-load the sidebar iframe: set src from data-src when sidebar becomes visible,
     * and unload (set src to about:blank) when sidebar is hidden to stop all requests.
     */
    function loadSidebarIframe(sidebar) {
        var iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
        if (iframe && iframe.dataset.src && iframe.src !== iframe.dataset.src) {
            iframe.src = iframe.dataset.src;
        }
    }

    function unloadSidebarIframe(sidebar) {
        var iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
        if (iframe && iframe.src && iframe.src !== 'about:blank') {
            iframe.src = 'about:blank';
        }
    }

    function checkAndShowSidebar() {
        try {
            var sidebarVisible = localStorage.getItem('peligent_ai_sidebar_visible');
            var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
            if (sidebar) {
                if (sidebarVisible === '0') {
                    sidebar.classList.add('peligent-ai-hidden');
                    sidebar.classList.remove('peligent-ai-initially-hidden');
                    document.body.classList.add('peligent-ai-sidebar-hidden');
                    // Don't load iframe when hidden
                    unloadSidebarIframe(sidebar);
                } else {
                    sidebar.classList.remove('peligent-ai-hidden');
                    sidebar.classList.remove('peligent-ai-initially-hidden');
                    document.body.classList.remove('peligent-ai-sidebar-hidden');
                    // Load iframe when visible
                    loadSidebarIframe(sidebar);
                    if (sidebarVisible === null) {
                        try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch(e) {}
                    }
                }
            }
        } catch (e) {
            var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
            if (sidebar) {
                sidebar.classList.remove('peligent-ai-hidden');
                sidebar.classList.remove('peligent-ai-initially-hidden');
                document.body.classList.remove('peligent-ai-sidebar-hidden');
                loadSidebarIframe(sidebar);
            }
        }
    }

    // Observe sidebar class changes to load/unload iframe dynamically
    function observeSidebar(sidebar) {
        if (typeof MutationObserver === 'undefined') return;
        var observer = new MutationObserver(function() {
            if (sidebar.classList.contains('peligent-ai-hidden')) {
                unloadSidebarIframe(sidebar);
                // Show floating toggle button if it exists
                var toggle = document.getElementById('peligent-floating-toggle');
                if (toggle) toggle.style.display = '';
            } else {
                loadSidebarIframe(sidebar);
                // Hide floating toggle button
                var toggle = document.getElementById('peligent-floating-toggle');
                if (toggle) toggle.style.display = 'none';
            }
        });
        observer.observe(sidebar, { attributes: true, attributeFilter: ['class'] });
    }

    function initSidebar() {
        var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
        if (sidebar) {
            checkAndShowSidebar();
            observeSidebar(sidebar);
            // Push defaults (language/tone) to iframe if available
            try {
                var iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
                if (iframe && iframe.contentWindow && window.PELIGENT_DEFAULTS) {
                    iframe.contentWindow.postMessage({
                        type: 'PELIGENT_AI_SET_PREFERENCES',
                        language: window.PELIGENT_DEFAULTS.language || null,
                        tone: window.PELIGENT_DEFAULTS.tone || null
                    }, 'https://app.peligent.com');
                }
            } catch (e) {}
        } else {
            // Retry if sidebar not yet rendered
            setTimeout(initSidebar, 100);
        }
    }

    // Start initialization
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSidebar);
    } else {
        initSidebar();
    }
})();
