(function () {
    'use strict';

    var data = window.enterpriseChartData || {};
    var charts = {};
    var defaultPeriod = window.enterpriseDefaultPeriod || 'q1';

    Chart.defaults.color = '#6b7280';
    Chart.defaults.borderColor = '#e5e7eb';
    Chart.defaults.font.family = 'Inter, sans-serif';
    Chart.defaults.font.size = 11;

    function buildLineChart(canvasId, dataset) {
        var ctx = document.getElementById(canvasId);
        if (!ctx) return null;

        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: dataset.labels,
                datasets: [{
                    data: dataset.values,
                    borderColor: '#374151',
                    backgroundColor: 'transparent',
                    borderWidth: 2.5,
                    pointBackgroundColor: '#ffffff',
                    pointBorderColor: '#374151',
                    pointBorderWidth: 2,
                    pointRadius: 5,
                    pointHoverRadius: 6,
                    tension: 0.3,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                return ctx.parsed.y + ' total';
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        border: { display: false },
                        ticks: { color: '#9ca3af', font: { weight: '500' } }
                    },
                    y: {
                        grid: { color: '#f3f4f6' },
                        border: { display: false },
                        beginAtZero: true,
                        ticks: {
                            color: '#9ca3af',
                            precision: 0
                        }
                    }
                }
            }
        });
    }

    function buildBarChart(canvasId, dataset) {
        var ctx = document.getElementById(canvasId);
        if (!ctx) return null;

        return new Chart(ctx, {
            type: 'bar',
            data: {
                labels: dataset.labels,
                datasets: [{
                    data: dataset.values,
                    backgroundColor: '#374151',
                    borderRadius: 4,
                    barPercentage: 0.55,
                    categoryPercentage: 0.7
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                return ctx.parsed.y + ' users';
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        border: { display: false },
                        ticks: { color: '#9ca3af', font: { weight: '500', size: 10 } }
                    },
                    y: {
                        display: false,
                        grid: { display: false },
                        beginAtZero: true
                    }
                }
            },
            plugins: [{
                id: 'barValueLabels',
                afterDatasetsDraw: function (chart) {
                    var meta = chart.getDatasetMeta(0);
                    var cctx = chart.ctx;
                    cctx.save();
                    cctx.font = '600 11px Inter, sans-serif';
                    cctx.fillStyle = '#111827';
                    cctx.textAlign = 'center';
                    meta.data.forEach(function (bar, i) {
                        var val = chart.data.datasets[0].data[i];
                        cctx.fillText(String(val), bar.x, bar.y - 8);
                    });
                    cctx.restore();
                }
            }]
        });
    }

    function buildDoughnutChart(canvasId, dataset) {
        var ctx = document.getElementById(canvasId);
        if (!ctx) return null;

        var colors = ['#1f2937', '#4b5563', '#6b7280', '#9ca3af', '#d1d5db', '#e5e7eb'];

        return new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: dataset.labels,
                datasets: [{
                    data: dataset.values,
                    backgroundColor: dataset.labels.map(function (_, i) {
                        return colors[i % colors.length];
                    }),
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '62%',
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            boxWidth: 12,
                            padding: 14,
                            font: { size: 11, weight: '500' },
                            color: '#6b7280'
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                return ctx.label + ': ' + ctx.parsed + ' users';
                            }
                        }
                    }
                }
            }
        });
    }

    function syncPeriodToggles(period) {
        document.querySelectorAll('.enterprise-period-toggle').forEach(function (toggle) {
            toggle.querySelectorAll('button').forEach(function (btn) {
                btn.classList.toggle('active', btn.getAttribute('data-period') === period);
            });
        });
    }

    function initCharts(period) {
        period = period || defaultPeriod;
        var periodData = data[period] || data[defaultPeriod] || {};

        Object.keys(charts).forEach(function (key) {
            charts[key].destroy();
        });
        charts = {};

        if (periodData.registrations) {
            charts.registrations = buildLineChart('registrationsChart', periodData.registrations);
        }
        if (periodData.usersByRole) {
            charts.usersByRole = buildBarChart('usersByRoleChart', periodData.usersByRole);
        }
        if (periodData.usersByBranch) {
            charts.usersByBranch = buildDoughnutChart('usersByBranchChart', periodData.usersByBranch);
        }
        if (periodData.loginActivity) {
            charts.loginActivity = buildLineChart('loginActivityChart', periodData.loginActivity);
        }

        syncPeriodToggles(period);
    }

    document.querySelectorAll('.enterprise-period-toggle').forEach(function (toggle) {
        toggle.addEventListener('click', function (e) {
            var btn = e.target.closest('button[data-period]');
            if (!btn) return;
            initCharts(btn.getAttribute('data-period'));
        });
    });

    var reloadBtn = document.getElementById('reloadFeedBtn');
    if (reloadBtn) {
        reloadBtn.addEventListener('click', function () {
            window.location.reload();
        });
    }

    if (typeof Chart !== 'undefined') {
        initCharts(defaultPeriod);
    }
})();
