/**
 * Chart Persistence Manager
 * Ensures charts run continuously until manually stopped
 */

class ChartPersistenceManager {
    constructor() {
        this.STORAGE_KEYS = {
            CHART_STATE: 'tradingChart_fullState',
            ACTIVE_ASSET: 'tradingChart_activeAsset',
            DATASET_INFO: 'tradingChart_datasetInfo',
            MANUAL_STOP: 'tradingChart_manualStop'
        };
        
        this.isInitialized = false;
        this.autoResumeEnabled = true;
        
        this.init();
    }
    
    init() {
        // Check for existing state on page load
        document.addEventListener('DOMContentLoaded', () => {
            // Wait longer for all systems to initialize
            setTimeout(() => {
                this.waitForChartReady();
            }, 1000);
        });
        
        // Save state periodically
        setInterval(() => {
            this.saveCurrentState();
        }, 3000);
        
        // Listen for asset changes to clear old state
        this.lastSavedAsset = null;
        this.setupAssetChangeListener();
        
        // Handle page unload
        window.addEventListener('beforeunload', () => {
            this.saveCurrentState();
        });
        
        this.isInitialized = true;
    }
    
    saveCurrentState() {
        if (!this.autoResumeEnabled) return;
        
        // Get the active chart (either from multi-chart manager or global chart)
        let activeChart = null;
        const activeAssetName = document.querySelector('.asset-name')?.textContent;
        
        if (window.multiChartManager && window.multiChartManager.isInitialized && activeAssetName) {
            activeChart = window.multiChartManager.getChart(activeAssetName);
        } else if (window.chart) {
            activeChart = window.chart;
        }
        
        if (!activeChart) return;
        
        try {
            // Save complete chart state
            const chartState = {
                currentCandleIndex: activeChart.currentCandleIndex,
                currentCandleElapsed: activeChart.currentCandleElapsed,
                isPlaying: activeChart.isPlaying,
                currentTimeframe: activeChart.currentTimeframe,
                panOffset: activeChart.panOffset,
                timestamp: Date.now(),
                realStartTime: activeChart.realStartTime
            };
            
            // Get active asset card to save exact state
            const activeAssetCard = document.querySelector('.asset-card-tab:not([style*="display: none"])');
            const activeAsset = {
                name: document.querySelector('.asset-name')?.textContent || 'USD/BDT (OTC)',
                payout: document.querySelector('.asset-return')?.textContent || '80%',
                cardLabel: activeAssetCard?.querySelector('.asset-card-label')?.textContent,
                cardPayout: activeAssetCard?.querySelector('.asset-card-payout')?.textContent,
                timestamp: Date.now()
            };
            
            // Save dataset info with validation
            const datasetInfo = {
                hasData: activeChart.candleData && activeChart.candleData.length > 0,
                dataLength: activeChart.candleData?.length || 0,
                isValidDataset: activeChart.candleData && activeChart.candleData.length > 10, // Ensure real data
                timestamp: Date.now()
            };
            
            localStorage.setItem(this.STORAGE_KEYS.CHART_STATE, JSON.stringify(chartState));
            localStorage.setItem(this.STORAGE_KEYS.ACTIVE_ASSET, JSON.stringify(activeAsset));
            localStorage.setItem(this.STORAGE_KEYS.DATASET_INFO, JSON.stringify(datasetInfo));
            
    
            

            
        } catch (error) {
        }
    }
    
    restoreChartState() {
        try {

            
            // Clean up any duplicate asset cards first
            this.cleanupAssetCards();
            
            // Check if chart was manually stopped
            const manualStop = localStorage.getItem(this.STORAGE_KEYS.MANUAL_STOP);
            if (manualStop === 'true') {

                return false;
            }
            
            const chartState = JSON.parse(localStorage.getItem(this.STORAGE_KEYS.CHART_STATE) || '{}');
            const activeAsset = JSON.parse(localStorage.getItem(this.STORAGE_KEYS.ACTIVE_ASSET) || '{}');
            const datasetInfo = JSON.parse(localStorage.getItem(this.STORAGE_KEYS.DATASET_INFO) || '{}');
            
            // Check if we have valid state to restore
            if (!chartState.timestamp || !activeAsset.name) {

                return false;
            }
            
            // Check if state is not too old (max 1 hour)
            const stateAge = Date.now() - chartState.timestamp;
            if (stateAge > 3600000) { // 1 hour

                this.clearState();
                return false;
            }
            

            

            
            // Validate that we have a proper asset and dataset
            if (!activeAsset.name) {
                this.clearState();
                return false;
            }
            
            // Check if we have valid dataset info
            if (!datasetInfo.isValidDataset && datasetInfo.dataLength < 10) {
                this.clearState();
                return false;
            }
            
            // Restore asset selection
            this.restoreAssetSelection(activeAsset);
            
            // Wait for asset to load, then restore chart
            setTimeout(() => {
                this.restoreChartPlayback(chartState, datasetInfo);
            }, 2000); // Increased timeout for better reliability
            
            return true;
            
        } catch (error) {
            return false;
        }
    }
    
