/**
 * @web/loader
 * 极简模块调度中心
 */

const DEFAULT_VERSIONS = {
    'state': '1.0.11',
    'bootstrap': '1.0.3',
    'base': '1.0.7',
    'datatable': '1.0.6',
    'kanban': '1.0.0',
    'mindmap': '1.0.0',
    'chart': '1.0.0',
    'editor': '1.0.0',
    'loader': '1.0.2'
};

const Loader = {
    load: (...pkgs) => {
        if (typeof document === 'undefined') return;

        const currentScript = document.currentScript;
        const currentUrl = currentScript ? currentScript.src : '';
        
        // 1. 默认模板 (jsDelivr)
        let tpl = 'https://cdn.jsdelivr.net/npm/@apigo.cc/{project}@{tag}/dist/{project}.min.js';

        // 2. 根据当前 loader.js 来源自动适配镜像
        if (currentUrl) {
            if (currentUrl.includes('esm.sh')) {
                tpl = 'https://esm.sh/@apigo.cc/{project}@{tag}/dist/{project}.min.js';
            } else if (currentUrl.includes('unpkg.com')) {
                tpl = 'https://unpkg.com/@apigo.cc/{project}@{tag}/dist/{project}.min.js';
            } else if (currentUrl.includes('unpkg.zhimg.com')) {
                tpl = 'https://unpkg.zhimg.com/@apigo.cc/{project}@{tag}/dist/{project}.min.js';
            } else if (currentUrl.includes('npm.elemecdn.com')) {
                tpl = 'https://npm.elemecdn.com/@apigo.cc/{project}@{tag}/dist/{project}.min.js';
            } else if (currentUrl.includes('jsdelivr.net')) {
                tpl = 'https://cdn.jsdelivr.net/npm/@apigo.cc/{project}@{tag}/dist/{project}.min.js';
            }
        }

        const importMap = { imports: {} };

        pkgs.forEach(pkg => {
            let [name, version] = pkg.split(':');
            const key = name.toLowerCase();
            const fullKey = `@apigo.cc/${key}`;

            let url = '';
            // 优先检查本地 localStorage 重定向配置，方便开发调试
            try {
                if (typeof localStorage !== 'undefined') {
                    url = localStorage.getItem(`dev:${fullKey}`) || '';
                }
            } catch (e) {}

            if (!url) {
                version = version || DEFAULT_VERSIONS[key] || 'latest';
                url = tpl.replace(/{project}/g, key).replace(/{tag}/g, version);
            }
            importMap.imports[fullKey] = url;
        });

        const script = document.createElement('script');
        script.type = 'importmap';
        script.textContent = JSON.stringify(importMap);
        
        if (currentScript) {
            currentScript.parentNode.insertBefore(script, currentScript);
        } else {
            document.head.appendChild(script);
        }
    }
};

// 挂载到全局
globalThis.Loader = Loader;

export { Loader };
export default Loader;
