import { registerGlobalStyles } from '@melodicdev/core';
const phosphorWeightCss = {
    thin: './fonts/phosphor/thin/style.css',
    light: './fonts/phosphor/light/style.css',
    regular: './fonts/phosphor/regular/style.css',
    bold: './fonts/phosphor/bold/style.css',
    fill: './fonts/phosphor/fill/style.css',
    duotone: './fonts/phosphor/duotone/style.css'
};
const phosphorWeightClass = {
    thin: 'ph-thin',
    light: 'ph-light',
    regular: 'ph',
    bold: 'ph-bold',
    fill: 'ph-fill',
    duotone: 'ph-duotone'
};
const weightStates = new Map();
const supportsConstructableStylesheets = () => 'adoptedStyleSheets' in Document.prototype && 'replaceSync' in CSSStyleSheet.prototype;
const ensureWeightState = (weight) => {
    let state = weightStates.get(weight);
    if (!state) {
        state = { loaded: false };
        weightStates.set(weight, state);
    }
    return state;
};
const absolutizeFontUrls = (cssText, cssUrl) => {
    const baseUrl = new URL('.', cssUrl).href;
    return cssText.replace(/url\((['"]?)\.\/(.*?)\1\)/g, (_match, quote, file) => {
        const url = `${baseUrl}${file}`;
        return `url(${quote}${url}${quote})`;
    });
};
/**
 * Get the URL for a Phosphor font weight stylesheet.
 */
export function getPhosphorFontUrl(weight = 'regular') {
    return new URL(phosphorWeightCss[weight], import.meta.url).href;
}
/**
 * Ensure Phosphor font styles are available in a shadow root.
 * Injects a <link> element that the browser loads natively.
 */
export function ensurePhosphorFontStyles(weight = 'regular') {
    if (typeof document === 'undefined') {
        return;
    }
    const state = ensureWeightState(weight);
    if (state.loaded || state.loading) {
        return;
    }
    const cssUrl = getPhosphorFontUrl(weight);
    state.loading = fetch(cssUrl)
        .then((response) => response.text())
        .then((cssText) => {
        const resolvedCss = absolutizeFontUrls(cssText, cssUrl);
        if (supportsConstructableStylesheets()) {
            const sheet = new CSSStyleSheet();
            sheet.replaceSync(resolvedCss);
            registerGlobalStyles(sheet);
        }
        else {
            registerGlobalStyles(resolvedCss);
        }
        state.loaded = true;
    })
        .catch((error) => {
        console.warn(`Failed to load Phosphor font styles: ${weight}`, error);
    })
        .finally(() => {
        state.loading = undefined;
    });
}
export function getPhosphorFontClass(weight = 'regular') {
    return phosphorWeightClass[weight] ?? phosphorWeightClass.regular;
}
