var DashConforme = 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 loja = String(item.loja || "Sem loja").trim();
            if (!mapa[loja]) {
                mapa[loja] = { total: 0, conforme: 0 };
            }
            mapa[loja].total += 1;
            if (normalizaStatus(item) === "CONFORME") {
                mapa[loja].conforme += 1;
            }
        });

        var pares = Object.keys(mapa).map(function (nome) {
            var total = mapa[nome].total;
            var pct = total ? (mapa[nome].conforme / total) * 100 : 0;
            return { nome: nome, pct: Number(pct.toFixed(2)) };
        });

        pares.sort(function (a, b) {
            return b.pct - a.pct;
        });

        if (!pares.length) {
            pares = [{ nome: "Aguardando filtro", pct: 0 }];
        }

        var labels = pares.map(function (p) { return p.nome; });
        var valores = pares.map(function (p) { return p.pct; });

        var ctx = document.getElementById("graficoConforme_" + this.instanceId);
        if (!ctx) 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(ctx, {
            type: "bar",
            plugins: [valueLabelsPlugin],
            data: {
                labels: labels,
                datasets: [{
                    data: valores,
                    backgroundColor: "#0a5d82"
                }]
            },
            options: {
                responsive: true,
                layout: {
                    padding: {
                        top: 14
                    }
                },
                plugins: { legend: { display: false } },
                scales: {
                    x: {
                        ticks: {
                            autoSkip: false,
                            maxRotation: 28,
                            minRotation: 10,
                            callback: function (value, index) {
                                var txt = labels[index] || "";
                                return txt.length > 22 ? txt.substring(0, 22) + "..." : txt;
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: function (value) {
                                return value + "%";
                            }
                        }
                    }
                }
            }
        });
    }

});

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