// This script runs in the "Isolated World"
// It injects the bot script into the "Main World" (Page Context)

(async function () {
    console.log('[Magic Bot Extension] Initializing...');

    // 2. Inject Modules
    const modules = [
        'modules/core.js',
        'modules/socket.js',
        'modules/state.js',
        'modules/commands.js',
        'modules/decision.js',
        'modules/main.js',
        
        // UI Modules (ES Modules required)
        'modules/ui/ui_manager.js' 
    ];
    
    // Note: Since ui_manager.js uses ES imports (import ... from ...), 
    // we MUST load it as type="module".
    // Also, core/socket/etc are currently "script" (globals).
    // We can leave legacy modules as scripts, but the new UI manager is an ES module.
    
    // Legacy Modules (Synchronous-ish load)
    const legacyModules = [
        'modules/core.js',
        'modules/socket.js',
        'modules/state.js',
        'modules/commands.js',
        'modules/decision.js',
        'modules/main.js' 
    ];

    legacyModules.forEach(file => {
        const s = document.createElement('script');
        s.src = chrome.runtime.getURL(file);
        s.onload = function () { this.remove(); };
        (document.head || document.documentElement).appendChild(s);
    });

    // UI Manager (Module)
    // Wait a brief moment for legacy modules to be defined on window?
    setTimeout(() => {
        const s = document.createElement('script');
        s.type = 'module';
        s.src = chrome.runtime.getURL('modules/ui/ui_manager.js');
        s.onload = function () { this.remove(); };
        (document.head || document.documentElement).appendChild(s);
    }, 500);

    console.log('[Magic Bot Extension] Modules injection started.');
})();