    restoreAssetSelection(activeAsset) {

        
        // First, ensure we have the correct asset card
        const targetAssetName = activeAsset.cardLabel || activeAsset.name;
        let matchingCard = null;
        
        // Find exact matching asset card
        const assetCards = document.querySelectorAll('.asset-card-tab');
        assetCards.forEach(card => {
            const cardLabel = card.querySelector('.asset-card-label');
            if (cardLabel && cardLabel.textContent === targetAssetName) {
                matchingCard = card;
            }
        });
        
        if (matchingCard) {
            
            // Hide all other cards first
            assetCards.forEach(card => {
                if (card !== matchingCard) {
                    card.style.display = 'none';
                }
            });
            
            // Show and activate the correct card
            matchingCard.style.display = 'block';
            
            // Update asset display immediately
            if (window.updateAssetDisplay) {
                window.updateAssetDisplay(activeAsset.name);
            }
            
            // Simulate click to load dataset
            setTimeout(() => {
                matchingCard.click();
            }, 300);
        } else {
            // Fallback: just update the display
            if (window.updateAssetDisplay) {
                window.updateAssetDisplay(activeAsset.name);
            }
        }
    }
    
    restoreChartPlayback(chartState, datasetInfo) {
        if (!window.chart) {
            return;
        }
        
        try {
            // Check if we have valid dataset
            if (!datasetInfo.isValidDataset || !window.chart.candleData || window.chart.candleData.length <= 10) {
                this.loadDefaultDataset();
                return;
            }
            
            // Calculate time elapsed since last save
            const timeSinceLastSave = Math.floor((Date.now() - chartState.timestamp) / 1000);
            const secondsPerCandle = window.chart.timeframeIntervals[chartState.currentTimeframe] || 60;
            
            // Calculate new position
            const totalElapsedSeconds = (chartState.currentCandleIndex * secondsPerCandle) + 
                                      chartState.currentCandleElapsed + timeSinceLastSave;
            
            const newCandleIndex = Math.floor(totalElapsedSeconds / secondsPerCandle);
            const newCandleElapsed = totalElapsedSeconds % secondsPerCandle;
            
            // Restore chart position
            window.chart.currentCandleIndex = Math.min(newCandleIndex, window.chart.candleData.length - 1);
            window.chart.currentCandleElapsed = Math.min(newCandleElapsed, secondsPerCandle - 1);
            
            // Restore timeframe if different
            if (chartState.currentTimeframe !== window.chart.currentTimeframe) {
                window.chart.setTimeframe(chartState.currentTimeframe);
            }
            
            // Restore pan offset
            if (chartState.panOffset !== undefined) {
                window.chart.panOffset = chartState.panOffset;
            }
            
            // Update chart state
            const currentCandle = window.chart.candleData[window.chart.currentCandleIndex];
            if (currentCandle && currentCandle.secondData && currentCandle.secondData[window.chart.currentCandleElapsed]) {
                window.chart.currentPrice = currentCandle.secondData[window.chart.currentCandleElapsed].price;
                window.chart.targetPrice = window.chart.currentPrice;
            }
            
            // Mark previous candles as complete
            window.chart.candleData.forEach((candle, index) => {
                candle.isComplete = index < window.chart.currentCandleIndex;
            });
            
            // Initialize running extremes
            if (window.chart._initRunningExtremes) {
                window.chart._initRunningExtremes();
            }
            
            // Update displays
            if (window.chart.updateDisplays) {
                window.chart.updateDisplays();
            }
            
            // Auto-resume playback if it was playing
            if (chartState.isPlaying && !window.chart.isPlaying) {
                setTimeout(() => {
                    window.chart.startAnimation();
                }, 1000);
            }
            

            
        } catch (error) {
        }
    }
    
