/**
 * Multi-Chart Manager
 * Manages multiple chart instances running in background with single display
 */

class MultiChartManager {
    constructor() {
        this.charts = new Map(); // assetName -> chartInstance
        this.activeAsset = null;
        this.chartContainer = null;
        this.canvasPool = new Map(); // assetName -> canvas
        this.isInitialized = false;
    }

    init() {
        this.chartContainer = document.getElementById('chartContainer');
        if (!this.chartContainer) {
            return;
        }

        this.setupAssetListeners();
        this.isInitialized = true;

    }

    // Create chart instance for specific asset
    createChartForAsset(assetName, candleData, sentimentData) {
        if (this.charts.has(assetName)) {

            return this.charts.get(assetName);
        }

        // Validate data before creating chart
        if (!this.validateAssetData(candleData)) {
            return null;
        }

        // Create dedicated canvas for this asset
        const canvas = this.createCanvas(assetName);

        // Create chart instance
        const chart = new SmoothTradingChart(canvas.id);
        chart.assetName = assetName;
        chart.isBackground = true;

        // Set asset-specific configuration
        if (typeof getAssetConfig === 'function') {
            const assetConfig = getAssetConfig(assetName);
            if (assetConfig) {

                // Apply the configuration immediately
                chart.updateAssetIntervals();
            }
        }

        // Ensure visibility handler is set up for background charts
        if (!chart.visibilityHandlerSetup) {
            chart.setupVisibilityHandler();
            chart.visibilityHandlerSetup = true;
        }

        // Load data and start
        const dataLoaded = chart.loadDataset(candleData, sentimentData);
        if (!dataLoaded) {
            canvas.remove();
            return null;
        }

        // Ensure asset intervals are applied after data loading
        chart.updateAssetIntervals();

        this.charts.set(assetName, chart);
        this.canvasPool.set(assetName, canvas);


        return chart;
    }

    // Create canvas element for asset
    createCanvas(assetName) {
        const canvas = document.createElement('canvas');
        canvas.id = `chartCanvas_${assetName.replace(/[^a-zA-Z0-9]/g, '_')}`;
        canvas.style.position = 'absolute';
        canvas.style.top = '0';
        canvas.style.left = '0';
        canvas.style.width = '100%';
        canvas.style.height = '100%';
        canvas.style.display = 'none'; // Hidden by default

        this.chartContainer.appendChild(canvas);
        return canvas;
    }

    // Switch to display specific asset chart
    switchToAsset(assetName) {


        if (!this.charts.has(assetName)) {
            return false;
        }

        // Set transition state for time display controller
        if (window.timeDisplayController) {
            window.timeDisplayController.setTransition(1500);
        }

        // Hide current active chart
        if (this.activeAsset && this.canvasPool.has(this.activeAsset)) {
            const currentCanvas = this.canvasPool.get(this.activeAsset);
            currentCanvas.style.display = 'none';

            const currentChart = this.charts.get(this.activeAsset);
            if (currentChart) {
                currentChart.isBackground = true;
            }
        }

        // Show new active chart
        const newCanvas = this.canvasPool.get(assetName);
        const newChart = this.charts.get(assetName);

        newCanvas.style.display = 'block';
        newChart.isBackground = false;

        // Update global chart reference
        window.chart = newChart;

        // Ensure global chart has dataset path for Time Jump Controller
        if (newChart && newChart.currentDatasetPath) {
            window.chart.currentDatasetPath = newChart.currentDatasetPath;
        }

        // Ensure visibility handler is active for the new active chart
        if (!newChart.visibilityHandlerSetup) {
            newChart.setupVisibilityHandler();
            newChart.visibilityHandlerSetup = true;
        }

        // Update asset display in UI
        this.updateAssetDisplay(assetName);

        // Resize canvas to fit container
        newChart.setupCanvas();

        this.activeAsset = assetName;

        // Notify time jump controller about asset change
        setTimeout(() => {

            if (window.timeJumpController) {
                window.timeJumpController.updateTimeRange();
            }
        }, 1000);

        return true;
    }

    // Start chart for asset (background processing)
    startChart(assetName) {
        const chart = this.charts.get(assetName);
        if (chart && !chart.isPlaying) {
            chart.startAnimation();
        }
    }

    // Stop chart for asset
    stopChart(assetName) {
        const chart = this.charts.get(assetName);
        if (chart && chart.isPlaying) {
            chart.stopAnimation();
        }
    }

