// Cluster View Component
class ClusterViewComponent extends Component {
    constructor(container, viewModel, eventBus) {
        super(container, viewModel, eventBus);
        
        logger.debug('ClusterViewComponent: Constructor called');
        logger.debug('ClusterViewComponent: Container:', container);
        logger.debug('ClusterViewComponent: Container ID:', container?.id);
        
        // Find elements for sub-components
        const primaryNodeContainer = this.findElement('.primary-node-info');
        const clusterMembersContainer = this.findElement('#cluster-members-container');
        
        logger.debug('ClusterViewComponent: Primary node container:', primaryNodeContainer);
        logger.debug('ClusterViewComponent: Cluster members container:', clusterMembersContainer);
        logger.debug('ClusterViewComponent: Cluster members container ID:', clusterMembersContainer?.id);
        logger.debug('ClusterViewComponent: Cluster members container innerHTML:', clusterMembersContainer?.innerHTML);
        
        // Create sub-components
        this.primaryNodeComponent = new PrimaryNodeComponent(
            primaryNodeContainer,
            viewModel,
            eventBus
        );
        
        this.clusterMembersComponent = new ClusterMembersComponent(
            clusterMembersContainer,
            viewModel,
            eventBus
        );
        
        logger.debug('ClusterViewComponent: Sub-components created');
        
        // Track if we've already loaded data to prevent unnecessary reloads
        this.dataLoaded = false;
        
        // Initialize overlay dialog
        this.overlayDialog = null;
    }

    mount() {
        logger.debug('ClusterViewComponent: Mounting...');
        super.mount();
        
        logger.debug('ClusterViewComponent: Mounting sub-components...');
        // Mount sub-components
        this.primaryNodeComponent.mount();
        this.clusterMembersComponent.mount();
        
        // Set up refresh button event listener (since it's in the cluster header, not in the members container)
        this.setupRefreshButton();
        
        // Set up deploy button event listener
        this.setupDeployButton();
        
        // Set up config button event listener
        this.setupConfigButton();
        
        // Initialize overlay dialog
        this.initializeOverlayDialog();
        
        // Only load data if we haven't already or if the view model is empty
        const members = this.viewModel.get('members');
        const shouldLoadData = true; // always perform initial refresh quickly
        
        if (shouldLoadData) {
            logger.debug('ClusterViewComponent: Starting initial data load...');
            // Initial data load - ensure it happens after mounting
            // Trigger immediately to reduce perceived startup latency
            this.viewModel.updateClusterMembers().then(() => {
                this.dataLoaded = true;
            }).catch(error => {
                logger.error('ClusterViewComponent: Failed to load initial data:', error);
            });
        } else {
            logger.debug('ClusterViewComponent: Data already loaded, skipping initial load');
        }
        
        // Set up periodic updates
        // this.setupPeriodicUpdates(); // Disabled automatic refresh
        logger.debug('ClusterViewComponent: Mounted successfully');
    }
    
    setupRefreshButton() {
        logger.debug('ClusterViewComponent: Setting up refresh button...');
        
        const refreshBtn = this.findElement('.refresh-btn');
        logger.debug('ClusterViewComponent: Found refresh button:', !!refreshBtn, refreshBtn);
        
        if (refreshBtn) {
            logger.debug('ClusterViewComponent: Adding click event listener to refresh button');
            this.addEventListener(refreshBtn, 'click', this.handleRefresh.bind(this));
            logger.debug('ClusterViewComponent: Event listener added successfully');
        } else {
            logger.error('ClusterViewComponent: Refresh button not found!');
            logger.debug('ClusterViewComponent: Container HTML:', this.container.innerHTML);
            logger.debug('ClusterViewComponent: All buttons in container:', this.container.querySelectorAll('button'));
        }
    }
    
    setupDeployButton() {
        logger.debug('ClusterViewComponent: Setting up deploy button...');
        
        const deployBtn = this.findElement('#deploy-firmware-btn');
        logger.debug('ClusterViewComponent: Found deploy button:', !!deployBtn, deployBtn);
        
        if (deployBtn) {
            logger.debug('ClusterViewComponent: Adding click event listener to deploy button');
            this.addEventListener(deployBtn, 'click', this.handleDeploy.bind(this));
            logger.debug('ClusterViewComponent: Event listener added successfully');
        } else {
            logger.error('ClusterViewComponent: Deploy button not found!');
            logger.debug('ClusterViewComponent: Container HTML:', this.container.innerHTML);
            logger.debug('ClusterViewComponent: All buttons in container:', this.container.querySelectorAll('button'));
        }
    }
    
