document.addEventListener("DOMContentLoaded", function () {
    if (typeof Highcharts === "undefined") {
        console.error("Highcharts library not loaded!");
        return;
    }

    function createGaugeChart(progress, color, divId, title, height, width, fontSize, fontYAxis, fontXAxis, fontColor, total, actual, aGrade, bGrade, cGrade) {
        Highcharts.chart(divId, {
            chart: {
                type: 'solidgauge',
                width: width,
                height: height,
                backgroundColor: 'transparent',
                plotBackgroundColor: null,
                shadow: false
            },
            title: {
                text: title,
                y: 30
            },
            pane: {
                startAngle: 0,
                endAngle: 360,
                y: 0,
                background: [{
                    backgroundColor: 'transparent',
                    shape: "arc",
                    borderWidth: 0,
                    innerRadius: '60%',
                    outerRadius: '100%'
                }]
            },
            yAxis: {
                min: 0,
                max: 100,
                tickPositions: [],
                lineWidth: 0,
                minorTickLength: 0,
                tickWidth: 0,
                gridLineWidth: 0,
                stops: [
                    [1, color]
                ]
            },
            series: [{
                name: 'Percentage',
                data: [progress],
                dataLabels: {
                    format: '{y}% ',
                    y: fontYAxis,
                    x: fontXAxis,
                    borderWidth: 0,
                    backgroundColor: 'none',
                    style: {
                        fontSize: fontSize + 'px',
                        fontWeight: 'bold',
                        color: fontColor
                    },
                    zIndex: 10
                },
                tooltip: {
                    pointFormat: title == 'Finishing Progress' ? 'Percentage: ' + progress + '%<br>Total: ' + total + '<br>Completed: ' + actual + '<br>A Grade: ' + aGrade + '<br>B Grade: ' + bGrade + '<br>C Grade: ' + cGrade : 'Percentage: ' + progress + '%<br>Total: ' + total + '<br>Completed:' + actual
                },
                color: color,
                showInLegend: false
            }],
            credits: {
                enabled: false
            }
        });
    }

    function createBarChart(divId, height, width, title, aHeading, aData, bHeading, bData, cHeading, cData, dHeading, dData, dates, fontSize, maxValue) {
        if (!document.getElementById(divId)) {
            return;
        }
        Highcharts.chart(divId, {
            chart: {
                type: 'column',
                height: height,
                width: width,
            },
            title: {
                text: title,
                align: 'center',
                verticalAlign: 'top',
                y: 30,
                style: {
                    fontSize: fontSize,
                    fontWeight: 'bold',
                }
            },
            xAxis: {
                categories: dates,
                labels: {
                    rotation: -45,
                    style: {
                        fontSize: 10 - fontSize,
                        fontWeight: 'bold'
                    }
                }
            },
            yAxis: {
                min: 0,
                max: maxValue,
                softMax: maxValue,
                softMin: 0,
                startOnTick: true,
                endOnTick: true,
                title: {
                    text: 'Total Progress',
                    style: {
                        fontSize: fontSize,
                        fontWeight: 'bold',
                    }
                },
                labels: {
                    format: '{value}%'
                }
            },

            scrollbar: {
                enabled: true
            },
            series: [{
                name: aHeading,
                data: aData
            }, {
                name: bHeading,
                data: bData
            }, {
                name: cHeading,
                data: cData
            }, {
                name: dHeading,
                data: dData
            }]
        });
    }

    function dashboardChart(
        divId, height, width, title,
        aHeading, aData, bHeading, bData, cHeading, cData,
        dates, fontSize, fontSizeText, maxValue
    ) {
        if (!document.getElementById(divId)) return;

        Highcharts.chart(divId, {
            chart: {
                type: 'bar',
                height: height,
                width: width
            },
            title: {
                text: title,
                style: {
                    fontSize: fontSize
                }
            },
            xAxis: {
                categories: dates,
                labels: {
                    enabled: false
                },
                title: {
                    text: null
                },
                lineWidth: 2
            },
            yAxis: {
                max: maxValue,
                min: 0,
                title: {
                    text: null,
                    align: 'high',
                    style: {
                        fontSize: fontSizeText
                    }
                },
                labels: {
                    style: {
                        fontSize: fontSizeText
                    }
                },
                gridLineWidth: 0
            },
            legend: {
                itemStyle: {
                    fontSize: fontSizeText
                }
            },
            plotOptions: {
                bar: {
                    borderRadius: '50%',
                    dataLabels: {
                        enabled: true,
                        style: {
                            fontSize: fontSizeText
                        }
                    },
                    groupPadding: 0.1
                }
            },
            credits: {
                enabled: false
            },
            series: [
                {
                    name: aHeading,
                    data: aData
                },
                {
                    name: bHeading,
                    data: bData
                },
                {
                    name: cHeading,
                    data: cData
                }
            ]
        });
    }


    function createSingleBarChart(divId, height, width, title, Heading, Data, dates, fontSize, maxValue) {
        if (!document.getElementById(divId)) {
            return;
        }
        Highcharts.chart(divId, {
            chart: {
                type: 'column',
                height: height,
                width: width,
            },
            title: {
                text: title,
                align: 'center',
                verticalAlign: 'top',
                y: 30,
                style: {
                    fontSize: fontSize,
                    fontWeight: 'bold',
                }
            },
            xAxis: {
                categories: dates,
                labels: {
                    rotation: -45,
                    style: {
                        fontSize: 10 - fontSize,
                        fontWeight: 'bold'
                    }
                }
            },
            yAxis: {
                min: 0,
                max: maxValue,
                softMax: maxValue,
                softMin: 0,
                startOnTick: true,
                endOnTick: true,
                title: {
                    text: 'Total Progress',
                    style: {
                        fontSize: fontSize,
                        fontWeight: 'bold',
                    }
                },
                labels: {
                    format: '{value}%'
                }
            },
            legend: {
                itemStyle: {
                    fontSize: 10 - fontSize,
                    fontWeight: 'bold'
                }
            },
            scrollbar: {
                enabled: true
            },
            series: [{
                name: Heading,
                data: Data
            }]
        });
    }

    initializeGauges();

    function initializeGauges() {

        const gaugeDivs2 = document.querySelectorAll('.gauge-chart2');
        gaugeDivs2.forEach(function (div) {
            const progress = div.getAttribute('data-progress');
            const color = div.getAttribute('data-color');
            const title = div.getAttribute('data-title');
            const height = div.getAttribute('data-height');
            const width = div.getAttribute('data-width');
            const fontSize = div.getAttribute('data-fontSize');
            const fontColor = div.getAttribute('data-fontColor');
            const total = div.getAttribute('data-totalProduction');
            const actual = div.getAttribute('data-actualProduction');
            const divId = div.id;
            console.log(actual)
            createGaugeChart(parseInt(progress), color, divId, title, height, width, fontSize, -20, 4, fontColor, total, actual);
        });

        const gaugeDivs = document.querySelectorAll('.gauge-chart');
        gaugeDivs.forEach(function (div) {
            const progress = div.getAttribute('data-progress');
            const color = div.getAttribute('data-color');
            const title = div.getAttribute('data-title');
            const height = div.getAttribute('data-height');
            const width = div.getAttribute('data-width');
            const fontSize = div.getAttribute('data-fontSize');
            const fontColor = div.getAttribute('data-fontColor');
            const total = div.getAttribute('data-totalProduction');
            const actual = div.getAttribute('data-actualProduction');
            const aGrade = div.getAttribute('data-aGrade');
            const bGrade = div.getAttribute('data-bGrade');
            const cGrade = div.getAttribute('data-cGrade');
            const divId = div.id;
            createGaugeChart(parseInt(progress), color, divId, title, height, width, fontSize, -15, 2, fontColor, total, actual, aGrade, bGrade, cGrade);

        });

        const barChart = document.querySelectorAll('.barChart');
        barChart.forEach(function (div) {
            const title = div.getAttribute('data-title');
            const height = div.getAttribute('data-height');
            const width = div.getAttribute('data-width');
            const fontSize = div.getAttribute('data-fontSize');
            const maxValue = Number(div.getAttribute('data-totalProduction'));
            const aHeading = 'Cutting';
            const aData = JSON.parse(div.getAttribute('data-cutting'));
            const bHeading = 'Stitching';
            const bData = JSON.parse(div.getAttribute('data-stitching'));
            const cHeading = 'End Line Quality Checking';
            const cData = JSON.parse(div.getAttribute('data-quality'));
            const dHeading = "Finish Items";
            const dData = JSON.parse(div.getAttribute('data-finishing'));
            const dates = div.getAttribute('data-dates');
            const datesArray = dates.split(',');
            const divId = div.id;
            createBarChart(divId, height, width, title, aHeading, aData, bHeading, bData, cHeading, cData, dHeading, dData, datesArray, fontSize, maxValue);
        });

        const dashboardBarChart = document.querySelectorAll('.dashboardBarChart'); // fixed name
        dashboardBarChart.forEach(function (div) {
            const title = div.getAttribute('data-title');
            const height = div.getAttribute('data-height');
            const width = div.getAttribute('data-width');
            const fontSize = div.getAttribute('data-fontSize');

            const rawValue = div.getAttribute('data-totalProduction') || "0";
            const cleanValue = rawValue.replace(/[^0-9.-]+/g, '');
            const maxValue = Number(cleanValue);

            const aHeading = 'Stitching';
            const aDataString = div.getAttribute('data-stitching');
            const cleanValueStitch = aDataString.replace(/[^0-9.-]+/g, '');
            const aData = [Number(cleanValueStitch)];

            const bHeading = 'Finishing';
            const bDataString = div.getAttribute('data-finishing');
            const packaging = bDataString.replace(/[^0-9.-]+/g, '');
            const bData = [Number(packaging)];

            const cHeading = 'Packaging';
            const cDataString = div.getAttribute('data-packaging');
            const cleanValueAchieved = cDataString.replace(/[^0-9.-]+/g, '');
            const cData = [Number(cleanValueAchieved)];

            const dates = [div.getAttribute('data-dates')];
            const divId = div.id;
            dashboardChart(
                divId,
                height,
                width,
                title,
                aHeading,
                aData,
                bHeading,
                bData,
                cHeading,
                cData,
                dates,
                fontSize,
                '20',
                maxValue
            );
        });

        const cuttingBarChart = document.querySelectorAll('.singleBarChart');
        cuttingBarChart.forEach(function (div) {
            const title = div.getAttribute('data-title');
            const height = div.getAttribute('data-height');
            const width = div.getAttribute('data-width');
            const fontSize = div.getAttribute('data-fontSize');
            const maxValue = Number(div.getAttribute('data-totalProduction'));
            const Heading = div.getAttribute('data-barHeading');
            const Data = JSON.parse(div.getAttribute('data-barData'));
            const dates = div.getAttribute('data-dates');
            const datesArray = dates.split(',');
            const divId = div.id;
            createSingleBarChart(divId, height, width, title, Heading, Data, datesArray, fontSize, maxValue);
        });
    }
});
