(function () {
    const cache = new Map();

    async function loadPack(url) {
        if (cache.has(url)) {
            return cache.get(url);
        }

        const response = await fetch(url, { cache: 'force-cache' });

        if (!response.ok) {
            throw new Error('Unable to load icon pack: ' + url);
        }

        const data = await response.json();
        cache.set(url, data);

        return data;
    }

    function searchIcons(pack, term, limit = 300) {
        term = String(term || '').toLowerCase().trim();

        const icons = Array.isArray(pack.icons) ? pack.icons : [];

        if (!term) {
            return icons.slice(0, limit);
        }

        const results = [];

        for (const icon of icons) {
            const haystack = [
                icon.name,
                icon.label,
                icon.className,
                icon.style,
                ...(icon.categories || []),
                ...(icon.aliases || []),
                ...(icon.keywords || []),
                ...(icon.searchTerms || [])
            ].join(' ').toLowerCase();

            if (haystack.includes(term)) {
                results.push(icon);
            }

            if (results.length >= limit) {
                break;
            }
        }

        return results;
    }

    function renderIcon(icon) {
        if (!icon) {
            return '';
        }

        const className = typeof icon === 'string'
            ? icon
            : icon.className;

        if (!className) {
            return '';
        }

        return '<i class="' + String(className).replaceAll('"', '&quot;') + '"></i>';
    }

    window.PpIconManager = {
        loadPack,
        searchIcons,
        renderIcon
    };
})();