/**
 * Lazy MDI icon path lookup.
 *
 * Instead of `import * as mdi from '@mdi/js'` (which loads ~5MB of SVG paths
 * into memory), this module loads the full set once on first use and caches it.
 * Vite only processes the import once, reducing HMR memory pressure.
 *
 * Uses $state so that components re-render once the icon module finishes loading
 * (fixes icons not appearing until page reload after cache-clearing navigations).
 */

let _cache: Record<string, string> | null = null;
let _ready = $state<Record<string, string> | null>(null);

async function _load(): Promise<Record<string, string>> {
	if (_cache) return _cache;
	const mod = await import('@mdi/js');
	_cache = mod as unknown as Record<string, string>;
	return _cache;
}

// Eagerly load on module init (runs once)
_load().then(m => { _ready = m; });

/**
 * Get SVG path for an icon name. Returns empty string if not found or not yet loaded.
 */
export function getMdiPath(name: string): string {
	if (!name || !_ready) return '';
	return (_ready as any)[name] || '';
}

/**
 * Get all icon names (for IconPicker search). Returns empty array if not yet loaded.
 */
export function getAllMdiNames(): string[] {
	if (!_ready) return [];
	return Object.keys(_ready).filter(k => k.startsWith('mdi') && k !== 'default');
}
