var DashUf = SuperWidget.extend({

    chart: null,

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

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

    render: function (dados) {
        var ranking = this.montarRanking(dados);
        if (!ranking.length) {
            ranking = [{ nome: "Sem dados", total: 0 }];
        }

        this.plot(
            ranking.map(function (item) { return item.nome; }),
            ranking.map(function (item) { return item.total; })
        );
    },

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

        dados.forEach(function (item) {
            var uf = String(item.uf || "").replace(/\s+/g, " ").trim().toUpperCase();
            if (!uf) {
                uf = "SEM UF";
            }
            mapa[uf] = (mapa[uf] || 0) + 1;
        });

        return Object.keys(mapa).map(function (uf) {
            return {
                nome: uf,
                total: mapa[uf]
            };
        }).sort(function (a, b) {
            if (b.total !== a.total) return b.total - a.total;
            return a.nome.localeCompare(b.nome);
        });
    },

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

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

        var valueLabelsPlugin = {
            id: "valueLabelsPluginUf",
            afterDatasetsDraw: function (chart) {
                var c = chart.ctx;
                c.save();
                c.font = "700 11px Arial";
                c.textAlign = "center";
                c.textBaseline = "bottom";
                c.fillStyle = "#0b4f6c";

                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) return;
                        c.fillText(String(value), bar.x, bar.y - 4);
                    });
                });

                c.restore();
            }
        };

        this.chart = new Chart(canvas, {
            type: "bar",
            plugins: [valueLabelsPlugin],
            data: {
                labels: labels,
                datasets: [{
                    label: "Auditorias",
                    data: valores,
                    backgroundColor: "#0b6a88",
                    borderColor: "#084d64",
                    borderWidth: 1,
                    borderRadius: 6,
                    maxBarThickness: 46
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return "Auditorias: " + context.raw;
                            }
                        }
                    }
                },
                layout: {
                    padding: {
                        top: 18,
                        right: 8
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: {
                            color: "#4b5563",
                            font: {
                                size: 11,
                                weight: "600"
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                            color: "#6b7280"
                        },
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

});
