/**
 * Multi-Chart Algorithm
 * Handles multiple chart instances and synchronization
 */

class MultiChartAlgorithm {
    constructor() {
        this.charts = new Map();
        this.activeChart = null;
        this.syncEnabled = false;
        this.maxCharts = 4;
    }

    // Initialize multi-chart functionality
    init() {
        this.createChartContainer();
        this.setupEventListeners();
    }

    // Create chart container structure
    createChartContainer() {
        const chartArea = document.querySelector('.chart-area');
        if (!chartArea) return;

        // Add multi-chart controls
        const controls = document.createElement('div');
        controls.className = 'multi-chart-controls';
        controls.innerHTML = `
            <button class="chart-control-btn" id="addChart">+</button>
            <button class="chart-control-btn" id="syncCharts">Sync</button>
            <select class="chart-layout-select" id="layoutSelect">
                <option value="1">1 Chart</option>
                <option value="2">2 Charts</option>
                <option value="4">4 Charts</option>
            </select>
        `;
        
        chartArea.insertBefore(controls, chartArea.firstChild);
    }

    // Setup event listeners
    setupEventListeners() {
        const addBtn = document.getElementById('addChart');
        const syncBtn = document.getElementById('syncCharts');
        const layoutSelect = document.getElementById('layoutSelect');

        if (addBtn) {
            addBtn.addEventListener('click', () => this.addChart());
        }

        if (syncBtn) {
            syncBtn.addEventListener('click', () => this.toggleSync());
        }

        if (layoutSelect) {
            layoutSelect.addEventListener('change', (e) => {
                this.setLayout(parseInt(e.target.value));
            });
        }
    }

    // Add new chart
    addChart() {
        if (this.charts.size >= this.maxCharts) return;

        const chartId = `chart-${Date.now()}`;
        const chartContainer = this.createChartElement(chartId);
        
        this.charts.set(chartId, {
            container: chartContainer,
            data: null,
            timeframe: '1m',
            symbol: 'USD/BDT'
        });

        this.updateLayout();
    }

    // Create chart element
    createChartElement(chartId) {
        const container = document.createElement('div');
        container.className = 'chart-instance';
        container.id = chartId;
        container.innerHTML = `
            <div class="chart-header">
                <span class="chart-symbol">USD/BDT</span>
                <button class="chart-close" onclick="multiChart.removeChart('${chartId}')">×</button>
            </div>
            <div class="chart-canvas-container">
                <canvas class="chart-canvas"></canvas>
            </div>
        `;

        const chartArea = document.querySelector('.chart-area');
        chartArea.appendChild(container);
        
        return container;
    }

    // Remove chart
    removeChart(chartId) {
        const chart = this.charts.get(chartId);
        if (chart && chart.container) {
            chart.container.remove();
            this.charts.delete(chartId);
            this.updateLayout();
        }
    }

    // Set layout
    setLayout(count) {
        // Remove excess charts
        while (this.charts.size > count) {
            const firstChart = this.charts.keys().next().value;
            this.removeChart(firstChart);
        }

        // Add charts if needed
        while (this.charts.size < count) {
            this.addChart();
        }

        this.updateLayout();
    }

    // Update chart layout
    updateLayout() {
        const chartInstances = document.querySelectorAll('.chart-instance');
        const count = chartInstances.length;

        chartInstances.forEach((chart, index) => {
            chart.className = 'chart-instance';
            
            if (count === 1) {
                chart.classList.add('single');
            } else if (count === 2) {
                chart.classList.add('dual');
            } else if (count <= 4) {
                chart.classList.add('quad');
            }
        });
    }

    // Toggle synchronization
    toggleSync() {
        this.syncEnabled = !this.syncEnabled;
        const syncBtn = document.getElementById('syncCharts');
        
        if (syncBtn) {
            syncBtn.textContent = this.syncEnabled ? 'Unsync' : 'Sync';
            syncBtn.classList.toggle('active', this.syncEnabled);
        }
    }

    // Sync chart data across all instances
    syncChartData(sourceChartId, data) {
        if (!this.syncEnabled) return;

        this.charts.forEach((chart, chartId) => {
            if (chartId !== sourceChartId && chart.data) {
                this.updateChartData(chartId, data);
            }
        });
    }

    // Update chart data
    updateChartData(chartId, data) {
        const chart = this.charts.get(chartId);
        if (chart) {
            chart.data = data;
            // Trigger chart redraw
            this.redrawChart(chartId);
        }
    }

    // Redraw specific chart
    redrawChart(chartId) {
        const chart = this.charts.get(chartId);
        if (chart && chart.container) {
            const canvas = chart.container.querySelector('.chart-canvas');
            if (canvas) {
                // Trigger chart update event
                const event = new CustomEvent('chartUpdate', {
                    detail: { chartId, data: chart.data }
                });
                canvas.dispatchEvent(event);
            }
        }
    }

    // Get active chart
    getActiveChart() {
        return this.activeChart;
    }

    // Set active chart
    setActiveChart(chartId) {
        // Remove active class from all charts
        document.querySelectorAll('.chart-instance').forEach(chart => {
            chart.classList.remove('active');
        });

        // Set new active chart
        const chart = this.charts.get(chartId);
        if (chart) {
            chart.container.classList.add('active');
            this.activeChart = chartId;
        }
    }

    // Get chart count
    getChartCount() {
        return this.charts.size;
    }

    // Update symbol for specific chart
    updateChartSymbol(chartId, symbol) {
        const chart = this.charts.get(chartId);
        if (chart) {
            chart.symbol = symbol;
            const symbolElement = chart.container.querySelector('.chart-symbol');
            if (symbolElement) {
                symbolElement.textContent = symbol;
            }
        }
    }

    // Update timeframe for specific chart
    updateChartTimeframe(chartId, timeframe) {
        const chart = this.charts.get(chartId);
        if (chart) {
            chart.timeframe = timeframe;
        }
    }
}

// Initialize multi-chart algorithm
const multiChart = new MultiChartAlgorithm();

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

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