    setupConfigButton() {
        logger.debug('ClusterViewComponent: Setting up config button...');
        
        const configBtn = this.findElement('#config-wifi-btn');
        logger.debug('ClusterViewComponent: Found config button:', !!configBtn, configBtn);
        
        if (configBtn) {
            logger.debug('ClusterViewComponent: Adding click event listener to config button');
            this.addEventListener(configBtn, 'click', this.handleConfig.bind(this));
            logger.debug('ClusterViewComponent: Event listener added successfully');
        } else {
            logger.error('ClusterViewComponent: Config button not found!');
            logger.debug('ClusterViewComponent: Container HTML:', this.container.innerHTML);
            logger.debug('ClusterViewComponent: All buttons in container:', this.container.querySelectorAll('button'));
        }
    }
    
    initializeOverlayDialog() {
        // Create overlay container if it doesn't exist
        let overlayContainer = document.getElementById('cluster-overlay-dialog');
        if (!overlayContainer) {
            overlayContainer = document.createElement('div');
            overlayContainer.id = 'cluster-overlay-dialog';
            overlayContainer.className = 'overlay-dialog';
            document.body.appendChild(overlayContainer);
        }

        // Create and initialize the overlay dialog component
        if (!this.overlayDialog) {
            const overlayVM = new ViewModel();
            this.overlayDialog = new OverlayDialogComponent(overlayContainer, overlayVM, this.eventBus);
            this.overlayDialog.mount();
        }
    }

    showConfirmationDialog(options) {
        if (!this.overlayDialog) {
            this.initializeOverlayDialog();
        }
        
        this.overlayDialog.show(options);
    }
    
    async handleDeploy() {
        logger.debug('ClusterViewComponent: Deploy button clicked, opening firmware upload drawer...');
        
        // Get current filtered members from cluster members component
        const filteredMembers = this.clusterMembersComponent ? this.clusterMembersComponent.getFilteredMembers() : [];
        
        if (!filteredMembers || filteredMembers.length === 0) {
            this.showConfirmationDialog({
                title: 'No Nodes Available',
                message: 'No nodes available for firmware deployment. Please ensure cluster members are loaded and visible.',
                confirmText: 'OK',
                cancelText: null,
                onConfirm: () => {},
                onCancel: null
            });
            return;
        }
        
        // Open drawer with firmware upload interface
        this.openFirmwareUploadDrawer(filteredMembers);
    }
    
    async handleConfig() {
        logger.debug('ClusterViewComponent: Config button clicked, opening WiFi config drawer...');
        
        // Get current filtered members from cluster members component
        const filteredMembers = this.clusterMembersComponent ? this.clusterMembersComponent.getFilteredMembers() : [];
        
        if (!filteredMembers || filteredMembers.length === 0) {
            this.showConfirmationDialog({
                title: 'No Nodes Available',
                message: 'No nodes available for WiFi configuration. Please ensure cluster members are loaded and visible.',
                confirmText: 'OK',
                cancelText: null,
                onConfirm: () => {},
                onCancel: null
            });
            return;
        }
        
        // Open drawer with WiFi configuration interface
        this.openWiFiConfigDrawer(filteredMembers);
    }
    
