/**
 * Centralized Time Display Controller
 * Eliminates time blinking by managing all time updates from a single source
 */

class TimeDisplayController {
    constructor() {
        this.isTransitioning = false;
        this.transitionTimeout = null;
        this.activeChart = null;
        this.lastValidTime = null;
        this.lastValidServerTime = null;
        this.updateInterval = null;
        
        this.init();
    }
    
    init() {
        // Start coordinated time updates
        this.startTimeUpdates();
        
        // Listen for asset transitions
        this.setupTransitionListeners();
    }
    
    /**
     * Set transition state to prevent conflicting updates
     */
    setTransition(duration = 2000) {
        this.isTransitioning = true;
        clearTimeout(this.transitionTimeout);
        
        this.transitionTimeout = setTimeout(() => {
            this.isTransitioning = false;

        }, duration);
        

    }
    
    /**
     * Get stable chart reference with validation
     */
    getStableChart() {
        // Priority: Multi-chart active > Global chart > Cached reference
        let chart = null;
        
        if (window.multiChartManager?.activeAsset) {
            chart = window.multiChartManager.getChart(window.multiChartManager.activeAsset);
        }
        
        if (!chart || !chart.candleData?.length) {
            chart = window.chart;
        }
        
        // Validate chart has required data
        if (chart?.candleData?.length && chart.currentCandleIndex !== undefined) {
            this.activeChart = chart;
            return chart;
        }
        
        // Return cached reference if current is invalid
        return this.activeChart;
    }
    
    /**
     * Master time update function - single source of truth
     */
    updateAllTimeDisplays() {
        // Skip updates during transitions
        if (this.isTransitioning) return;
        
        const chart = this.getStableChart();
        if (!chart?.candleData?.length) return;
        
        const candle = chart.candleData[chart.currentCandleIndex];
        if (!candle) return;
        
        try {
            // Update right sidebar time
            this.updateSidebarTime(chart, candle);
            
            // Update server time
            this.updateServerTime(chart, candle);
            
        } catch (error) {
            // Use last valid times on error
            this.useLastValidTimes();
        }
    }
    
    /**
     * Update sidebar time display
     */
    updateSidebarTime(chart, candle) {
        const timeValue = document.querySelector('.time-value');
        if (!timeValue) return;
        
        let displayTime;
        
        if (!window.isManualTimeSet) {
            const remainingSeconds = 60 - chart.currentCandleElapsed;
            
            if (chart.currentCandleElapsed >= 30) {
                displayTime = new Date(candle.timestamp + chart.currentCandleElapsed * 1000 + (remainingSeconds + 60) * 1000);
            } else {
                displayTime = new Date(candle.timestamp + 60000);
            }
        } else {
            const remainingSeconds = 60 - chart.currentCandleElapsed;
            const totalOffset = remainingSeconds + (window.manualTimeOffset * 60);
            displayTime = new Date(candle.timestamp + chart.currentCandleElapsed * 1000 + totalOffset * 1000);
        }
        
        const timeString = displayTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
        
        // Only update if different to prevent unnecessary DOM changes
        if (timeValue.textContent !== timeString) {
            timeValue.textContent = timeString;
            this.lastValidTime = timeString;
        }
    }
    
    /**
     * Update server time display
     */
    updateServerTime(chart, candle) {
        const serverTimeElement = document.querySelector('.server-time.online');
        if (!serverTimeElement) return;
        
        const currentServerTime = new Date(candle.timestamp + chart.currentCandleElapsed * 1000);
        const serverTimeString = currentServerTime.toLocaleTimeString([], { 
            hour: '2-digit', 
            minute: '2-digit', 
            second: '2-digit', 
            hour12: false 
        });
        
        // Only update if different
        const currentText = serverTimeElement.childNodes[0]?.textContent?.trim();
        if (currentText !== serverTimeString) {
            const timeText = serverTimeElement.childNodes[0];
            if (timeText && timeText.nodeType === Node.TEXT_NODE) {
                timeText.textContent = serverTimeString + ' ';
            } else {
                const span = serverTimeElement.querySelector('span');
                const spanContent = span ? span.outerHTML : '<span>UTC+6</span>';
                serverTimeElement.innerHTML = serverTimeString + ' ' + spanContent;
            }
            this.lastValidServerTime = serverTimeString;
        }
    }
    
    /**
     * Use last valid times when current update fails
     */
    useLastValidTimes() {
        if (this.lastValidTime) {
            const timeValue = document.querySelector('.time-value');
            if (timeValue) timeValue.textContent = this.lastValidTime;
        }
        
        if (this.lastValidServerTime) {
            const serverTimeElement = document.querySelector('.server-time.online');
            if (serverTimeElement) {
                const span = serverTimeElement.querySelector('span');
                const spanContent = span ? span.outerHTML : '<span>UTC+6</span>';
                serverTimeElement.innerHTML = this.lastValidServerTime + ' ' + spanContent;
            }
        }
    }
    
    /**
     * Start coordinated time updates
     */
    startTimeUpdates() {
        // Clear any existing interval
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
        
        // Start master update loop
        this.updateInterval = setInterval(() => {
            this.updateAllTimeDisplays();
        }, 100);
    }
    
    /**
     * Setup listeners for asset transitions
     */
    setupTransitionListeners() {
        // Listen for asset card clicks
        document.addEventListener('click', (e) => {
            const assetCard = e.target.closest('.asset-card-tab');
            if (assetCard) {
                this.setTransition(2000);
            }
        });
        
        // Listen for multi-chart asset switches
        if (window.multiChartManager) {
            const originalSwitchToAsset = window.multiChartManager.switchToAsset;
            window.multiChartManager.switchToAsset = (assetName) => {
                this.setTransition(1500);
                return originalSwitchToAsset.call(window.multiChartManager, assetName);
            };
        }
    }
    
    /**
     * Stop all time updates
     */
    stop() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
            this.updateInterval = null;
        }
        
        if (this.transitionTimeout) {
            clearTimeout(this.transitionTimeout);
            this.transitionTimeout = null;
        }
    }
}

// Initialize global time display controller when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    // Wait for other systems to initialize first
    setTimeout(() => {
        if (!window.timeDisplayController) {
            window.timeDisplayController = new TimeDisplayController();

        }
    }, 500);
});

// Fallback initialization if DOM is already loaded
if (document.readyState === 'loading') {
    // DOM is still loading, event listener will handle it
} else {
    // DOM is already loaded
    setTimeout(() => {
        if (!window.timeDisplayController) {
            window.timeDisplayController = new TimeDisplayController();

        }
    }, 500);
}

// Export for module systems
if (typeof module !== 'undefined' && module.exports) {
    module.exports = TimeDisplayController;
}