// Auto-extracted from apps-manager.js (verbatim) — augments AppsManager.prototype. Loaded after the base.
Object.assign(AppsManager.prototype, {
  // Initialize port managers after DOM is ready
  async initializePortManagers() {
    //// // console.log('🔌 Looking for port manager containers...');
    const portContainers = document.querySelectorAll('.port-manager-container');
    //// // console.log(`🔌 Found ${portContainers.length} port manager containers`);
    
    // Group port containers by app
    const appPortContainers = {};
    for (const container of portContainers) {
      const appName = container.dataset.appName;
      if (!appPortContainers[appName]) {
        appPortContainers[appName] = [];
      }
      appPortContainers[appName].push(container);
    }
    
    // Create one consolidated port manager per app
    for (const [appName, containers] of Object.entries(appPortContainers)) {
      //// // console.log(`🔌 Creating consolidated port manager for app: ${appName} with ${containers.length} port fields`);
      
      try {
        // Get all port configurations for this app
        const appConfig = this.getCurrentAppConfig();
        const allPortConfigs = this.getAllPortConfigs(appConfig, appName);
        
        // Create consolidated port manager
        const portManager = new PortManager();
        const html = portManager.generateHTML(appName, allPortConfigs);
        
        // Replace the first container with the consolidated port manager
        const firstContainer = containers[0];
        firstContainer.innerHTML = html;
        
        // Hide other port containers (PORT_2, PORT_3, etc.) and their labels
        for (let i = 1; i < containers.length; i++) {
          const container = containers[i];
          const formField = container.closest('.form-field');
          if (formField) {
            formField.style.display = 'none';
          } else {
            container.style.display = 'none';
          }
        }
        
        // Hide labels and help text for the first port container
        this.hidePortFieldLabels(containers[0]);
        
        // Initialize port manager with services
        await portManager.initialize(appName);
        //// // console.log(`🔌 Consolidated port manager initialized successfully for ${appName}`);
      } catch (error) {
        console.error(`Error initializing consolidated port manager for ${appName}:`, error);
        containers[0].innerHTML = `<div class="error">Failed to initialize port manager: ${error.message}</div>`;
      }
    }
  },
  // Hide labels and help text for port field containers
  hidePortFieldLabels(container) {
    const formField = container.closest('.form-field');
    if (formField) {
      // Hide the label
      const label = formField.querySelector('label.form-label');
      if (label) {
        label.style.display = 'none';
      }
      
      // Hide the help text
      const helpText = formField.querySelector('small.form-help');
      if (helpText) {
        helpText.style.display = 'none';
      }
      
      // Hide any help icons
      const helpIcons = formField.querySelectorAll('.help-icon');
      helpIcons.forEach(icon => {
        icon.style.display = 'none';
      });
    }
  },
  // Get all port configurations for an app
  getAllPortConfigs(appConfig, appName) {
    const portConfigs = [];
    const portPrefix = `CFG_${appName.toUpperCase()}_PORT_`;
    Object.keys(appConfig).forEach(key => {
      if (key.startsWith(portPrefix)) {
        const configValue = appConfig[key];
        if (configValue && configValue.trim() !== '') {
          portConfigs.push(configValue);
        }
      }
    });
    // Return as array — one CFG_<APP>_PORT_N value per element. The
    // port manager iterates this directly so commas inside fields
    // (multi-button labels / paths) stay meaningful and hand-editable.
    return portConfigs;
  },
});
