var DashPilar = SuperWidget.extend({

    chart: null,

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

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

    render: function (dados) {
        var agregados = this.agruparPorPilar(dados);
        if (!agregados.length) {
            agregados = [{ nome: "Sem dados", score: 0 }];
        }

        this.plot(
            agregados.map(function (item) { return item.nome; }),
            agregados.map(function (item) { return item.score; })
        );
    },

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

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

            var parsed = null;
            try {
                parsed = JSON.parse(raw);
            } catch (e) {
                parsed = null;
            }
            if (!parsed) return;

            Object.keys(parsed).forEach(function (nomePilar) {
                var itemPilar = parsed[nomePilar] || {};
                var score = parseFloat(itemPilar.score);
                if (isNaN(score)) return;

                if (!mapa[nomePilar]) {
                    mapa[nomePilar] = { total: 0, qtd: 0 };
                }
                mapa[nomePilar].total += score;
                mapa[nomePilar].qtd += 1;
            });
        });

        return Object.keys(mapa).map(function (nomePilar) {
            var r = mapa[nomePilar];
            return {
                nome: nomePilar.replace(/^PILAR\s+/i, ""),
                score: r.qtd ? Number((r.total / r.qtd).toFixed(2)) : 0
            };
        }).sort(function (a, b) {
            if (b.score !== a.score) return b.score - a.score;
            return a.nome.localeCompare(b.nome);
        });
    },

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

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

        var valueLabelsPlugin = {
            id: "valueLabelsPluginPilar",
            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).replace(".", ",") + "%", bar.x, bar.y - 4);
                    });
                });

                c.restore();
            }
        };

        this.chart = new Chart(canvas, {
            type: "bar",
            plugins: [valueLabelsPlugin],
            data: {
                labels: labels,
                datasets: [{
                    label: "Score médio",
                    data: valores,
                    backgroundColor: "#0b6a88",
                    borderColor: "#084d64",
                    borderWidth: 1,
                    borderRadius: 6,
                    maxBarThickness: 42
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return "Score médio: " + String(context.raw).replace(".", ",") + "%";
                            }
                        }
                    }
                },
                layout: {
                    padding: {
                        top: 20,
                        right: 10
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: {
                            autoSkip: false,
                            maxRotation: 18,
                            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
                        }
                    }
                }
            }
        });
    }

});
