import { moduleConfig } from './config.js';
import { Logger } from '../core/logger.js';

export const activeModules = new Map(); // key: modulename → { mod, config }

export async function registerModules() {
    const modules = import.meta.glob('./*/index.js', { eager: true });

    const domModules = new Set(
        Array.from(document.querySelectorAll('[data-module]')).map(el => el.dataset.module).filter(Boolean)
    );

    const usedModules = new Set(domModules);
    const fallbackMode = usedModules.size === 0;

    Object.entries(modules).forEach(([path, mod]) => {
        const name = path.split('/').slice(-2, -1)[0]; // z.B. "noise-toggle.js"
        const config = moduleConfig[name] || {};

        if(!fallbackMode && !usedModules.has(name)) {
            Logger.info(`⏭️ [Module] Skipped (not used in DOM): ${name}`);
            return;
        }

        if (typeof mod.init === 'function') {
            mod.init(config);
            activeModules.set(name, { mod, config });
            Logger.info(`✅ [Module] Initialized: ${name}`);
        } else {
            Logger.warn(`⛔ [Module] No init() in ${name}`);
        }
    });

    if (fallbackMode) {
        Logger.info('⚠️ [Module] No data-module usage detected, fallback to full init mode');
    }
}

export function destroyModules() {
    for (const [name, { mod }] of activeModules.entries()) {
        if (typeof mod.destroy === 'function') {
            mod.destroy();
            Logger.info(`🧹 [Module] Destroyed: ${name}`);
        }
    }
    activeModules.clear();
}
