    const formID2 = '243167527463865';
    const apiKey2 = '6e2676fa4067aecefdfae6fca7c4bb41';
    
    // Fetch data from the API
    fetch(`https://api.jotform.com/form/${formID2}/submissions?apiKey=${apiKey2}&limit=100`)
        .then(response => response.json())
        .then(data => {
                    console.log("All data:", data); // Log all data to see its structure
    
            // Filter to get submissions with contratoFirmado
            const filteredSubmissions = data.content.filter(entry => {
                const answers = entry.answers;
                for (const key in answers) {
                    if (answers[key].name === "contratoFirmado" && answers[key].answer.length > 0) {
                        return true;
                    }
                }
                return false;
            });
            
            console.log(filteredSubmissions)
            const noProyectos = filteredSubmissions.length;
            document.getElementById("noProyectos").textContent = `${noProyectos}`;
            
    
                   // Extract the required data and perform the calculation
            let totalResult = 0; // Initialize total result
    
            filteredSubmissions.forEach(entry => {
                const answers = entry.answers;
                let monto = 0;
    
                // Extract monto and comision from the answers
                for (const key in answers) {
                    if (answers[key].name === "monto") {
                        monto = parseFloat(answers[key].answer.replace("$", ""));
                    }
                }
    
                // Perform the calculation
                const result = monto;
                totalResult += result; // Add result to total
            });
    
            console.log("Total Result:", totalResult);
    
            // Display the total result in HTML
            const resultsContainer = document.getElementById("results-container");
            resultsContainer.textContent = `$${totalResult.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            
            // Helper function to get the last nine months as strings in the format "MMM yyyy"
    function getLastNineMonths() {
        const months = [];
        const currentDate = new Date();
        for (let i = 0; i < 12; i++) {
            const formattedDate = currentDate.toLocaleString('default', { month: 'short', year: 'numeric' });
            months.push(formattedDate);
            currentDate.setMonth(currentDate.getMonth() - 1);
        }
        return months.reverse();
    }
    
    // Object to hold summed monto values by month
    const monthlySums = {};
    
    // Extract the required data and perform the calculation
    filteredSubmissions.forEach(entry => {
        const answers = entry.answers;
        let monto = 0;
        let fecha = '';
    
        // Extract monto, comision, and fecha from the answers
        for (const key in answers) {
            if (answers[key].name === "monto") {
                monto = parseFloat(answers[key].answer.replace("$", ""));
            } else if (answers[key].name === "fecha") {
                fecha = answers[key].answer;
            }
        }
    
        // Perform the calculation
        const result = monto;
    
        // Parse the date (format: yyyy-mm-dd)
        const [year, month, day] = fecha.split('-');
        const date = new Date(year, month - 1, day);
        const formattedDate = date.toLocaleString('default', { month: 'short', year: 'numeric' });
    
        console.log(`Fecha: ${fecha}, FormattedDate: ${formattedDate}, Monto: ${monto}`);
    
        // Sum the result by formatted date
        if (monthlySums[formattedDate]) {
            monthlySums[formattedDate] += result;
        } else {
            monthlySums[formattedDate] = result;
        }
    });
    
    console.log("Monthly Sums:", monthlySums);
    
    // Get the last nine months
    const lastNineMonths = getLastNineMonths();
    
    // Prepare data for the bar chart, ensuring 0 for months with no data
    const labels = lastNineMonths;
    const datos = lastNineMonths.map(month => monthlySums[month] || 0);
        console.log("Datos:", datos);
        
         // Calculate the sum for the current month
        
        const currentMonthSum = `${datos[11].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;

        // Insert the current month sum into the HTML
        document.getElementById("currentMonthSum").textContent = `$${currentMonthSum}`;
        
        let totalAmountCom = 0;
        filteredSubmissions.forEach(entry => {
            const answers = entry.answers;
            let amount = 0;
            let comision = 0;

            // Extract monto and comision from the answers
            for (const key in answers) {
                if (answers[key].name === "monto") {
                    amount = parseFloat(answers[key].answer.replace("$", ""));
                }else if (answers[key].name === "comision") {
                    comision = parseFloat(answers[key].answer)*0.01;
                }
            }

            const amountCom = amount*(1+comision)
            totalAmountCom += amountCom; // Add result to total
        });
            console.log("Colocado con comisiones:", totalAmountCom)
            const comisionesTotal = totalAmountCom- totalResult
            document.getElementById("comisionesTotal").textContent = `$${comisionesTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
        
        // Create the bar chart
        const ctx = document.getElementById("myChart").getContext("2d");
        new Chart(ctx, {
            type: "bar",
            data: {
                labels: labels,
                datasets: [{
                    label: "Monto",
                    tension: 0.4,
                    borderRadius: 4,
                    borderSkipped: false,
                    borderColor: "#8ac926",
                    backgroundColor: "#8ac926",
                    fill: true,
                    borderWidth: 3,
                    data: datos,
                    maxBarThickness: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false,
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index',
                },
                scales: {
                    y: {
                      grid: {
                        drawBorder: false,
                        display: true,
                        drawOnChartArea: true,
                        drawTicks: false,
                        borderDash: [5, 5]
                      },
                      ticks: {
                        display: true,
                        padding: 10,
                        color: '#b2b9bf',
                        font: {
                          size: 11,
                          style: 'normal',
                          lineHeight: 2
                        },
                      }
                    },
                    x: {
                      grid: {
                        drawBorder: false,
                        display: false,
                        drawOnChartArea: false,
                        drawTicks: false,
                        borderDash: [5, 5]
                      },
                      ticks: {
                        display: true,
                        color: '#b2b9bf',
                        padding: 10,
                        font: {
                          size: 11,
                          style: 'normal',
                          lineHeight: 2
                        },
                      }
                    },
                },
            },
        });
         
         // Object to hold summed monto values by project
        const projectSums = {};

        // Calculate the total monto
        let totalMonto = 0;

        // Extract the required data and perform the calculation
        filteredSubmissions.forEach(entry => {
            const answers = entry.answers;
            let monto = 0;
            let projectName = "Unnamed Project";

            // Extract monto and nombrecompleto from the answers
            for (const key in answers) {
                if (answers[key].name === "monto") {
                    monto = parseFloat(answers[key].answer.replace("$", ""));
                } else if (answers[key].name === "noContrato") {
                    projectName = answers[key].answer;
                }
            }

            totalMonto += monto;

            // Sum the result by project
            if (projectSums[projectName]) {
                projectSums[projectName] += monto;
            } else {
                projectSums[projectName] = monto;
            }
        });

        // Calculate the percentage for each project
        const projectPercentages = {};
        for (const projectName in projectSums) {
            projectPercentages[projectName] = ((projectSums[projectName] / totalMonto) * 100);
        }

        console.log("Sums by name:", projectSums);
        console.log("Percentages by name:", projectPercentages);

        // Prepare data for the pie chart
        const namesLabels = Object.keys(projectPercentages);
        const datosPie = Object.values(projectPercentages);
        
        
        // Function to calculate HHI
        function calculateHHI(projectSums) {
            // Convert the percentage shares to decimals
            const projectShares = Object.values(projectPercentages).map(percentage => parseFloat(percentage) / 100);
        
            // Calculate the HHI
            const hhi = projectShares.reduce((sum, share) => sum + share ** 2, 0);
        
            return hhi;
        }
        
        const hhi = calculateHHI(projectSums);
        
        console.log("Herfindahl-Hirschman Index (HHI):", hhi);
        document.getElementById("indexHHI").textContent = `${(hhi*100).toFixed(2)}%`;
        
       
        // Prepare data for the pie chart
        const pieData = {
            labels: namesLabels,
            datasets: [{
                  weight: 9,
                cutout: 0,
                tension: 0.9,
                pointRadius: 2,
                borderWidth: 2,
                data: datosPie,
                backgroundColor: ['#ff595e', '#ff924c', '#ffca3a', '#c5ca30', '#8ac926', '#36949d', '#1982c4', '#4267ac', '#565aa0', '#6a4c93'
                ],
                borderWidth: 1
            }]
        };
        // Create the pie chart
        const pieChart = document.getElementById("pie-chart").getContext("2d");
        new Chart(pieChart, {
            type: "pie",
            data: pieData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false,
                    },
                    tooltip: {
                        callbacks: {
                            label: function(tooltipItem) {
                                return tooltipItem.label + ': ' + tooltipItem.raw.toFixed(2) + '%';
                            }
                        }
                    }
                }
            }
        });
        
    })
    .catch(error => {
        console.error("Error fetching data:", error);
    });