document.addEventListener('DOMContentLoaded', function() {
    function getElfinderStyleSheet(main = true) {
        const regex = main ? /RobiNN1\/elFinder-Material-Theme\/Material\/css\/theme\.min\.css/ : /RobiNN1\/elFinder-Material-Theme\/Material\/css\/theme-gray\.min\.css/;
        const linkElements = document.querySelectorAll('link[rel="stylesheet"]');
        // Find the main elfinder stylesheet
        let selectedLinkElement;
        for (const linkElement of linkElements) {
            if (regex.test(linkElement.href)) {
                selectedLinkElement = linkElement;
                break;
            }
        }
        return selectedLinkElement;
    }

    function addElfinderLightStylesheet() {
        let themeLightAsset = `<link href="/storage/basset/cdn.jsdelivr.net/gh/RobiNN1/elFinder-Material-Theme/Material/css/theme-gray.min.css?fe1b2b726f2e" rel="stylesheet" type="text/css" />
Already in cache`;
        const match = themeLightAsset.match(/<link\s+href="([^"]+)"/i);
        if (match && match.length > 1) {
            let mainStyleSheet = getElfinderStyleSheet();
            let lightStyleSheet = getElfinderStyleSheet(false);
            // if found append the light mode css to the main theme stylesheet
            if (mainStyleSheet && ! lightStyleSheet) {
                let themeLight = document.createElement('link');
                themeLight.href = match[1];
                themeLight.rel = 'stylesheet';
                themeLight.type = 'text/css';
                mainStyleSheet.insertAdjacentElement('afterend', themeLight);
            }
        }
    }

    let colorMode = window.parent.colorMode?.result ?? window.colorMode?.result ?? false;
   
    if(colorMode !== 'dark') {
        addElfinderLightStylesheet();
    }

    // register a color mode change event so that we remove
    // the light stylesheet when the color mode change
    if(colorMode) {
        let colorModeClass = window.parent.colorMode ?? window.colorMode;
        colorModeClass.onChange(function(scheme) {
            let styleSheetType = scheme === 'dark' ? false : true;
            let selectedLinkElement = getElfinderStyleSheet(styleSheetType);

            if (! selectedLinkElement) {
                return true;
            }
            // in case we switched to dark mode, remove the ligth theme css
            if(scheme === 'dark') {
                selectedLinkElement.parentNode.removeChild(selectedLinkElement);
                return true; 
            }
            addElfinderLightStylesheet()
        });
    }

    // we dont want to style the body when elfinder is loaded as a component in a backpack view
    // we pass true when loading elfinder inside an iframe to style the iframe body.
    });

