var DashInconforme = 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).slice(0, 5);
        if (!ranking.length) {
            ranking = [{ nome: "Aguardando filtro", total: 0 }];
        }

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

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

        dados.forEach(function (item) {
            var lista = String(item.listaNaoConforme || "").trim();
            if (!lista) return;

            lista.split("|").forEach(function (parte) {
                var nome = String(parte || "").replace(/\s+/g, " ").trim();
                if (!nome) return;
                mapa[nome] = (mapa[nome] || 0) + 1;
            });
        });

        return Object.keys(mapa).map(function (nome) {
            return {
                nome: nome,
                total: mapa[nome]
            };
        }).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("graficoInconforme_" + 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 11px Arial";
                c.textAlign = "center";
                c.fillStyle = "#111111";

                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.textBaseline = "bottom";
                        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: "Ocorrencias",
                    data: valores,
                    backgroundColor: "#0b6a88",
                    borderColor: "#084d64",
                    borderWidth: 1,
                    borderRadius: 6,
                    maxBarThickness: 42
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            title: function (items) {
                                return items && items.length ? items[0].label : "";
                            },
                            label: function (context) {
                                return "Ocorrencias: " + context.raw;
                            }
                        }
                    }
                },
                layout: {
                    padding: {
                        top: 20,
                        right: 10
                    }
                },
                scales: {
                    x: {
                        ticks: {
                            autoSkip: false,
                            maxRotation: 25,
                            minRotation: 25,
                            callback: function (value, index) {
                                var txt = labels[index] || "";
                                return txt.length > 18 ? txt.substring(0, 18) + "..." : txt;
                            }
                        },
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        },
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

});
