import Taskbar from './components/Taskbar.js';
import StartMenu from './components/StartMenu.js';
import FileExplorer from './components/FileExplorer.js';
import Browser from './components/Browser.js';
import Settings from './components/Settings.js';
import RemoteDesktop from './components/RemoteDesktop.js';

class OSController {
    constructor() {
        this.components = {};
        this.activePopup = null;
        this.initialize();
    }

    initialize() {
        // Initialize all components
        this.components.startMenu = new StartMenu(this);
        this.components.fileExplorer = new FileExplorer(this);
        this.components.browser = new Browser(this);
        this.components.remoteDesktop = new RemoteDesktop(this);
        this.components.settings = new Settings(this);
        
        // Taskbar comes last as it needs references to others
        this.components.taskbar = new Taskbar(this);

        // Global click to close popups
        document.addEventListener('click', (e) => {
            // Check if click was inside a popup or on a taskbar button
            const isPopupClick = e.target.closest('.popup');
            const isTaskbarBtnClick = e.target.closest('.taskbar-btn');
            
            if (!isPopupClick && !isTaskbarBtnClick && this.activePopup) {
                this.closeAllPopups();
            }
        });
    }

    togglePopup(componentName) {
        const component = this.components[componentName];
        if (!component) return;

        if (this.activePopup === component) {
            this.closeAllPopups();
        } else {
            this.closeAllPopups();
            component.open();
            this.activePopup = component;
        }
    }

    closeAllPopups() {
        if (this.activePopup) {
            this.activePopup.close();
            this.activePopup = null;
        }
    }
}

// Initialize on load
window.addEventListener('DOMContentLoaded', () => {
    window.os = new OSController();
});