    openFirmwareUploadDrawer(targetNodes) {
        logger.debug('ClusterViewComponent: Opening firmware upload drawer for', targetNodes.length, 'nodes');
        
        // Get display name for drawer title
        const nodeCount = targetNodes.length;
        const displayName = `Firmware Deployment - ${nodeCount} node${nodeCount !== 1 ? 's' : ''}`;
        
        // Open drawer with content callback (hide terminal button for firmware upload)
        this.clusterMembersComponent.drawer.openDrawer(displayName, (contentContainer, setActiveComponent) => {
            // Create firmware upload view model and component
            const firmwareUploadVM = new ClusterFirmwareViewModel();
            firmwareUploadVM.setTargetNodes(targetNodes);
            
            // Create HTML for firmware upload interface
            contentContainer.innerHTML = `
                <div class="firmware-upload-drawer">
                    <div class="firmware-upload-section">
                        <!--div class="firmware-upload-header">
                            <h3>
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16" style="margin-right:6px; vertical-align: -2px;">
                                    <path d="M4 7l8-4 8 4v10l-8 4-8-4z"/>
                                    <path d="M12 8v8"/>
                                </svg>
                                Firmware Upload
                            </h3>
                        </div-->
                        
                        <div class="firmware-upload-controls">
                            <div class="file-input-wrapper">
                                <div class="file-input-left">
                                    <input type="file" id="firmware-file" accept=".bin,.hex" style="display: none;">
                                    <button class="upload-btn-compact" onclick="document.getElementById('firmware-file').click()">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14" style="margin-right:6px; vertical-align: -2px;">
                                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                            <path d="M14 2v6h6"/>
                                        </svg>
                                        Choose File
                                    </button>
                                    <span class="file-info" id="file-info">No file selected</span>
                                </div>
                                <button class="deploy-btn-compact" id="deploy-btn" disabled>
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14" style="margin-right:6px; vertical-align: -2px;">
                                        <path d="M12 16V4"/>
                                        <path d="M8 8l4-4 4 4"/>
                                        <path d="M20 16v2a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-2"/>
                                    </svg>
                                    Deploy
                                </button>
                            </div>
                        </div>
                        
                        <div class="target-nodes-section">
                            <h3>
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16" style="margin-right:6px; vertical-align: -2px;">
                                    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                                    <circle cx="9" cy="7" r="4"/>
                                    <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
                                    <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
                                </svg>
                                Target Nodes (${targetNodes.length})
                            </h3>
                            <div class="target-nodes-list">
                                ${targetNodes.map(node => `
                                    <div class="target-node-item" data-node-ip="${node.ip}">
                                        <div class="node-info">
                                            <span class="node-name">${node.hostname || node.ip}</span>
                                            <span class="node-ip">${node.ip}</span>
                                        </div>
                                        <div class="node-status">
                                            <span class="status-indicator ready">Ready</span>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                        
                        
                        <div id="firmware-progress-container">
                            <!-- Progress will be shown here during upload -->
                        </div>
                    </div>
                </div>
            `;
            
            // Create and mount firmware upload component
            const firmwareUploadComponent = new FirmwareUploadComponent(contentContainer, firmwareUploadVM, this.eventBus);
            setActiveComponent(firmwareUploadComponent);
            firmwareUploadComponent.mount();
            
        }, null, () => {
            // Close callback - clear any upload state
            logger.debug('ClusterViewComponent: Firmware upload drawer closed');
        }, true); // Hide terminal button for firmware upload
    }
    
    openWiFiConfigDrawer(targetNodes) {
        logger.debug('ClusterViewComponent: Opening WiFi config drawer for', targetNodes.length, 'nodes');
        
        // Get display name for drawer title
        const nodeCount = targetNodes.length;
        const displayName = `Configuration - ${nodeCount} node${nodeCount !== 1 ? 's' : ''}`;
        
        // Open drawer with content callback (hide terminal button for WiFi config)
        this.clusterMembersComponent.drawer.openDrawer(displayName, (contentContainer, setActiveComponent) => {
            // Create WiFi config view model and component
            const wifiConfigVM = new WiFiConfigViewModel();
            wifiConfigVM.setTargetNodes(targetNodes);
            
            // Create HTML for WiFi configuration interface
            contentContainer.innerHTML = `
                <div class="wifi-config-drawer">
                    <div class="tabs-container">
                        <div class="tabs-header">
                            <button class="tab-button active" data-tab="wifi">WiFi</button>
                        </div>
                        
                        <div class="tab-content active" id="wifi-tab">
                            <div class="wifi-config-section">
                                <div class="wifi-form">
                                    <div class="form-group">
                                        <label for="wifi-ssid">SSID (Network Name)</label>
                                        <input type="text" id="wifi-ssid" placeholder="Enter WiFi network name" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="wifi-password">Password</label>
                                        <input type="password" id="wifi-password" placeholder="Enter WiFi password" required>
                                    </div>
                                    
                                    <div class="wifi-divider"></div>
                                    
                                    <div class="affected-nodes-info">
                                        <div class="nodes-count">
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16" style="margin-right:6px; vertical-align: -2px;">
                                                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                                                <circle cx="9" cy="7" r="4"/>
                                                <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
                                                <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
                                            </svg>
                                            Affected Nodes: <span id="affected-nodes-count">${targetNodes.length}</span>
                                        </div>
                                    </div>
                                    
                                    <div class="wifi-actions">
                                        <button class="config-btn" id="apply-wifi-config" disabled>
                                            Apply
                                        </button>
                                    </div>
                                </div>
                                
                                <div id="wifi-progress-container">
                                    <!-- Progress will be shown here during configuration -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Create and mount WiFi config component
            const wifiConfigComponent = new WiFiConfigComponent(contentContainer, wifiConfigVM, this.eventBus);
            setActiveComponent(wifiConfigComponent);
            wifiConfigComponent.mount();
            
        }, null, () => {
            // Close callback - clear any config state
            logger.debug('ClusterViewComponent: WiFi config drawer closed');
        }, true); // Hide terminal button for WiFi config
    }
    
