// Main System Orchestrator - Ties together loading, setup, and initialization
class SystemOrchestrator {
  constructor() {
    // console.log('🏗️ SystemOrchestrator: Constructor called');
    this.systemLoader = null;
    this.loadingUI = null;
    this.setupDetector = null;
    this.isInitialized = false;
    this.loadingPromise = null;
  }

  // Initialize the entire system
  async initialize() {
    // console.log('🚀 SystemOrchestrator: initialize() called');
    
    if (this.isInitialized) {
      // console.log('🔄 SystemOrchestrator: Already initialized, returning existing promise');
      return this.loadingPromise;
    }

    // console.log('🆕 SystemOrchestrator: Starting initialization...');
    try {
      // Auth gate — must complete before anything else loads or fetches data
      if (window.authManager) {
        await window.authManager.initialize();
        window.authManager.interceptFetch();
      }

      // console.log('🚀 System Orchestrator: Initializing...');

      // Initialize components
      // console.log('🔧 SystemOrchestrator: Creating SystemLoader...');
      this.systemLoader = new SystemLoader();
      
      // console.log('🎨 SystemOrchestrator: Creating LoadingUI...');
      this.loadingUI = new LoadingUI();
      
      // console.log('🔍 SystemOrchestrator: Creating SetupDetector...');
      this.setupDetector = new SetupDetector();

      // Show loading screen
      // console.log('📺 SystemOrchestrator: Showing loading screen...');
      this.loadingUI.initialize();

      // Setup event listeners
      this.setupEventListeners();

      // Check if first-time setup is needed
      const setupStatus = await this.setupDetector.initialize();
      
      const hasActiveHandoff = (() => {
        try { return !!sessionStorage.getItem('libreportal_setup_handoff'); }
        catch { return false; }
      })();

      if (setupStatus.isFirstTime && !hasActiveHandoff) {
        // console.log('🔧 First-time setup detected');
        await this.handleFirstTimeSetup();
      } else if (setupStatus.isFirstTime && hasActiveHandoff) {
        console.log('[orchestrator] setup handoff in progress, skipping wizard');
        await this.handleNormalLoading();
      } else {
        // console.log('✅ Returning user detected, proceeding with normal loading');
        await this.handleNormalLoading();
      }

      this.isInitialized = true;
      // console.log('✅ System Orchestrator: Initialization complete');

    } catch (error) {
      console.error('❌ System Orchestrator: Initialization failed:', error);
      this.handleInitializationError(error);
      throw error;
    }
  }

  // Setup event listeners
  setupEventListeners() {
    // System Loader events
    this.systemLoader.on('onProgress', (data) => {
      this.loadingUI.updateProgress(data.progress, `${data.checkName}...`);
      this.loadingUI.updateSystemCheck(
        data.systemId || this.getSystemIdFromCheck(data.checkId), // Use systemId if available, fallback to mapping
        data.checkName,
        data.status,
        data.error,
        data.message // Pass the message for tooltip
      );
    });

    this.systemLoader.on('onSystemCheck', (data) => {
      this.loadingUI.updateSystemCheck(
        data.systemId,
        data.checkName,
        data.status
      );
    });

    this.systemLoader.on('onComplete', (data) => {
      // console.log('✅ System Loader completed:', data.success ? 'SUCCESS' : 'FAILED');
      
      // Don't show errors here - let handleNormalLoading handle all error display logic
      if (data.success) {
        this.proceedToApplication();
      }
      // Errors will be handled in handleNormalLoading method
    });

    this.systemLoader.on('onError', (data) => {
      console.error('System Loader Error:', data);
    });

    // Override loading UI retry behavior
    this.loadingUI.onRetry = () => {
      this.retryInitialization();
    };
  }

  // Handle first-time setup
  async handleFirstTimeSetup() {
    // console.log('🎯 Starting first-time setup flow...');
    
    return new Promise((resolve, reject) => {
      // Create and show setup wizard
      const setupWizard = new SetupWizard();
      setupWizard.initialize(this.setupDetector, async () => {
        try {
          // Setup completed, continue with normal loading
          await this.handleNormalLoading();
          resolve();
        } catch (error) {
          reject(error);
        }
      });
      
      setupWizard.show();
    });
  }

