// Fix for color-modes.js iframe context
(function() {
    'use strict';
    
    // Wait for DOM to be ready
    function waitForElement(selector, callback) {
        const element = document.querySelector(selector);
        if (element) {
            callback(element);
        } else {
            setTimeout(() => waitForElement(selector, callback), 100);
        }
    }
    
    // Fix showActiveTheme function for iframe context
    function showActiveTheme(theme, highlight) {
        // Check if elements exist before accessing them
        const themeSwitcher = document.querySelector('[data-bs-theme-value]');
        const highlightSwitcher = document.querySelector('[data-bs-color-mode]');
        
        if (themeSwitcher) {
            themeSwitcher.setAttribute('data-bs-theme-value', theme);
        }
        
        if (highlightSwitcher) {
            highlightSwitcher.setAttribute('data-bs-color-mode', highlight);
        }
    }
    
    // Initialize theme when DOM is ready
    function initTheme() {
        // Check if we're in an iframe
        const isInIframe = window.self !== window.top;
        
        if (isInIframe) {
            // Iframe context - use default theme
            showActiveTheme('light', 'light');
        } else {
            // Normal context - use saved theme
            const savedTheme = localStorage.getItem('bs-theme') || 'light';
            const savedHighlight = localStorage.getItem('bs-color-mode') || 'light';
            showActiveTheme(savedTheme, savedHighlight);
        }
    }
    
    // Wait for DOM and initialize
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initTheme);
    } else {
        initTheme();
    }
    
    // Expose function globally
    window.showActiveTheme = showActiveTheme;
})();
