// Filename: frontend/js/main.js

// === 1. 导入通用组件 (这些是所有页面都可能用到的，保持静态导入) ===
import SlidingTabs from './components/slidingTabs.js';
import CustomSelect from './components/customSelect.js';
import { modalManager, uiPatterns } from './components/ui.js';
import { taskCenterManager, toastManager} from './components/taskCenter.js';
// === 2. 导入布局专属的初始化模块 ===
import initLayout from './layout/base.js';
// === 3. 定义动态导入的页面模块映射 ===
const pageModules = {
    // 键 'dashboard' 对应一个函数，该函数调用 import() 返回一个 Promise
    // esbuild 看到这个 import() 语法，就会自动将 dashboard.js 及其依赖打包成一个独立的 chunk 文件
    'dashboard': () => import('./pages/dashboard.js'),
    'keys': () => import('./pages/keys/index.js'),
    'logs': () => import('./pages/logs/index.js'), 
    // 'settings': () => import('./pages/settings.js'), // 未来启用 settings 页面
    // 未来新增的页面，只需在这里添加一行映射，esbuild会自动处理
};
// === 4. 主执行逻辑，现在是异步的 ===
document.addEventListener('DOMContentLoaded', async () => { 
    initLayout(); 
    // --- 通用组件初始化 (总会执行) ---
    const allTabContainers = document.querySelectorAll('[data-sliding-tabs-container]');
    allTabContainers.forEach(container => new SlidingTabs(container));
    const allSelectContainers = document.querySelectorAll('[data-custom-select-container]');
    allSelectContainers.forEach(container => new CustomSelect(container));
    taskCenterManager.init();
    
    // --- 页面专属逻辑调度 (按需执行) ---
    const pageContainer = document.querySelector('[data-page-id]');
    if (pageContainer) {
        const pageId = pageContainer.dataset.pageId;
        if (pageId && pageModules[pageId]) {
            try {
                const pageModule = await pageModules[pageId](); 
                if (pageModule.default && typeof pageModule.default === 'function') {
                    pageModule.default();
                }
            } catch (error) {
                console.error(`Failed to load module for page: ${pageId}`, error);
            }
        }
    }
});
// 将管理器挂载到全局，方便在浏览器控制台调试
window.modalManager = modalManager;
window.taskCenterManager = taskCenterManager;
window.toastManager = toastManager;
window.uiPatterns = uiPatterns;
