/*!
 * Custom elements for Nanopore-Digital Web applications
 */
let cachedCSStylesheet;
/**
 * Adds the global nano-components stylesheets as a constructable stylesheet to a shadow root.
 * This is useful when shadow DOM enabled components:
 * - use css-only components
 * - use themed sections within their markup (i.e. `<div class="nano-theme-darK">Always dark themed section</div>`)
 *
 * @param shadowRoot - The shadow root to add the stylesheet to
 */
function addGlobalStylesheetToShadow(shadowRoot) {
    if (!shadowRoot)
        return;
    if (cachedCSStylesheet) {
        // we've already constructed the stylesheet
        shadowRoot.adoptedStyleSheets.push(cachedCSStylesheet);
        return;
    }
    const globalStylesheets = document.styleSheets;
    let stylesheet = null;
    let rule = null;
    const globalStylesheet = [];
    for (stylesheet of globalStylesheets) {
        if (!(stylesheet instanceof CSSStyleSheet)) {
            continue;
        }
        let cssRules;
        try {
            // Attempt to access the cssRules of the stylesheet
            cssRules = stylesheet?.cssRules;
            // no cssRules? skip it
            if (!cssRules)
                continue;
        }
        catch (e) {
            // some stylesheets may not be accessible due to CORS or other restrictions
            console.warn('Unable to access stylesheet:', stylesheet, e);
            continue;
        }
        for (rule of cssRules) {
            // arbitrary piece of text to check for that appears early in the `nano-components` stylesheet
            // this is a bit fragile but does the job
            if (rule instanceof CSSLayerBlockRule &&
                rule.cssText.indexOf('.nano-toast-stack') > -1) {
                globalStylesheet.push(stylesheet);
            }
            if (rule instanceof CSSLayerBlockRule &&
                rule.cssText.indexOf('.nano-theme') > -1) {
                globalStylesheet.push(stylesheet);
            }
        }
    }
    if (globalStylesheet.length) {
        // if we found the global stylesheet, add it to the shadow root
        const sheet = new CSSStyleSheet();
        for (const globalSheet of globalStylesheet) {
            for (const rule of globalSheet.cssRules) {
                sheet.insertRule(rule.cssText);
            }
        }
        cachedCSStylesheet = sheet;
        shadowRoot.adoptedStyleSheets.push(sheet);
        return;
    }
    console.warn('No global stylesheet found');
}

export { addGlobalStylesheetToShadow as a };
