// Both load and DOMContentLoaded need to be observed here. DOMContentLoaded is more correct, and avoids a flash of dark
// when light mode should be forced, but is never triggered when composing.

window.addEventListener('load', function() {
    styleIfNecessary();
});

window.addEventListener('DOMContentLoaded', function() {
    styleIfNecessary();
});

function styleForDarkMode() {
    let style = document.createElement('style');
    style.appendChild(document.createTextNode(':root { color-scheme: light dark; }'));
    document.head.appendChild(style);
    document.documentElement.classList.add('dl-dark-mode');
}

function documentColorSchemes() {
    let styleSchemes = window.getComputedStyle(document.documentElement).colorScheme;
    
    if (styleSchemes && styleSchemes !== 'normal') {
        let schemes = styleSchemes.split(/\s+/);
        
        if (schemes)
            return schemes;
    }
    
    let schemeMetaElements = document.querySelectorAll("meta[name='color-scheme']")
        || document.querySelectorAll("meta[name='supported-color-schemes']");
    
    if (schemeMetaElements) {
        let element = schemeMetaElements[schemeMetaElements.length - 1];

        if (element && element.content) {
            let schemes = element.content.toLowerCase().split(/\s+/);
            
            if (schemes && schemes.length)
                return schemes;
        }
    }
    
    return null;
}

function documentContainsImages() {
    for (let image of document.images) {
        if (image.src.startsWith('http') && (image.width > 1 || image.height > 1))
            return true;
    }
    
    if (window.getComputedStyle(document.body).backgroundImage !== 'none')
        return true;
    
    return false;
}

let stylingFinished = false;

function styleIfNecessary() {
    if (stylingFinished)
        return;
    
    let schemes = documentColorSchemes();

    if (!schemes)
        styleForDarkMode();

    let forceLightMode = documentContainsImages();
    
    if (!forceLightMode && schemes)
        forceLightMode = (schemes.includes('light') || schemes.includes('only')) && !schemes.includes('dark');
    
    if (forceLightMode) {
        let forceLightHandler = window.webkit.messageHandlers.forceLightMode;
        
        if (forceLightHandler)
            forceLightHandler.postMessage(true);
    }
    
    stylingFinished = true;
}
