"use strict";
/**
 * Icon Service
 * Provides unified icon management with support for multiple providers
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.iconService = exports.IconService = void 0;
class IconService {
    constructor() {
        this.providers = new Map();
        this.packsCache = new Map();
        this.iconsCache = new Map();
        this.initializeDefaultProviders();
    }
    /**
     * Initialize default icon providers
     */
    initializeDefaultProviders() {
        // Default system icons
        this.registerProvider({
            name: 'default',
            displayName: 'System Icons',
            version: '1.0.0',
            packs: [{
                    id: 'system',
                    name: 'System Icons',
                    description: 'Basic system icons',
                    provider: 'default',
                    version: '1.0.0',
                    icons: {
                        'check': {
                            pack: 'system',
                            name: 'check',
                            label: 'Check',
                            unicode: '✓',
                            categories: ['actions'],
                            keywords: ['success', 'ok', 'valid'],
                        },
                        'close': {
                            pack: 'system',
                            name: 'close',
                            label: 'Close',
                            unicode: '✕',
                            categories: ['actions'],
                            keywords: ['cancel', 'delete', 'remove'],
                        },
                        'warning': {
                            pack: 'system',
                            name: 'warning',
                            label: 'Warning',
                            unicode: '⚠️',
                            categories: ['status'],
                            keywords: ['alert', 'caution', 'attention'],
                        },
                        'error': {
                            pack: 'system',
                            name: 'error',
                            label: 'Error',
                            unicode: '❌',
                            categories: ['status'],
                            keywords: ['failed', 'invalid', 'wrong'],
                        },
                        'info': {
                            pack: 'system',
                            name: 'info',
                            label: 'Information',
                            unicode: 'ℹ️',
                            categories: ['status'],
                            keywords: ['details', 'help', 'about'],
                        },
                        'loading': {
                            pack: 'system',
                            name: 'loading',
                            label: 'Loading',
                            unicode: '⋯',
                            categories: ['status'],
                            keywords: ['wait', 'progress', 'spinner'],
                        },
                    },
                }],
        });
        // FontAwesome provider
        this.registerProvider({
            name: 'fontawesome',
            displayName: 'Font Awesome',
            version: '6.0.0',
            config: {
                cdnUrl: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css',
                license: 'SIL OFL 1.1',
            },
            packs: [{
                    id: 'fa-solid',
                    name: 'Font Awesome Solid',
                    description: 'Font Awesome solid icons',
                    provider: 'fontawesome',
                    version: '6.0.0',
                    cssClass: 'fas',
                    icons: {
                        'home': {
                            pack: 'fa-solid',
                            name: 'home',
                            label: 'Home',
                            fontClass: 'fas fa-home',
                            categories: ['navigation'],
                            keywords: ['house', 'main', 'dashboard'],
                        },
                        'user': {
                            pack: 'fa-solid',
                            name: 'user',
                            label: 'User',
                            fontClass: 'fas fa-user',
                            categories: ['users'],
                            keywords: ['person', 'profile', 'account'],
                        },
                        'cog': {
                            pack: 'fa-solid',
                            name: 'cog',
                            label: 'Settings',
                            fontClass: 'fas fa-cog',
                            categories: ['actions'],
                            keywords: ['settings', 'config', 'options'],
                        },
                    },
                }],
        });
        // Heroicons provider
        this.registerProvider({
            name: 'heroicons',
            displayName: 'Heroicons',
            version: '2.0.0',
            config: {
                license: 'MIT',
            },
            packs: [{
                    id: 'heroicons-outline',
                    name: 'Heroicons Outline',
                    description: 'Heroicons outline style',
                    provider: 'heroicons',
                    version: '2.0.0',
                    icons: {
                        'arrow-right': {
                            pack: 'heroicons-outline',
                            name: 'arrow-right',
                            label: 'Arrow Right',
                            svg: '<svg fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" /></svg>',
                            categories: ['arrows'],
                            keywords: ['next', 'forward', 'continue'],
                        },
                        'arrow-left': {
                            pack: 'heroicons-outline',
                            name: 'arrow-left',
                            label: 'Arrow Left',
                            svg: '<svg fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" /></svg>',
                            categories: ['arrows'],
                            keywords: ['back', 'previous', 'return'],
                        },
                    },
                }],
        });
    }
    /**
     * Register a new icon provider
     */
    registerProvider(provider) {
        this.providers.set(provider.name, provider);
        // Cache all packs from this provider
        provider.packs.forEach(pack => {
            this.packsCache.set(pack.id, pack);
            // Cache all icons from this pack
            Object.entries(pack.icons).forEach(([iconId, icon]) => {
                const fullIconId = `${provider.name}:${pack.id}:${iconId}`;
                this.iconsCache.set(fullIconId, icon);
                // Also cache without provider prefix for default provider
                if (provider.name === 'default') {
                    this.iconsCache.set(`${pack.id}:${iconId}`, icon);
                    this.iconsCache.set(iconId, icon);
                }
            });
        });
    }
    /**
     * Get all available providers
     */
    getProviders() {
        return Array.from(this.providers.values());
    }
    /**
     * Get an icon by ID
     */
    getIcon(iconId, provider) {
        // Try full qualified ID first
        if (provider) {
            const fullId = `${provider}:${iconId}`;
            const icon = this.iconsCache.get(fullId);
            if (icon)
                return icon;
        }
        // Try direct lookup
        const icon = this.iconsCache.get(iconId);
        if (icon)
            return icon;
        // Try searching all providers
        for (const [providerId, providerData] of this.providers) {
            for (const pack of providerData.packs) {
                const icon = pack.icons[iconId];
                if (icon)
                    return icon;
            }
        }
        return null;
    }
    /**
     * Search icons by query and filters
     */
    searchIcons(query, filters) {
        const results = [];
        const queryLower = query.toLowerCase();
        for (const [providerId, provider] of this.providers) {
            // Skip if provider filter doesn't match
            if (filters?.provider && providerId !== filters.provider) {
                continue;
            }
            for (const pack of provider.packs) {
                for (const [iconId, icon] of Object.entries(pack.icons)) {
                    // Check if icon matches query
                    const matches = icon.name.toLowerCase().includes(queryLower) ||
                        icon.label.toLowerCase().includes(queryLower) ||
                        (icon.keywords && icon.keywords.some(keyword => keyword.toLowerCase().includes(queryLower)));
                    if (!matches)
                        continue;
                    // Check category filter
                    if (filters?.category &&
                        (!icon.categories || !icon.categories.includes(filters.category))) {
                        continue;
                    }
                    // Check variants filter
                    if (filters?.variants &&
                        (!icon.variants || !filters.variants.some(v => icon.variants.includes(v)))) {
                        continue;
                    }
                    results.push(icon);
                }
            }
        }
        return results;
    }
    /**
     * Get all icons from a specific pack
     */
    getPackIcons(packId) {
        const pack = this.packsCache.get(packId);
        if (!pack)
            return [];
        return Object.values(pack.icons);
    }
    /**
     * Get all available icon packs
     */
    getIconPacks() {
        return Array.from(this.packsCache.values());
    }
    /**
     * Get icon categories
     */
    getCategories() {
        const categories = new Set();
        for (const icon of this.iconsCache.values()) {
            if (icon.categories) {
                icon.categories.forEach(category => categories.add(category));
            }
        }
        return Array.from(categories).sort();
    }
    /**
     * Load external icon pack
     */
    async loadExternalPack(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Failed to load icon pack: ${response.statusText}`);
            }
            const packData = await response.json();
            // Validate pack structure
            if (!packData.id || !packData.name || !packData.icons) {
                throw new Error('Invalid icon pack format');
            }
            const pack = {
                id: packData.id,
                name: packData.name,
                description: packData.description || '',
                provider: packData.provider || 'external',
                version: packData.version || '1.0.0',
                icons: packData.icons,
                cssClass: packData.cssClass,
                fontUrl: packData.fontUrl,
                config: packData.config,
            };
            // Cache the pack
            this.packsCache.set(pack.id, pack);
            // Cache all icons
            Object.entries(pack.icons).forEach(([iconId, icon]) => {
                const fullIconId = `${pack.provider}:${pack.id}:${iconId}`;
                this.iconsCache.set(fullIconId, icon);
            });
            return pack;
        }
        catch (error) {
            console.error('Failed to load external icon pack:', error);
            throw error;
        }
    }
    /**
     * Generate CSS for icon packs
     */
    generateCSS() {
        let css = '';
        // Base icon styles
        css += `
.icon {
  display: inline-block;
  line-height: 1;
  text-align: center;
  vertical-align: middle;
}

.icon-xs { font-size: 0.75rem; width: 0.75rem; height: 0.75rem; }
.icon-sm { font-size: 0.875rem; width: 0.875rem; height: 0.875rem; }
.icon-md { font-size: 1rem; width: 1rem; height: 1rem; }
.icon-lg { font-size: 1.25rem; width: 1.25rem; height: 1.25rem; }
.icon-xl { font-size: 1.5rem; width: 1.5rem; height: 1.5rem; }

.icon-loading { animation: spin 1s linear infinite; }
.icon-error { color: #dc3545; }

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
`;
        // Add provider-specific styles
        for (const provider of this.providers.values()) {
            for (const pack of provider.packs) {
                if (pack.cssClass) {
                    css += `\n.icon-${provider.name} { font-family: "${pack.name}"; }`;
                }
            }
        }
        return css;
    }
    /**
     * Get icon statistics
     */
    getStatistics() {
        const iconsByProvider = {};
        const iconsByCategory = {};
        for (const provider of this.providers.values()) {
            let providerIconCount = 0;
            for (const pack of provider.packs) {
                providerIconCount += Object.keys(pack.icons).length;
                // Count by category
                for (const icon of Object.values(pack.icons)) {
                    if (icon.categories) {
                        icon.categories.forEach(category => {
                            iconsByCategory[category] = (iconsByCategory[category] || 0) + 1;
                        });
                    }
                }
            }
            iconsByProvider[provider.name] = providerIconCount;
        }
        return {
            totalIcons: this.iconsCache.size,
            totalProviders: this.providers.size,
            totalPacks: this.packsCache.size,
            iconsByProvider,
            iconsByCategory,
        };
    }
}
exports.IconService = IconService;
// Create singleton instance
exports.iconService = new IconService();
exports.default = exports.iconService;
//# sourceMappingURL=icon-service.js.map