<script>
    // License data
    const licenseData = [
        {
            "product": "Visual Studio Enterprise Subscription with GitHub Enterprise",
            "edition": "Enterprise",
            "version": 2022,
            "licenseMetric": "User",
            "softwareAssurance": 76,
            "entitlement": 76,
            "deployment": 0,
            "financialRisk": 0,
            "potentialSavings": 0,
            "gap": 0
        },
        {
            "product": "Visual Studio Pro Subscription with GitHub Enterprise",
            "edition": "Enterprise",
            "version": 2022,
            "licenseMetric": "User",
            "softwareAssurance": 119,
            "entitlement": 119,
            "deployment": 0,
            "financialRisk": 0,
            "potentialSavings": 0,
            "gap": 0
        },
        {
            "product": "BizTalk Server Enterprise - 2 Core",
            "edition": "Enterprise",
            "version": 2020,
            "licenseMetric": "2-Core",
            "softwareAssurance": 8,
            "entitlement": 8,
            "deployment": 8,
            "financialRisk": 0,
            "potentialSavings": 0,
            "gap": 0
        },
        {
            "product": "Windows Remote Desktop Services - User CAL",
            "edition": "n/a",
            "version": 2022,
            "licenseMetric": "User CAL",
            "softwareAssurance": 1100,
            "entitlement": 1100,
            "deployment": 671,
            "financialRisk": 0,
            "potentialSavings": 10862.28,
            "gap": 0
        },
        {
            "product": "SQL Server Standard - 2 Core",
            "edition": "Standard",
            "version": 2022,
            "licenseMetric": "2-Core",
            "softwareAssurance": 268,
            "entitlement": 268,
            "deployment": 193,
            "financialRisk": 0,
            "potentialSavings": 11765.52,
            "gap": 0
        },
        {
            "product": "SQL Server Enterprise - 2 Core",
            "edition": "Enterprise",
            "version": 2022,
            "licenseMetric": "2-Core",
            "softwareAssurance": 408,
            "entitlement": 6000,
            "deployment": 400,
            "financialRisk": 12000,
            "potentialSavings": 170429.76,
            "gap": 0
        },
        {
            "product": "Core Infrastructure Server Suite Datacenter - 2 Core",
            "edition": "Datacenter",
            "version": 2022,
            "licenseMetric": "2-Core",
            "softwareAssurance": 2976,
            "entitlement": 2976,
            "deployment": 3000,
            "financialRisk": 25000,
            "potentialSavings": 0,
            "gap": 24
        },
        {
            "product": "Core Infrastructure Server Suite Standard - 2 Core",
            "edition": "Standard",
            "version": 2022,
            "licenseMetric": "2-Core",
            "softwareAssurance": 4562,
            "entitlement": 4562,
            "deployment": 4220,
            "financialRisk": 4500,
            "potentialSavings": 13214.88,
            "gap": 0
        }
    ];

    // Utility functions
    function formatCurrency(value) {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD'
        }).format(value);
    }

    function getSelectedValues(selectElement) {
        return Array.from(selectElement.selectedOptions).map(option => option.value);
    }

    // Initialize filters
    function initializeFilters() {
        const products = [...new Set(licenseData.map(item => item.product))].sort();
        
        const productSelect = document.getElementById('product-filter');
        
        // Add product options
        productSelect.innerHTML = '<option value="">All Products</option>';
        products.forEach(product => {
            productSelect.add(new Option(product, product));
        });

        // Initial population of Edition and Version filters
        updateDependentFilters();
    }

    function updateDependentFilters() {
        const selectedProducts = getSelectedValues(document.getElementById('product-filter'));
        const editionSelect = document.getElementById('edition-filter');
        const versionSelect = document.getElementById('version-filter');

        let filteredData = licenseData;
        if (selectedProducts.length > 0) {
            filteredData = licenseData.filter(item => selectedProducts.includes(item.product));
        }

        const editions = [...new Set(filteredData.map(item => item.edition))].sort();
        const versions = [...new Set(filteredData.map(item => item.version))].sort((a, b) => b - a);

        editionSelect.innerHTML = '<option value="">All Editions</option>';
        editions.forEach(edition => {
            editionSelect.add(new Option(edition, edition));
        });

        versionSelect.innerHTML = '<option value="">All Versions</option>';
        versions.forEach(version => {
            versionSelect.add(new Option(version, version));
        });

        handleFilterChange();
    }

    function handleFilterChange() {
        const selectedProducts = getSelectedValues(document.getElementById('product-filter'));
        const selectedEditions = getSelectedValues(document.getElementById('edition-filter'));
        const selectedVersions = getSelectedValues(document.getElementById('version-filter'));

        let filteredData = licenseData;

        if (selectedProducts.length > 0) {
            filteredData = filteredData.filter(item => selectedProducts.includes(item.product));
        }
        if (selectedEditions.length > 0) {
            filteredData = filteredData.filter(item => selectedEditions.includes(item.edition));
        }
        if (selectedVersions.length > 0) {
            filteredData = filteredData.filter(item => selectedVersions.includes(item.version.toString()));
        }

        updateDashboard(filteredData);
    }

    function updateDashboard(data) {
    updateMetrics(data);
    updateCharts(data);
    updateTables(data);
    updateDetailedTable(data); // Add this new line
}

    function updateMetrics(data) {
    const totalRisk = data.reduce((sum, item) => sum + (item.financialRisk || 0), 0);
    const totalSavings = data.reduce((sum, item) => sum + (item.potentialSavings || 0), 0);
    const totalGap = data.reduce((sum, item) => sum + (item.gap || 0), 0);
    
    // New surplus calculation: only count as surplus if there's no gap and entitlement > deployment
    const totalSurplus = data.reduce((sum, item) => {
        if (item.gap > 0) return sum; // If there's a gap, there's no surplus
        const difference = (item.entitlement || 0) - (item.deployment || 0);
        return sum + (difference > 0 ? difference : 0);
    }, 0);

    document.getElementById('total-risk').textContent = formatCurrency(totalRisk);
    document.getElementById('total-savings').textContent = formatCurrency(totalSavings);
    document.getElementById('total-gap').textContent = totalGap;
    document.getElementById('total-surplus').textContent = totalSurplus;
}

    // Create main license position chart
    function createMainChart() {
        const ctx = document.getElementById('licenseChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: licenseData.map(item => item.product.split(' - ')[0]),
                datasets: [{
                    label: 'Entitlements',
                    data: licenseData.map(item => item.entitlement),
                    backgroundColor: '#3182ce',
                    borderColor: '#2c5282',
                    borderWidth: 1
                }, {
                    label: 'Deployments',
                    data: licenseData.map(item => item.deployment),
                    backgroundColor: '#38a169',
                    borderColor: '#2f855a',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: 'y',
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end',
                        labels: {
                            boxWidth: 12,
                            padding: 15,
                            font: { size: 11 }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            font: { size: 11 }
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            font: { size: 11 }
                        }
                    }
                },
                barPercentage: 0.8,
                categoryPercentage: 0.9
            }
        });
    }

    // Create financial charts
    function createFinancialCharts() {
        const commonOptions = {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '60%',
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        usePointStyle: true,
                        padding: 15,
                        font: { size: 11 }
                    }
                },
                title: {
                    display: true,
                    font: { size: 14, weight: '500' },
                    padding: { bottom: 10 }
                }
            }
        };

        // Risk Chart