    // Reset chart with user-specific data reload
    async resetChart(assetName) {
        const chart = this.charts.get(assetName);
        if (!chart) {
            return false;
        }

        // Always use auto-detection to ensure user-specific paths
        let datasetPath = await this.autoDetectDatasetPath(assetName);

        if (datasetPath) {
            try {
                const response = await fetch(datasetPath);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                const candleData = await response.json();


                const loadResult = chart.loadDataset(candleData, []);
                if (loadResult === false) {
                    throw new Error('Chart loadDataset returned false');
                }

                chart.restart();
                return true;
            } catch (error) {

                alert(`Failed to reset chart: ${error.message}`);
            }
        } else {
            console.error('No dataset path found for asset:', assetName);
            alert('No dataset found for this asset');
        }

        // Fallback to restart without data reload
        chart.restart();
        return false;
    }

    // Build all candles with user-specific data reload
    async buildAllChart(assetName) {
        const chart = this.charts.get(assetName);
        if (!chart) {
            return false;
        }

        // Always use auto-detection to ensure user-specific paths
        let datasetPath = await this.autoDetectDatasetPath(assetName);

        if (datasetPath) {
            try {
                const response = await fetch(datasetPath);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                const candleData = await response.json();


                const loadResult = chart.loadDataset(candleData, []);
                if (loadResult === false) {
                    throw new Error('Chart loadDataset returned false');
                }

                chart.buildAllCandles();
                return true;
            } catch (error) {

                alert(`Failed to build all candles: ${error.message}`);
            }
        } else {
            console.error('No dataset path found for asset:', assetName);
            alert('No dataset found for this asset');
        }

        // Fallback to build all without data reload
        chart.buildAllCandles();
        return false;
    }

    // Get chart instance for asset
    getChart(assetName) {
        return this.charts.get(assetName);
    }

    // Check if chart exists for asset
    hasChart(assetName) {
        return this.charts.has(assetName);
    }

    // Get all running charts
    getRunningCharts() {
        const running = [];
        this.charts.forEach((chart, assetName) => {
            if (chart.isPlaying) {
                running.push(assetName);
            }
        });
        return running;
    }

    // Setup asset card click listeners
    setupAssetListeners() {
        document.addEventListener('click', (e) => {
            const assetCard = e.target.closest('.asset-card-tab');
            if (assetCard) {
                const assetName = assetCard.querySelector('.asset-card-label')?.textContent;
                if (assetName) {
                    this.handleAssetSelection(assetName);
                }
            }
        });
    }

    // Handle asset selection
    async handleAssetSelection(assetName) {
        // Freeze all charts during asset switching
        this.freezeAllCharts();

        // Check if chart already exists
        if (this.hasChart(assetName)) {
            this.switchToAsset(assetName);
            this.unfreezeAllCharts();
            return;
        }

        // Load data and create chart using dynamic detection
        try {
            // Try to auto-detect the dataset path for the asset
            const datasetPath = await this.autoDetectDatasetPath(assetName);
            if (!datasetPath) {

                return;
            }


            const response = await fetch(datasetPath);
            const candleData = await response.json();

            // Create and start chart
            const chart = this.createChartForAsset(assetName, candleData, []);

            // Store dataset path in chart instance for Time Jump Controller
            if (chart) {
                chart.currentDatasetPath = datasetPath;


                // Use global storage function
                if (window.storeChartDatasetPath) {
                    window.storeChartDatasetPath(datasetPath, assetName);
                }
            }

            this.switchToAsset(assetName);

            // Auto-start if not manually stopped
            setTimeout(() => {
                if (!chart.isPlaying) {
                    this.startChart(assetName);
                }

                // Notify time jump controller after chart is ready
                if (window.timeJumpController) {
                    window.timeJumpController.updateTimeRange();
                }

                // Unfreeze all charts after loading is complete
                this.unfreezeAllCharts();
            }, 2000);

        } catch (error) {

        }
    }

    // Validate asset data
    validateAssetData(candleData) {
        return candleData && candleData.length > 0 &&
            candleData.every(item => item.time && item.price && !isNaN(parseFloat(item.price)));
    }

    // Get dataset path for asset with user-specific detection
    async getDatasetPath(assetName) {
        const chart = this.charts.get(assetName);
        if (chart && chart.currentDatasetPath) {
            return chart.currentDatasetPath;
        }
        return await this.autoDetectDatasetPath(assetName);
    }

