var DashGrafico = SuperWidget.extend({

    chart: null,

    init: function () {
        var self = this;
        this.render([]);

        window.addEventListener("dashboardData", function (e) {
            self.render(e.detail || []);
        });
    },

    render: function (dados) {
        var mapa = {};

        dados.forEach(function (item) {
            var regiao = String(item.regional || "Sem regiao").trim();
            if (!mapa[regiao]) {
                mapa[regiao] = { total: 0, conforme: 0, naoConforme: 0 };
            }
            mapa[regiao].total += 1;
            if (normalizaStatus(item) === "CONFORME") {
                mapa[regiao].conforme += 1;
            } else {
                mapa[regiao].naoConforme += 1;
            }
        });

        var labels = Object.keys(mapa).sort(function (a, b) { return a.localeCompare(b); });
        if (!labels.length) {
            labels = ["Aguardando filtro"];
            this.plot(labels, [0], [0]);
            return;
        }

        var atingimento = labels.map(function (l) {
            var r = mapa[l];
            return r.total ? Number(((r.conforme / r.total) * 100).toFixed(2)) : 0;
        });

        var ncMedio = labels.map(function (l) {
            var r = mapa[l];
            return r.total ? Number(((r.naoConforme / r.total) * 100).toFixed(2)) : 0;
        });

        this.plot(labels, atingimento, ncMedio);
    },

    plot: function (labels, atingimento, ncMedio) {
        var canvas = document.getElementById("grafico_" + this.instanceId);
        if (!canvas) return;

        if (this.chart) {
            this.chart.destroy();
        }

        var valueLabelsPlugin = {
            id: "valueLabelsPlugin",
            afterDatasetsDraw: function (chart) {
                var c = chart.ctx;
                c.save();
                c.font = "700 10px Arial";
                c.textAlign = "center";

                chart.data.datasets.forEach(function (dataset, datasetIndex) {
                    var meta = chart.getDatasetMeta(datasetIndex);
                    meta.data.forEach(function (bar, index) {
                        var value = dataset.data[index];
                        if (value == null || Number(value) === 0) return;

                        var y = bar.y - 4;
                        var baseline = "bottom";
                        if (y < chart.chartArea.top + 12) {
                            y = bar.y + 10;
                            baseline = "top";
                        }

                        c.textBaseline = baseline;
                        c.fillStyle = baseline === "top" ? "#ffffff" : "#111111";
                        c.fillText(String(value).replace(".", ",") + "%", bar.x, y);
                    });
                });

                c.restore();
            }
        };

        this.chart = new Chart(canvas, {
            type: "bar",
            plugins: [valueLabelsPlugin],
            data: {
                labels: labels,
                datasets: [
                    {
                        label: "Atingimento (%)",
                        data: atingimento,
                        backgroundColor: "#0a5d82"
                    },
                    {
                        label: "Nao conforme (%)",
                        data: ncMedio,
                        backgroundColor: "#88a5b8"
                    }
                ]
            },
            options: {
                responsive: true,
                layout: {
                    padding: {
                        top: 14
                    }
                },
                plugins: {
                    legend: {
                        position: "top"
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            autoSkip: false,
                            maxRotation: 20,
                            minRotation: 0,
                            callback: function (value, index) {
                                var txt = labels[index] || "";
                                return txt.length > 18 ? txt.substring(0, 18) + "..." : txt;
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: function (value) {
                                return value + "%";
                            }
                        },
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

});

function normalizaStatus(item) {
    return String(item.saidaAnalise || item.status || "").trim().toUpperCase();
}
