// 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;
    }

    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();
        
        // 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'));
        }
    }
    
    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; 