    loadDefaultDataset() {
        // No fallback loading - show blank chart
        if (window.chart) {
            window.chart.candleData = [];
            window.chart.rawData = [];
            window.chart.currentCandleIndex = 0;
            window.chart.currentPrice = 0;
            window.chart.stopAnimation();
        }
        
        // Clear persistence state to prevent loops
        this.clearState();
    }
    
    markManualStop() {

        localStorage.setItem(this.STORAGE_KEYS.MANUAL_STOP, 'true');
    }
    
    clearManualStop() {

        localStorage.removeItem(this.STORAGE_KEYS.MANUAL_STOP);
    }
    
    clearState() {
        Object.values(this.STORAGE_KEYS).forEach(key => {
            localStorage.removeItem(key);
        });
    }
    
    cleanupAssetCards() {
        // Remove any duplicate or invalid asset cards
        const assetCards = document.querySelectorAll('.asset-card-tab');
        const seenAssets = new Set();
        
        assetCards.forEach(card => {
            const cardLabel = card.querySelector('.asset-card-label');
            if (!cardLabel) {
                // Remove cards without proper labels
                card.remove();
                return;
            }
            
            const assetName = cardLabel.textContent;
            if (seenAssets.has(assetName)) {
                // Remove duplicate cards
                card.remove();
            } else {
                seenAssets.add(assetName);
            }
        });
        

    }
    
    enableAutoResume() {
        this.autoResumeEnabled = true;
        this.clearManualStop();
    }
    
    disableAutoResume() {
        this.autoResumeEnabled = false;
        this.markManualStop();
    }
    
    // Public methods for manual control
    stopChart() {
        if (window.chart && window.chart.stopAnimation) {
            window.chart.stopAnimation();
        }
        this.markManualStop();
    }
    
    startChart() {
        if (window.chart && window.chart.startAnimation) {
            window.chart.startAnimation();
        }
        this.clearManualStop();
    }
    

    
    // Validate that the current state is consistent
    validateCurrentState() {
        const assetName = document.querySelector('.asset-name')?.textContent;
        const visibleCards = document.querySelectorAll('.asset-card-tab:not([style*="display: none"])');
        
        return {
            assetName,
            visibleCardCount: visibleCards.length,
            hasValidChart: window.chart && window.chart.candleData && window.chart.candleData.length > 10
        };
    }
    
    waitForChartReady() {
        let attempts = 0;
        const maxAttempts = 15; // 30 seconds max wait
        
        const checkReady = () => {
            attempts++;
            
            // Check if chart exists and has data
            const hasChart = window.chart && window.chart.candleData && window.chart.candleData.length > 0;
            // Check if multi-chart manager is ready
            const hasMultiChart = window.multiChartManager && window.multiChartManager.isInitialized;
            // Check if asset is loaded
            const hasAsset = document.querySelector('.asset-name')?.textContent;
            

            
            if ((hasChart || hasMultiChart) && hasAsset) {
                setTimeout(() => {
                    const state = this.validateCurrentState();
                    this.restoreChartState();
                }, 1000);
            } else if (attempts < maxAttempts) {
                setTimeout(checkReady, 2000);
            }
        };
        
        checkReady();
    }
    
    setupAssetChangeListener() {
        // Monitor for asset changes and coordinate with time display controller
        setInterval(() => {
            const currentAsset = document.querySelector('.asset-name')?.textContent;
            if (currentAsset && this.lastSavedAsset && currentAsset !== this.lastSavedAsset) {
                
                // Set transition state for time display controller
                if (window.timeDisplayController) {
                    window.timeDisplayController.setTransition(1500);
                }
                
                // Update time jump controller when asset changes
                if (window.timeJumpController && window.timeJumpController.updateTimeRange) {
                    setTimeout(() => {
                        window.timeJumpController.updateTimeRange();
                    }, 1500);
                }
                this.clearManualStop();
            }
            this.lastSavedAsset = currentAsset;
        }, 1000);
    }
}
// Initialize the persistence manager
window.chartPersistenceManager = new ChartPersistenceManager();

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ChartPersistenceManager;
}