import { setMode } from "@stencil/core";
const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
function injectWebtoolsLoad() {
    if (!isBrowser)
        return;
    const scriptId = 'webtools-loader';
    if (!document.getElementById(scriptId)) {
        const script = document.createElement('script');
        script.id = scriptId;
        script.src = 'https://webtools.europa.eu/load.js';
        script.defer = true;
        script.type = 'text/javascript';
        document.head.appendChild(script);
    }
}
function injectThemeCss(theme) {
    if (!isBrowser)
        return;
    const existingLinks = document.querySelectorAll('link[data-ecl-theme-css]');
    // If the same theme is already injected, skip
    if (window.__eclCurrentTheme === theme)
        return;
    // Remove existing theme CSS
    existingLinks.forEach(link => link.remove());
    // Inject new theme CSS
    const themeLink = document.createElement('link');
    themeLink.rel = 'stylesheet';
    themeLink.href = `/build/styles/custom-properties-${theme}.css`;
    themeLink.setAttribute('data-ecl-theme-css', '');
    document.head.appendChild(themeLink);
    if (theme === 'ec') {
        const ecModeLink = document.createElement('link');
        ecModeLink.rel = 'stylesheet';
        ecModeLink.href = `/build/styles/ecl-ec-color-modes.css`;
        ecModeLink.setAttribute('data-ecl-theme-css', '');
        document.head.appendChild(ecModeLink);
    }
    window.__eclCurrentTheme = theme;
}
function switchTheme(theme) {
    if (!isBrowser)
        return;
    localStorage.setItem('ecl-theme', theme);
    document.documentElement.setAttribute('data-ecl-theme', theme);
    window.location.reload();
}
if (typeof window !== 'undefined') {
    window.switchTheme = switchTheme;
}
export default () => {
    if (!isBrowser) {
        setMode(() => 'ec');
        return;
    }
    const themeResolver = (elm) => {
        const theme = document.documentElement.getAttribute('data-ecl-theme') ||
            elm.getAttribute('theme') ||
            elm.theme;
        if (theme) {
            document.documentElement.setAttribute('data-ecl-theme', theme);
            injectThemeCss(theme);
            injectWebtoolsLoad();
            return theme;
        }
        else if (!elm.parentElement) {
            injectThemeCss('ec');
            injectWebtoolsLoad();
            return 'ec';
        }
        else {
            return themeResolver(elm.parentElement);
        }
    };
    setMode((elm) => {
        return themeResolver(elm);
    });
};