const riskData = licenseData.filter(item => item.financialRisk > 0);
new Chart(document.getElementById('riskChart'), {
    type: 'doughnut',
    data: {
        labels: riskData.map(item => item.product.split(' - ')[0]),
        datasets: [{
            data: riskData.map(item => item.financialRisk),
            backgroundColor: ['#FF0000', '#FF8C00', '#9B2C2C', '#800080', '#4B0082'],  // Red, Orange, Dark Red, Purple, Indigo
            borderColor: '#ffffff',
            borderWidth: 2
        }]
    },
    options: {
        ...commonOptions,
        plugins: {
            ...commonOptions.plugins,
            title: {
                ...commonOptions.plugins.title,
                text: 'Financial Risk Distribution'
            }
        }
    }
});

        // Savings Chart
        const savingsData = licenseData.filter(item => item.potentialSavings > 0);
        new Chart(document.getElementById('savingsChart'), {
            type: 'doughnut',
            data: {
                labels: savingsData.map(item => item.product.split(' - ')[0]),
                datasets: [{
                    data: savingsData.map(item => item.potentialSavings),
                    backgroundColor: ['#48bb78', '#68d391', '#9ae6b4', '#c6f6d5'],
                    borderColor: '#ffffff',
                    borderWidth: 2
                }]
            },
            options: {
                ...commonOptions,
                plugins: {
                    ...commonOptions.plugins,
                    title: {
                        ...commonOptions.plugins.title,
                        text: 'Potential Savings Distribution'
                    }
                }
            }
        });
    }

    // Update charts based on filtered data
    function updateCharts(data) {
        const mainChart = Chart.getChart('licenseChart');
        if (mainChart) {
            mainChart.data.labels = data.map(item => item.product.split(' - ')[0]);
            mainChart.data.datasets[0].data = data.map(item => item.entitlement);
            mainChart.data.datasets[1].data = data.map(item => item.deployment);
            mainChart.update();
        }

        const riskChart = Chart.getChart('riskChart');
        const riskData = data.filter(item => item.financialRisk > 0);
        if (riskChart) {
            riskChart.data.labels = riskData.map(item => item.product.split(' - ')[0]);
            riskChart.data.datasets[0].data = riskData.map(item => item.financialRisk);
            riskChart.update();
        }

        const savingsChart = Chart.getChart('savingsChart');
        const savingsData = data.filter(item => item.potentialSavings > 0);
        if (savingsChart) {
            savingsChart.data.labels = savingsData.map(item => item.product.split(' - ')[0]);
            savingsChart.data.datasets[0].data = savingsData.map(item => item.potentialSavings);
            savingsChart.update();
        }
    }

    // Update tables with filtered data
    function updateTables(data) {
        const riskTable = document.getElementById('risk-table').getElementsByTagName('tbody')[0];
        const savingsTable = document.getElementById('savings-table').getElementsByTagName('tbody')[0];

        riskTable.innerHTML = '';
        savingsTable.innerHTML = '';

        // Update risk table
        data.filter(item => item.financialRisk > 0)
            .sort((a, b) => b.financialRisk - a.financialRisk)
            .forEach(item => {
                const row = riskTable.insertRow();
                row.insertCell(0).textContent = item.product;
                row.insertCell(1).textContent = formatCurrency(item.financialRisk);
                row.insertCell(2).textContent = item.gap;
                row.cells[1].className = 'risk-high';
            });

        // Update savings table
        data.filter(item => item.potentialSavings > 0)
            .sort((a, b) => b.potentialSavings - a.potentialSavings)
            .forEach(item => {
                const row = savingsTable.insertRow();
                row.insertCell(0).textContent = item.product;
                row.insertCell(1).textContent = formatCurrency(item.potentialSavings);
                row.insertCell(2).textContent = item.entitlement - item.deployment;
                row.cells[1].className = 'risk-low';
            });
    }


    // Initialize dashboard
	/* Add this new function before the window.onload function */
