// chart-sorting.js - Chart sorting functionality

let currentSortMode = 'popular'; // Default: 'popular', 'youtube', 'twitch'

// Initialize chart sorting
function initChartSorting() {
    createSortingUI();
    loadSortingSettings();
}

// Create the sorting dropdown UI
function createSortingUI() {
    const widgetContainer2 = document.getElementById('widgetContainer2');

    if (widgetContainer2) {
        const sortingDiv = document.createElement('div');
        sortingDiv.className = 'chart-sorting-container mt-3 mb-3';
        sortingDiv.innerHTML = `
            <div class="d-flex justify-content-center align-items-center">
                <label for="chartSortDropdown" class="form-label me-2 mb-0">
                    <i class="fas fa-sort"></i> Sort Chart:
                </label>
                <select class="form-select form-select-sm" id="chartSortDropdown" style="width: auto;">
                    <option value="popular">Popular (Total Votes)</option>
                    <option value="youtube">YouTube Popular</option>
                    <option value="twitch">Twitch Popular</option>
                </select>
            </div>
        `;

        // Insert the sorting dropdown before the toggle button
        const toggleButtonContainer = widgetContainer2.querySelector('.text-center');
        if (toggleButtonContainer) {
            widgetContainer2.insertBefore(sortingDiv, toggleButtonContainer);
        } else {
            widgetContainer2.appendChild(sortingDiv);
        }

        setupSortingEventListeners();
    }
}

// Set up event listeners for sorting
function setupSortingEventListeners() {
    const sortDropdown = document.getElementById('chartSortDropdown');
    if (sortDropdown) {
        sortDropdown.addEventListener('change', function () {
            currentSortMode = this.value;
            saveSortingSettings();
            refreshChart();
        });
    }
}

// Get sorted data based on current sort mode
function getSortedChartData(dataToUse) {
    const labels = [];
    const totalValues = [];
    const youtubeValues = [];
    const twitchValues = [];
    const sortKeys = []; // Values to sort by

    dataToUse.forEach((voteData, candidate) => {
        // Handle both old format (numbers) and new format (objects with source tracking)
        if (typeof voteData === 'number') {
            // Legacy format - only include if > 0
            if (voteData > 0) {
                labels.push(candidate);
                totalValues.push(voteData);
                youtubeValues.push(0);
                twitchValues.push(0);

                // For legacy data, use total for all sort modes
                sortKeys.push(voteData);
            }
        } else if (typeof voteData === 'object' && voteData !== null) {
            // New format with source tracking - only include if total > 0
            if (voteData.total > 0) {
                labels.push(candidate);
                totalValues.push(voteData.total);
                youtubeValues.push(voteData.youtube || 0);
                twitchValues.push(voteData.twitch || 0);

                // Choose sort key based on mode
                switch (currentSortMode) {
                    case 'youtube':
                        sortKeys.push(voteData.youtube || 0);
                        break;
                    case 'twitch':
                        sortKeys.push(voteData.twitch || 0);
                        break;
                    case 'popular':
                    default:
                        sortKeys.push(voteData.total);
                        break;
                }
            }
        }
    });

    // If no data, return empty arrays
    if (labels.length === 0) {
        return {
            labels: [],
            totalValues: [],
            youtubeValues: [],
            twitchValues: [],
            sortKeys: []
        };
    }

    // Create indices array and sort by the chosen criteria
    const sortedIndices = sortKeys.map((_, i) => i).sort((a, b) => {
        const aValue = sortKeys[a];
        const bValue = sortKeys[b];

        if (aValue !== bValue) {
            return bValue - aValue; // Primary sort: descending by chosen metric
        }

        // Secondary sort: if primary values are equal, sort by total votes
        return totalValues[b] - totalValues[a];
    });

    return {
        labels: sortedIndices.map(i => labels[i]),
        totalValues: sortedIndices.map(i => totalValues[i]),
        youtubeValues: sortedIndices.map(i => youtubeValues[i]),
        twitchValues: sortedIndices.map(i => twitchValues[i]),
        sortKeys: sortedIndices.map(i => sortKeys[i])
    };
}

