/**
 * layout-manager.js
 * Manages workdesk switching and layout state
 */

class LayoutManager {
  constructor() {
    this.currentWorkdesk = null;
    this.workdesks = new Map();
    this.shell = null;
  }

  /**
   * Initialize the layout manager with a shell instance
   */
  init(shell) {
    this.shell = shell;
  }

  /**
   * Register a workdesk class for a team
   */
  registerWorkdesk(teamId, WorkdeskClass) {
    this.workdesks.set(teamId, WorkdeskClass);
  }

  /**
   * Switch to a different team's workdesk
   */
  async switchWorkdesk(teamId) {
    if (!this.shell) {
      throw new Error('LayoutManager not initialized with shell');
    }

    // Cleanup current workdesk
    if (this.currentWorkdesk) {
      this.currentWorkdesk.destroy();
      this.currentWorkdesk = null;
    }

    // Load workdesk class if not already registered
    if (!this.workdesks.has(teamId)) {
      try {
        const module = await import(`../workdesks/${teamId}-workdesk.js`);
        this.registerWorkdesk(teamId, module.default);
      } catch (error) {
        console.error(`Failed to load workdesk for team ${teamId}:`, error);
        throw error;
      }
    }

    // Create new workdesk instance
    const WorkdeskClass = this.workdesks.get(teamId);
    this.currentWorkdesk = new WorkdeskClass(this.shell);

    // Render the workdesk
    this.currentWorkdesk.render();

    return this.currentWorkdesk;
  }

  /**
   * Get the current active workdesk
   */
  getCurrentWorkdesk() {
    return this.currentWorkdesk;
  }

  /**
   * Clean up all workdesks
   */
  destroy() {
    if (this.currentWorkdesk) {
      this.currentWorkdesk.destroy();
      this.currentWorkdesk = null;
    }
    this.workdesks.clear();
  }
}

// Singleton instance
const layoutManager = new LayoutManager();

export default layoutManager;
