<script type="text/javascript">
(function () {
    "use strict";

    var payload = @json($dashboardPayload ?? []);

    function ready(fn){ if (document.readyState !== 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } }
    function el(id){ return document.getElementById(id); }
    function hasRows(rows){ return Array.isArray(rows) && rows.length > 0; }
    function fallback(id, message){ if (el(id)) { el(id).innerHTML = '<div class="ngbvd-chart-empty" style="padding:40px;text-align:center;color:#64748b;font-weight:700;">'+message+'</div>'; } }

    ready(function () {
        if (!window.Highcharts) {
            ['top_districts','national_status','regions','column-chart','column-chart-agegroups','line-example','donut-example'].forEach(function(id){ fallback(id, 'Highcharts did not load. Please check the Highcharts script path.'); });
            return;
        }

        renderTopDistricts();
        renderNationalStatus();
        renderRegionGender();
        renderIncidentGender();
        renderAgeGender();
        renderTrendChart();
        renderIncidentDonut();

        setTimeout(function(){ if (Highcharts.charts) { Highcharts.charts.forEach(function(c){ if(c){ c.reflow(); } }); } }, 500);
    });

    function renderTopDistricts(){
        if (!el('top_districts')) { return; }
        var d = payload.districts || {series: [], drilldown: []};
        if (!hasRows(d.series)) { return fallback('top_districts', 'No district records available for your assigned data scope.'); }

        Highcharts.chart('top_districts', {
            chart: { type: 'column' },
            title: { align: 'left', text: 'Districts with the Highest Incident Rates' },
            subtitle: { align: 'left', text: '' },
            accessibility: { announceNewData: { enabled: true } },
            xAxis: { type: 'category' },
            yAxis: { title: { text: 'Total Number of Incidents' } },
            legend: { enabled: false },
            plotOptions: { series: { borderWidth: 0, dataLabels: { enabled: true, format: '{point.y:.1f}' } } },
            tooltip: { headerFormat: '<span style="font-size:11px">{series.name}</span><br>', pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b><br/>' },
            series: [{ name: 'Districts', colorByPoint: true, data: d.series }],
            drilldown: { breadcrumbs: { position: { align: 'right' } }, series: d.drilldown || [] }
        });
    }

    function renderNationalStatus(){
        if (!el('national_status')) { return; }
        var ns = payload.nationalStatus || {series: [], drilldown: []};
        if (!hasRows(ns.series)) { return fallback('national_status', 'No national-status records available for your assigned data scope.'); }

        Highcharts.chart('national_status', {
            chart: { type: 'pie' },
            title: { text: 'Incidents Statistics by National Status', align: 'left' },
            subtitle: { text: '', align: 'left' },
            accessibility: { announceNewData: { enabled: true }, point: { valueSuffix: '%' } },
            plotOptions: { series: { borderRadius: 5, dataLabels: { enabled: true, format: '{point.name}: {point.y:.1f}' } } },
            tooltip: { headerFormat: '<span style="font-size:11px">{series.name}</span><br>', pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>' },
            series: [{ name: 'National Status', colorByPoint: true, data: ns.series }],
            drilldown: { series: ns.drilldown || [] }
        });
    }

    function renderRegionGender(){
        if (!el('regions')) { return; }
        var rg = payload.regionGender || {categories: [], series: []};
        if (!hasRows(rg.series)) { return fallback('regions', 'No regional gender records available for your assigned data scope.'); }

        Highcharts.chart('regions', {
            title: { text: 'Incidents per Region vs Gender', align: 'left' },
            xAxis: { categories: rg.categories || [] },
            yAxis: { title: { text: 'Incidents' } },
            tooltip: { valueSuffix: ' incidents' },
            plotOptions: { series: { borderRadius: '25%' } },
            series: rg.series || []
        });
    }

    function renderIncidentGender(){
        if (!el('column-chart')) { return; }
        var ig = payload.incidentGender || {categories: [], series: []};
        if (!hasRows(ig.series)) { return fallback('column-chart', 'No incident gender records available for your assigned data scope.'); }

        Highcharts.chart('column-chart', {
            chart: { type: 'column' },
            title: { text: 'Incidents By Gender' },
            subtitle: { text: 'Number of Incidents disagregated by gender' },
            xAxis: { categories: ig.categories || [], crosshair: true },
            yAxis: { min: 0, title: { text: 'Incidents' } },
            tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td><td style="padding:0"><b>{point.y:.1f}</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true },
            plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } },
            series: ig.series || []
        });
    }

    function renderAgeGender(){
        if (!el('column-chart-agegroups')) { return; }
        var ag = payload.ageGender || {categories: [], series: []};
        if (!hasRows(ag.series)) { return fallback('column-chart-agegroups', 'No age-group records available for your assigned data scope.'); }

        Highcharts.chart('column-chart-agegroups', {
            chart: { type: 'column' },
            title: { text: 'Incidents By Age Group' },
            subtitle: { text: 'Number of Incidents disagregated by agegroup' },
            xAxis: { categories: ag.categories || [], crosshair: true },
            yAxis: { min: 0, title: { text: 'Incidents' } },
            tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td><td style="padding:0"><b>{point.y:.1f}</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true },
            plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } },
            series: ag.series || []
        });
    }

    function renderTrendChart(){
        if (!el('line-example')) { return; }
        var tr = payload.trends || {categories: [], series: []};
        if (!hasRows(tr.series)) { return fallback('line-example', 'No trend records available for your assigned data scope.'); }

        Highcharts.chart('line-example', {
            chart: { type: 'spline', height: 360 },
            title: { text: 'Trends of Incidents across the Years', align: 'left' },
            xAxis: { categories: tr.categories || [] },
            yAxis: { title: { text: 'Incidents' } },
            tooltip: { shared: true },
            credits: { enabled: true },
            plotOptions: { spline: { marker: { enabled: true, radius: 4 }, lineWidth: 3 } },
            series: tr.series || []
        });
    }

    function renderIncidentDonut(){
        if (!el('donut-example')) { return; }
        var rows = payload.categories || [];
        if (!hasRows(rows)) { return fallback('donut-example', 'No incident category records available for your assigned data scope.'); }

        Highcharts.chart('donut-example', {
            chart: { type: 'pie', height: 360 },
            title: { text: 'Total number of Incidents separated by Incident Category', align: 'left' },
            tooltip: { pointFormat: '<b>{point.y:,.0f}</b> incidents ({point.percentage:.1f}%)' },
            plotOptions: { pie: { innerSize: '55%', allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: false }, showInLegend: true } },
            legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', itemStyle: { fontSize: '11px' } },
            series: [{ name: 'Incidents', colorByPoint: true, data: rows }]
        });
    }
})();
</script>