// Enhanced renderChartJS function with sorting
function renderChartJSWithSorting() {
    console.log('=== renderChartJSWithSorting called ===');
    console.log('window._tempCombinedStats exists:', !!window._tempCombinedStats);

    // Check for temporary combined stats first (from drag-combine feature)
    let dataToUse;
    if (window._tempCombinedStats) {
        console.log('renderChartJSWithSorting: Using _tempCombinedStats');
        console.log('_tempCombinedStats keys:', Array.from(window._tempCombinedStats.keys()));
        dataToUse = window._tempCombinedStats;
    } else {
        // Determine which data source to use
        const useDoubleVoteMode = (typeof window !== 'undefined' &&
            typeof window.isDoubleVoteMode !== 'undefined' &&
            window.isDoubleVoteMode === true &&
            typeof combinationStats !== 'undefined' &&
            combinationStats.size > 0);

        dataToUse = useDoubleVoteMode ? combinationStats : (typeof stats !== 'undefined' ? stats : new Map());
        console.log('renderChartJSWithSorting: Using regular stats, keys:', Array.from(dataToUse.keys()));
    }

    // Check if we have any data with votes > 0
    let hasVotes = false;
    dataToUse.forEach((voteData) => {
        if (typeof voteData === 'number' && voteData > 0) {
            hasVotes = true;
        } else if (typeof voteData === 'object' && voteData.total > 0) {
            hasVotes = true;
        }
    });

    console.log('hasVotes:', hasVotes);
    console.log('dataToUse size:', dataToUse.size);

    const ctx = document.getElementById('chartjs-chart').getContext('2d');

    // If no votes, show empty chart
    if (!hasVotes) {
        return new Chart(ctx, {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: 'No votes yet',
                    data: [],
                    backgroundColor: 'rgba(200, 200, 200, 0.3)',
                    borderColor: 'rgba(200, 200, 200, 0.8)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 10, // Show some scale even when empty
                        ticks: {
                            stepSize: 1,
                            precision: 0
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: 'Waiting for votes...'
                    }
                }
            }
        });
    }

    // Get sorted data
    const sortedData = getSortedChartData(dataToUse);
    console.log('sortedData.labels:', sortedData.labels);
    console.log('sortedData.totalValues:', sortedData.totalValues);

    // Check if source tracking is enabled
    const useSourceTracking = (typeof window.doubleVote !== 'undefined' &&
        window.doubleVote.isSourceTrackingEnabled &&
        window.doubleVote.isSourceTrackingEnabled());

    if (useSourceTracking) {
        // Show source tracking with side-by-side bars
        return new Chart(ctx, {
            type: 'bar',
            data: {
                labels: sortedData.labels,
                datasets: [
                    {
                        label: 'YouTube',
                        data: sortedData.youtubeValues,
                        backgroundColor: 'rgba(255, 0, 0, 0.7)',
                        borderColor: 'rgba(255, 0, 0, 1)',
                        borderWidth: 1,
                        barPercentage: 0.8,
                        categoryPercentage: 0.9
                    },
                    {
                        label: 'Twitch',
                        data: sortedData.twitchValues,
                        backgroundColor: 'rgba(147, 96, 255, 0.7)',
                        borderColor: 'rgba(147, 96, 255, 1)',
                        borderWidth: 1,
                        barPercentage: 0.8,
                        categoryPercentage: 0.9
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                indexAxis: 'x',
                scales: {
                    x: {
                        stacked: false
                    },
                    y: {
                        stacked: false,
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1,
                            precision: 0
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    title: {
                        display: true,
                        text: getSortModeTitle()
                    },
                    tooltip: {
                        callbacks: {
                            footer: function (tooltipItems) {
                                const index = tooltipItems[0].dataIndex;
                                const total = sortedData.totalValues[index];
                                const youtube = sortedData.youtubeValues[index];
                                const twitch = sortedData.twitchValues[index];
                                return `Total: ${total} (YouTube: ${youtube}, Twitch: ${twitch})`;
                            }
                        }
                    }
                }
            }
        });
    } else {
        // Use regular chart (total votes only)
        return new Chart(ctx, {
            type: 'bar',
            data: {
                labels: sortedData.labels,
                datasets: [{
                    label: useDoubleVoteMode ? 'Combined Votes' : 'Votes',
                    data: getSortModeDisplayValues(sortedData),
                    backgroundColor: getSortModeColor(),
                    borderColor: getSortModeBorderColor(),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1,
                            precision: 0
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: getSortModeTitle()
                    },
                    tooltip: {
                        callbacks: {
                            afterLabel: function (context) {
                                const index = context.dataIndex;
                                const total = sortedData.totalValues[index];
                                const youtube = sortedData.youtubeValues[index];
                                const twitch = sortedData.twitchValues[index];

                                if (currentSortMode !== 'popular' && (youtube > 0 || twitch > 0)) {
                                    return `Total: ${total} (YouTube: ${youtube}, Twitch: ${twitch})`;
                                }
                                return null;
                            }
                        }
                    }
                }
            }
        });
    }
}

// Get the appropriate values to display based on sort mode
function getSortModeDisplayValues(sortedData) {
    switch (currentSortMode) {
        case 'youtube':
            return sortedData.youtubeValues;
        case 'twitch':
            return sortedData.twitchValues;
        case 'popular':
        default:
            return sortedData.totalValues;
    }
}

// Get chart color based on sort mode
function getSortModeColor() {
    switch (currentSortMode) {
        case 'youtube':
            return 'rgba(255, 0, 0, 0.7)'; // Red for YouTube
        case 'twitch':
            return 'rgba(147, 96, 255, 0.7)'; // Purple for Twitch
        case 'popular':
        default:
            return 'rgba(75, 192, 192, 0.5)'; // Default teal
    }
}

// Get chart border color based on sort mode
function getSortModeBorderColor() {
    switch (currentSortMode) {
        case 'youtube':
            return 'rgba(255, 0, 0, 1)';
        case 'twitch':
            return 'rgba(147, 96, 255, 1)';
        case 'popular':
        default:
            return 'rgba(75, 192, 192, 1)';
    }
}

// Get title for chart based on sort mode
function getSortModeTitle() {
    switch (currentSortMode) {
        case 'youtube':
            return 'Sorted by YouTube Votes';
        case 'twitch':
            return 'Sorted by Twitch Votes';
        case 'popular':
        default:
            return 'Sorted by Total Votes';
    }
}

// Refresh the chart with current settings
function refreshChart() {
    if (typeof chart !== 'undefined' && chart) {
        chart.destroy();
    }

    // Use our enhanced render function
    if (typeof window !== 'undefined') {
        window.chart = renderChartJSWithSorting();
    }
}

// Save sorting settings to localStorage
function saveSortingSettings() {
    try {
        localStorage.setItem('chartSortMode', currentSortMode);
    } catch (e) {
        console.error('Failed to save sorting settings:', e);
    }
}

// Load sorting settings from localStorage
function loadSortingSettings() {
    try {
        const saved = localStorage.getItem('chartSortMode');
        if (saved && ['popular', 'youtube', 'twitch'].includes(saved)) {
            currentSortMode = saved;

            // Update dropdown
            const sortDropdown = document.getElementById('chartSortDropdown');
            if (sortDropdown) {
                sortDropdown.value = currentSortMode;
            }
        }
    } catch (e) {
        console.error('Failed to load sorting settings:', e);
    }
}

// Override the global renderChartJS function
function overrideChartRendering() {
    // Store original function
    if (typeof window.renderChartJS === 'function') {
        window.originalRenderChartJS = window.renderChartJS;
    }

    // Override with our sorting-enabled version
    window.renderChartJS = renderChartJSWithSorting;
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function () {
    // Wait for other scripts to load
    setTimeout(() => {
        initChartSorting();
        overrideChartRendering();

        // If there's already a chart, refresh it with sorting
        if (typeof chart !== 'undefined' && chart) {
            refreshChart();
        }
    }, 300);
});

// Export functions for external use
window.chartSorting = {
    getSortMode: () => currentSortMode,
    setSortMode: (mode) => {
        if (['popular', 'youtube', 'twitch'].includes(mode)) {
            currentSortMode = mode;
            const dropdown = document.getElementById('chartSortDropdown');
            if (dropdown) dropdown.value = mode;
            saveSortingSettings();
            refreshChart();
        }
    },
    refresh: refreshChart,
    getSortedData: getSortedChartData
};