function updateDetailedTable(data) {
    const detailedTable = document.getElementById('detailed-license-table').getElementsByTagName('tbody')[0];
    detailedTable.innerHTML = '';

    data.forEach(item => {
        const row = detailedTable.insertRow();
        
        // Add cells
        row.insertCell(0).textContent = item.product;
        row.insertCell(1).textContent = item.edition;
        row.insertCell(2).textContent = item.licenseMetric;
        row.insertCell(3).textContent = item.entitlement.toLocaleString();
        row.insertCell(4).textContent = item.deployment.toLocaleString();
        
        // Gap/Surplus cell with color coding
        const gapCell = row.insertCell(5);
        gapCell.textContent = item.gap > 0 ? item.gap.toLocaleString() : (item.entitlement - item.deployment).toLocaleString();
        if (item.gap > 0) {
            gapCell.className = 'gap-negative';  // Gap (shortage) should be red
        } else if (item.entitlement > item.deployment) {
            gapCell.className = 'gap-positive';  // Surplus should be green
        }
        
        // Financial columns
        row.insertCell(6).textContent = formatCurrency(item.financialRisk || 0);
        row.insertCell(7).textContent = formatCurrency(item.potentialSavings || 0);
    });
}
	
    window.onload = function() {
        initializeFilters();
        createMainChart();
        createFinancialCharts();
        updateDashboard(licenseData);