    // Auto-detect dataset path for asset with user-specific paths
    async autoDetectDatasetPath(assetName) {
        if (!assetName) return null;

        // Convert asset name to folder format
        let folderName = assetName.toLowerCase().replace(/[^a-z]/g, '');
        if (!folderName.endsWith('otc')) {
            folderName += 'otc';
        }



        try {
            // Get current user's session info first
            const sessionResponse = await fetch('./php/session_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'getCurrentUser' })
            });

            let username = 'unrealengine_developer'; // fallback
            try {
                const sessionData = await sessionResponse.json();
                if (sessionData.username) {
                    username = sessionData.username;

                } else {

                }
            } catch (e) {

            }

            // Use PHP endpoint which handles user-specific data paths
            const response = await fetch(`./php/list_datasets.php?asset=${encodeURIComponent(folderName)}`);
            const datasets = await response.json();



            if (datasets && datasets.length > 0) {
                // Use the first dataset (newest due to sorting)
                const latestDataset = datasets[0];

                // Build user-specific path
                const path = `./data/${username}/${folderName}/${latestDataset}/candle_data.json`;


                // Verify the file exists by making a HEAD request
                try {
                    const verifyResponse = await fetch(path, { method: 'HEAD' });
                    if (verifyResponse.ok) {
                        console.log(`✅ Verified path exists: ${path}`);
                        return path;
                    } else {
                        console.error(`❌ Path verification failed (${verifyResponse.status}): ${path}`);
                    }
                } catch (verifyError) {

                }
            } else {

            }
        } catch (error) {

        }