  // Handle normal loading sequence
  async handleNormalLoading() {
    // console.log('📊 Starting normal loading sequence...');
    
    // Wait longer for all scripts to fully load
    await new Promise(resolve => setTimeout(resolve, 2500));
    
    // Run health checks
    const results = await this.systemLoader.runHealthChecks();
    
    // Check for missing data files specifically
    const missingDataFiles = results.errors.filter(error => 
      error.error && (error.error.includes('Missing required data file') || 
                     error.error.includes('libreportal webui generate all ') ||
                     error.error.includes('Critical configuration files are missing or empty'))
    );
    
    if (missingDataFiles.length > 0) {
      console.warn('⚠️ Missing LibrePortal data files detected');
      // console.log('🔍 Showing enhanced error for missing data files');
      
      // Show enhanced error message with setup instructions
      const enhancedErrors = results.errors.map(error => {
        if (error.error && (error.error.includes('Missing required data file') || 
                           error.error.includes('Critical configuration files are missing or empty'))) {
          return {
            ...error,
            error: `${error.error}\n\n🔧 TO FIX: Run this command in your terminal:\n   libreportal webui generate all \n\nThis will generate all required JSON files for the LibrePortal WebUI.`
          };
        }
        return error;
      });
      
      console.error('❌ Critical systems failed:', enhancedErrors);
      console.error('❌ Failed systems details:', JSON.stringify(enhancedErrors, null, 2));
      
      // Show enhanced errors in loading UI
      this.loadingUI.showError(enhancedErrors);
      
      // Listen for continue button click
      window.addEventListener('loadingContinue', () => {
        // console.log('🔄 User chose to continue despite errors');
        this.proceedToApplicationWithErrors();
      }, { once: true }); // Remove listener after first use
      this.errorAlreadyHandled = true;
      // console.log('🔍 Set errorAlreadyHandled = true, returning early');
      return; // Prevent reaching the general error handling below
    }
    
    if (results.success) {
      // console.log('✅ All systems passed health checks');

      // Initialize all components (even if some health checks failed)
      // console.log('🚨 BREAKPOINT: About to call initializeComponents()');
      await this.systemLoader.initializeComponents();
      // console.log('🚨 BREAKPOINT: initializeComponents() completed');

      // Hide loading screen only if everything is successful
      this.loadingUI.hide();

      // Now initialize the SPA after all components are ready
      this.initializeOriginalSPA();
      this.proceedToApplication();
    } else {
      // console.log('🔍 General error handling - errorAlreadyHandled:', this.errorAlreadyHandled);
      console.error('❌ Critical systems failed:', results.errors);
      console.error('❌ Failed systems details:', JSON.stringify(results.errors, null, 2));
      
      // Show errors in loading UI and keep it visible (only if not already handled)
      if (!this.errorAlreadyHandled) {
        // console.log('🔍 Showing general error (not already handled)');
        this.loadingUI.showError(results.errors);
      } else {
        // console.log('🔍 Skipping general error display (already handled)');
      }
      
      // Listen for continue button click
      window.addEventListener('loadingContinue', () => {
        // console.log('🔄 User chose to continue despite errors');
        this.proceedToApplicationWithErrors();
      }, { once: true }); // Remove listener after first use
    }
  }

  // Proceed to main application
  proceedToApplication() {
    // console.log('🎯 Proceeding to main application...');
    
    // Don't initialize SPA here - wait for component initialization to complete
    // SPA will be initialized after all components are ready
  }

  // Proceed with application despite errors (user choice)
  async proceedToApplicationWithErrors() {
    // console.log('🎯 Proceeding with application despite errors...');
    
    // Initialize components even though some checks failed
    // console.log('🚨 BREAKPOINT: About to call initializeComponents() with errors');
    await this.systemLoader.initializeComponents();
    // console.log('🚨 BREAKPOINT: initializeComponents() completed with errors');
    
    // Hide loading screen and proceed
    this.loadingUI.hide();

    // Now initialize the SPA after all components are ready
    this.initializeOriginalSPA();
    this._wireLogout();

    this.proceedToApplication();
  }

