// #region Imports
/**
 * Creates an items provider function for Google Fonts.
 * This provider can be used with the AutoCompleteBox component to provide
 * font family suggestions from the Google Fonts API.
 *
 * @example
 * ```typescript
 * const fontProvider = createGoogleFontsProvider({
 *   apiKey: 'YOUR_API_KEY',
 *   sort: 'popularity',
 *   pageSize: 30
 * });
 *
 * // Use with AutoCompleteBox
 * element.itemsProvider = fontProvider;
 * element.displayMemberPath = 'family';
 * element.valueMemberPath = 'family';
 * ```
 *
 * @public
 * @param options - The provider options.
 * @returns An ItemsProviderFn that fetches fonts from the Google Fonts API.
 */
export function createGoogleFontsProvider(options) {
    const { apiKey, sort = 'alpha', subset, pageSize = 50, cache = true } = options;
    let cachedFonts = null;
    let cachePromise = null;
    /**
     * Fetches all fonts from the Google Fonts API.
     */
    const fetchAllFonts = async (signal) => {
        // Return cached results if available
        if (cache && cachedFonts) {
            return cachedFonts;
        }
        // Return existing promise if a fetch is in progress
        if (cache && cachePromise) {
            return cachePromise;
        }
        const fetchPromise = (async () => {
            const url = new URL('https://www.googleapis.com/webfonts/v1/webfonts');
            url.searchParams.set('key', apiKey);
            url.searchParams.set('sort', sort);
            if (subset) {
                url.searchParams.set('subset', subset);
            }
            const response = await fetch(url.toString(), { signal });
            if (!response.ok) {
                throw new Error(`Failed to fetch Google Fonts: ${response.statusText}`);
            }
            const data = await response.json();
            if (cache) {
                cachedFonts = data.items;
            }
            return data.items;
        })();
        if (cache) {
            cachePromise = fetchPromise;
        }
        try {
            return await fetchPromise;
        }
        finally {
            if (cache) {
                cachePromise = null;
            }
        }
    };
    /**
     * Filters fonts based on search text.
     */
    const filterFonts = (fonts, searchText) => {
        if (!searchText || searchText.trim().length === 0) {
            return fonts.slice(0, pageSize);
        }
        const normalizedSearch = searchText.toLowerCase().trim();
        return fonts
            .filter((font) => font.family.toLowerCase().includes(normalizedSearch))
            .slice(0, pageSize);
    };
    /**
     * The items provider function.
     */
    return async (request) => {
        const { searchText, signal } = request;
        try {
            const allFonts = await fetchAllFonts(signal);
            return filterFonts(allFonts, searchText);
        }
        catch (error) {
            // Handle abort errors silently
            if (error instanceof Error && error.name === 'AbortError') {
                return [];
            }
            throw error;
        }
    };
}
/**
 * Clears the cache of the Google Fonts provider.
 * Call this if you need to refresh the font list.
 *
 * @public
 * @param provider - The provider function to clear cache for.
 */
export function clearGoogleFontsCache(provider) {
    // Note: Due to closure, we cannot directly clear the cache from outside.
    // Users should recreate the provider if they need fresh data.
    void provider;
}
/**
 * Loads a Google Font dynamically.
 * This can be used in combination with the renderItem function to preview fonts.
 *
 * @example
 * ```typescript
 * element.renderItem = (item: IGoogleFont, index: number) => {
 *   loadGoogleFont(item.family);
 *   return html`<span style="font-family: '${item.family}'">${item.family}</span>`;
 * };
 * ```
 *
 * @public
 * @param family - The font family name to load.
 * @param variants - Optional array of variants to load (default: ['regular']).
 */
export function loadGoogleFont(family, variants = ['regular']) {
    const variantsParam = variants
        .map((v) => v === 'regular' ? '' : v)
        .filter(Boolean)
        .join(',');
    const familyParam = variantsParam
        ? `${family}:${variantsParam}`
        : family;
    const encodedFamily = encodeURIComponent(familyParam);
    const linkId = `google-font-${encodedFamily.replace(/%20/g, '-').toLowerCase()}`;
    // Check if already loaded
    if (document.getElementById(linkId)) {
        return;
    }
    const link = document.createElement('link');
    link.id = linkId;
    link.rel = 'stylesheet';
    link.href = `https://fonts.googleapis.com/css2?family=${encodedFamily}&display=swap`;
    document.head.appendChild(link);
}
/**
 * Creates a simple local fonts provider that doesn't require an API key.
 * Uses a predefined list of common fonts.
 *
 * @example
 * ```typescript
 * const fontProvider = createLocalFontsProvider();
 * element.itemsProvider = fontProvider;
 * ```
 *
 * @public
 * @returns An ItemsProviderFn that provides a list of common fonts.
 */
export function createLocalFontsProvider() {
    const commonFonts = [
        {
            family: 'Arial',
            category: 'sans-serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Comic Sans MS',
            category: 'handwriting',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Courier New',
            category: 'monospace',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Georgia',
            category: 'serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Helvetica',
            category: 'sans-serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Impact',
            category: 'display',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Inter',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Lato',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Montserrat',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Open Sans',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Oswald',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Playfair Display',
            category: 'serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Poppins',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Roboto',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Source Code Pro',
            category: 'monospace',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Tahoma',
            category: 'sans-serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Times New Roman',
            category: 'serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Trebuchet MS',
            category: 'sans-serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Ubuntu',
            category: 'sans-serif',
            variants: ['regular', '700'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        },
        {
            family: 'Verdana',
            category: 'sans-serif',
            variants: ['regular'],
            subsets: ['latin'],
            version: '',
            lastModified: '',
            files: {}
        }
    ];
    return (request) => {
        const { searchText } = request;
        if (!searchText || searchText.trim().length === 0) {
            return commonFonts;
        }
        const normalizedSearch = searchText.toLowerCase().trim();
        return commonFonts.filter((font) => font.family.toLowerCase().includes(normalizedSearch));
    };
}
//# sourceMappingURL=GoogleFontsProvider.js.map