        console.log(`❌ Failed to detect dataset path for: ${assetName}`);
        return null;
    }

    // Time jump functionality with user-specific paths
    async jumpToTime(timeStr) {
        const activeAsset = this.activeAsset;
        if (!activeAsset || !this.charts.has(activeAsset)) {
            return false;
        }

        const chart = this.charts.get(activeAsset);

        // Use stored dataset path or auto-detect user-specific path
        let datasetPath = chart.currentDatasetPath;
        if (!datasetPath) {
            datasetPath = await this.autoDetectDatasetPath(activeAsset);
        }

        if (!datasetPath) {
            return false;
        }

        try {
            const response = await fetch(datasetPath);
            const fullData = await response.json();

            // Find target timestamp
            const targetTime = this.parseTimeToTimestamp(timeStr, fullData[0].time);
            const filteredData = fullData.filter(item => item.time >= targetTime);

            if (filteredData.length === 0) {
                return false;
            }

            // Reload chart with filtered data
            chart.loadDataset(filteredData, []);
            return true;

        } catch (error) {
            return false;
        }
    }

    parseTimeToTimestamp(timeStr, baseTimestamp) {
        const [hours, minutes] = timeStr.split(':').map(Number);
        const targetMinutes = hours * 60 + minutes;
        const result = baseTimestamp + (targetMinutes * 60);

        return result;
    }

    getActiveAssetTimeRange() {




        const activeAsset = this.activeAsset;
        if (!activeAsset || !this.charts.has(activeAsset)) {

            return null;
        }

        const chart = this.charts.get(activeAsset);


        if (!chart.candleData || chart.candleData.length === 0) {

            return null;
        }

        const firstCandle = chart.candleData[0];
        const lastCandle = chart.candleData[chart.candleData.length - 1];




        const timeRange = {
            start: new Date(firstCandle.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }),
            end: new Date(lastCandle.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
        };


        return timeRange;
    }

    // Save state of all charts
    saveState() {
        const state = {
            activeAsset: this.activeAsset,
            charts: {},
            timestamp: Date.now()
        };

        this.charts.forEach((chart, assetName) => {
            state.charts[assetName] = {
                currentCandleIndex: chart.currentCandleIndex,
                currentCandleElapsed: chart.currentCandleElapsed,
                isPlaying: chart.isPlaying,
                currentTimeframe: chart.currentTimeframe,
                panOffset: chart.panOffset,
                realStartTime: chart.realStartTime
            };
        });

        localStorage.setItem('multiChart_state', JSON.stringify(state));
    }

    // Restore state of all charts
    async restoreState() {
        try {
            const saved = localStorage.getItem('multiChart_state');
            if (!saved) return false;

            const state = JSON.parse(saved);
            const stateAge = Date.now() - state.timestamp;

            // Don't restore if too old (1 hour) OR if no valid datasets exist
            if (stateAge > 3600000) {
                localStorage.removeItem('multiChart_state');
                return false;
            }

            // Validate that datasets still exist before restoring
            let hasValidDatasets = false;
            for (const assetName of Object.keys(state.charts)) {
                const datasetPath = await this.autoDetectDatasetPath(assetName);
                if (datasetPath) {
                    hasValidDatasets = true;
                    break;
                }
            }

            if (!hasValidDatasets) {
                localStorage.removeItem('multiChart_state');
                return false;
            }

            // Restore charts
            for (const [assetName, chartState] of Object.entries(state.charts)) {
                const datasetPath = await this.getDatasetPath(assetName);
                if (!datasetPath) continue;

                try {
                    const response = await fetch(datasetPath);
                    const candleData = await response.json();

                    const chart = this.createChartForAsset(assetName, candleData, []);

                    // Store dataset path in chart instance
                    if (chart) {
                        chart.currentDatasetPath = datasetPath;
                    }

                    // Restore chart state
                    const timeSinceLastSave = Math.floor((Date.now() - state.timestamp) / 1000);
                    const secondsPerCandle = chart.timeframeIntervals[chartState.currentTimeframe] || 60;
                    const totalElapsed = (chartState.currentCandleIndex * secondsPerCandle) +
                        chartState.currentCandleElapsed + timeSinceLastSave;

                    chart.currentCandleIndex = Math.min(Math.floor(totalElapsed / secondsPerCandle), chart.candleData.length - 1);
                    chart.currentCandleElapsed = totalElapsed % secondsPerCandle;
                    chart.panOffset = chartState.panOffset || 0;

                    // Update chart position
                    const currentCandle = chart.candleData[chart.currentCandleIndex];
                    if (currentCandle && currentCandle.secondData && currentCandle.secondData[chart.currentCandleElapsed]) {
                        chart.currentPrice = currentCandle.secondData[chart.currentCandleElapsed].price;
                        chart.targetPrice = chart.currentPrice;
                    }

                    // Mark previous candles complete
                    chart.candleData.forEach((candle, index) => {
                        candle.isComplete = index < chart.currentCandleIndex;
                    });

                    if (chart._initRunningExtremes) chart._initRunningExtremes();
                    if (chart.updateDisplays) chart.updateDisplays();

                    // Auto-resume if was playing
                    if (chartState.isPlaying) {
                        setTimeout(() => chart.startAnimation(), 500);
                    }

                } catch (error) {

                }
            }

            // Switch to active asset
            if (state.activeAsset && this.hasChart(state.activeAsset)) {
                setTimeout(() => this.switchToAsset(state.activeAsset), 1000);
            }


            return true;

        } catch (error) {

            return false;
        }
    }

    // Update asset display in UI (controlled by Multi-Chart Manager)
    updateAssetDisplay(assetName) {
        // Update asset name in sidebar
        const assetNameElement = document.querySelector('.asset-name');
        if (assetNameElement) {
            assetNameElement.textContent = assetName;

            // Check if asset name wraps to multiple lines
            const assetHeader = document.querySelector('.asset-header');
            if (assetHeader) {
                // Wait for text to render
                setTimeout(() => {
                    const lineHeight = parseInt(window.getComputedStyle(assetNameElement).lineHeight);
                    const actualHeight = assetNameElement.offsetHeight;

                    // If height is greater than one line, add multiline class
                    if (actualHeight > lineHeight * 1.2) {
                        assetHeader.classList.add('multiline');
                    } else {
                        assetHeader.classList.remove('multiline');
                    }
                }, 10);
            }
        }

        // Update flags in sidebar
        const flagContainer = document.querySelector('.asset-header .flag-container');
        if (flagContainer && window.generateTradeFlags) {
            const flagsHtml = window.generateTradeFlags(assetName).replace(/trade-history-flag/g, '');
            flagContainer.innerHTML = flagsHtml;
        }

        // Update active asset card with caret icon
        if (window.updateActiveAssetCard) {
            window.updateActiveAssetCard(assetName);
        }

        // Ensure caret icons are added to all asset cards
        if (window.addCaretIconToAssetCards) {
            setTimeout(() => window.addCaretIconToAssetCards(), 100);
        }


    }

    // Freeze all charts
    freezeAllCharts() {
        this.charts.forEach((chart) => {
            if (chart.freezeChart) chart.freezeChart();
        });
    }

    // Unfreeze all charts
    unfreezeAllCharts() {
        this.charts.forEach((chart) => {
            if (chart.unfreezeChart) chart.unfreezeChart();
        });
    }

    // Cleanup
    destroy() {
        this.charts.forEach((chart, assetName) => {
            if (chart.stopAnimation) chart.stopAnimation();
        });

        this.canvasPool.forEach((canvas) => {
            if (canvas.parentNode) canvas.remove();
        });

        this.charts.clear();
        this.canvasPool.clear();
    }
}

// Initialize multi-chart manager
window.multiChartManager = new MultiChartManager();

// Auto-initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        window.multiChartManager.init();

        // Restore state after initialization
        setTimeout(() => {
            window.multiChartManager.restoreState();
        }, 2000);
    }, 1000);
});

// Save state periodically
setInterval(() => {
    if (window.multiChartManager && window.multiChartManager.isInitialized) {
        window.multiChartManager.saveState();
    }
}, 5000);

// Save state on page unload
window.addEventListener('beforeunload', () => {
    if (window.multiChartManager) {
        window.multiChartManager.saveState();
    }
});