  // Initialize the original SPA system
  initializeOriginalSPA() {
    // console.log('🔄 Initializing original SPA...');
    
    if (typeof window.spaClean !== 'undefined') {
      // console.log('✅ SPA instance already initialized by SystemLoader');
      
      // Now manually call the SPA's init method since we prevented auto-initialization
      if (typeof window.spaClean.init === 'function') {
        // console.log('🔄 Manually calling SPA init()...');
        window.spaClean.init().then(() => {
          // console.log('✅ SPA initialization completed');
        }).catch(error => {
          console.error('❌ SPA initialization failed:', error);
        });
      }
      
    } else if (typeof LibrePortalSPAClean !== 'undefined') {
      // console.log('🔄 Creating SPA instance manually...');
      window.spaClean = new LibrePortalSPAClean();
      // console.log('✅ SPA instance created');
    } else {
      console.error('❌ SPA class not available');
      return;
    }
  }

  // Handle initialization errors
  handleInitializationError(error) {
    console.error('❌ Critical initialization error:', error);
    
    // Show error in loading UI
    this.loadingUI.showError([{
      system: 'System Orchestrator',
      check: 'Initialization',
      error: error.message
    }]);

    // Show retry button
    const retryButton = document.getElementById('retry-button');
    if (retryButton) {
      retryButton.style.display = 'inline-block';
    }
  }

  // Retry initialization
  async retryInitialization() {
    // console.log('🔄 Retrying initialization...');
    
    // Reset UI
    this.loadingUI.reset();
    
    // Reset state
    this.isInitialized = false;
    this.loadingPromise = null;
    
    // Try again
    await this.initialize();
  }

  // Get system ID from check ID
  getSystemIdFromCheck(checkId) {
    // Map check IDs to system IDs
    const checkToSystemMap = {
      'dom': 'core',
      'spa': 'core',
      'utils': 'core',
      'data-loader': 'core',
      'config-files': 'config-validation', // Fixed: moved to config-validation system
      'update-lock': 'update-lock', // Update Lock check
      'pause-lock': 'pause-lock', // Pause Lock check
      'system-locks-combined': 'system-locks', // System Locks check
      'apps-data': 'data',
      'categories-data': 'data',
      'config-data': 'data',
      'topbar': 'components',
      'notifications': 'components',
      'task-manager': 'task',
      'apps-manager': 'managers',
      'config-manager': 'managers',
      'app-tabbed-manager': 'managers',
      'server-connectivity': 'backend',
      'api-endpoints': 'backend'
    };

    return checkToSystemMap[checkId] || 'core';
  }

  // Get current status
  getStatus() {
    return {
      initialized: this.isInitialized,
      loading: this.loadingPromise !== null && !this.isInitialized,
      setup: this.setupDetector?.getSetupStatus(),
      systemSummary: this.systemLoader?.getSystemSummary()
    };
  }

  // Force re-initialization (for testing)
  async forceReinitialize() {
    // console.log('🔄 Force re-initializing...');
    
    // Clean up
    if (this.loadingUI && this.loadingUI.isVisible) {
      this.loadingUI.hide();
    }
    
    // Reset state
    this.isInitialized = false;
    this.loadingPromise = null;
    
    // Re-initialize
    await this.initialize();
  }
}

// Global instance and initialization
window.SystemOrchestrator = SystemOrchestrator;

// Auto-initialize when DOM is ready
if (document.readyState === 'loading') {
  // console.log('🔄 SystemOrchestrator: DOM not ready, adding listener');
  document.addEventListener('DOMContentLoaded', async () => {
    // console.log('🚀 SystemOrchestrator: DOM ready, initializing...');
    window.systemOrchestrator = new SystemOrchestrator();
    await window.systemOrchestrator.initialize();
  });
} else {
  // DOM already ready
  // console.log('🚀 SystemOrchestrator: DOM already ready, initializing immediately...');
  (async () => {
    window.systemOrchestrator = new SystemOrchestrator();
    await window.systemOrchestrator.initialize();
  })();
}