    async handleRefresh() {
        logger.debug('ClusterViewComponent: Refresh button clicked, performing full refresh...');
        
        // Get the refresh button and show loading state
        const refreshBtn = this.findElement('.refresh-btn');
        logger.debug('ClusterViewComponent: Found refresh button for loading state:', !!refreshBtn);
        
        if (refreshBtn) {
            const originalText = refreshBtn.innerHTML;
            logger.debug('ClusterViewComponent: Original button text:', originalText);
            
            refreshBtn.innerHTML = `
                <svg class="refresh-icon spinning" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M1 4v6h6M23 20v-6h-6"/>
                    <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
                </svg>
                Refreshing...
            `;
            refreshBtn.disabled = true;
            
            try {
                logger.debug('ClusterViewComponent: Starting cluster members update...');
                // Always perform a full refresh when user clicks refresh button
                await this.viewModel.updateClusterMembers();
                logger.debug('ClusterViewComponent: Cluster members update completed successfully');
            } catch (error) {
                logger.error('ClusterViewComponent: Error during refresh:', error);
                // Show error state
                if (this.clusterMembersComponent && this.clusterMembersComponent.showErrorState) {
                    this.clusterMembersComponent.showErrorState(error.message || 'Refresh failed');
                }
            } finally {
                logger.debug('ClusterViewComponent: Restoring button state...');
                // Restore button state
                refreshBtn.innerHTML = originalText;
                refreshBtn.disabled = false;
            }
        } else {
            logger.warn('ClusterViewComponent: Refresh button not found, using fallback refresh');
            // Fallback if button not found
            try {
                await this.viewModel.updateClusterMembers();
            } catch (error) {
                logger.error('ClusterViewComponent: Fallback refresh failed:', error);
                if (this.clusterMembersComponent && this.clusterMembersComponent.showErrorState) {
                    this.clusterMembersComponent.showErrorState(error.message || 'Refresh failed');
                }
            }
        }
    }

    unmount() {
        logger.debug('ClusterViewComponent: Unmounting...');
        
        // Unmount sub-components
        if (this.primaryNodeComponent) {
            this.primaryNodeComponent.unmount();
        }
        if (this.clusterMembersComponent) {
            this.clusterMembersComponent.unmount();
        }
        
        // Clear intervals
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
        
        super.unmount();
        logger.debug('ClusterViewComponent: Unmounted');
    }

    // Override pause method to handle sub-components
    onPause() {
        logger.debug('ClusterViewComponent: Pausing...');
        
        // Pause sub-components
        if (this.primaryNodeComponent && this.primaryNodeComponent.isMounted) {
            this.primaryNodeComponent.pause();
        }
        if (this.clusterMembersComponent && this.clusterMembersComponent.isMounted) {
            this.clusterMembersComponent.pause();
        }
        
        // Clear any active intervals
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
            this.updateInterval = null;
        }
    }

    // Override resume method to handle sub-components
    onResume() {
        logger.debug('ClusterViewComponent: Resuming...');
        
        // Resume sub-components
        if (this.primaryNodeComponent && this.primaryNodeComponent.isMounted) {
            this.primaryNodeComponent.resume();
        }
        if (this.clusterMembersComponent && this.clusterMembersComponent.isMounted) {
            this.clusterMembersComponent.resume();
        }
        
        // Restart periodic updates if needed
        // this.setupPeriodicUpdates(); // Disabled automatic refresh
    }

    // Override to determine if re-render is needed on resume
    shouldRenderOnResume() {
        // Don't re-render on resume - the component should maintain its state
        return false;
    }

    setupPeriodicUpdates() {
        // Update primary node display every 10 seconds
        this.updateInterval = setInterval(() => {
            this.viewModel.updatePrimaryNodeDisplay();
        }, 10000);
    }
}

window.ClusterViewComponent = ClusterViewComponent; 