(function () {
    'use strict';

    // COUNTY_ID_MAP defined ONCE here — not inside any loop
    const COUNTY_ID_MAP = {
        "Baringo": "KE-01", "Bomet": "KE-02", "Bungoma": "KE-03", "Busia": "KE-04",
        "Elgeyo/Marakwet": "KE-05", "Embu": "KE-06", "Garissa": "KE-07", "Homa Bay": "KE-08",
        "Isiolo": "KE-09", "Kajiado": "KE-10", "Kakamega": "KE-11", "Kericho": "KE-12",
        "Kiambu": "KE-13", "Kilifi": "KE-14", "Kirinyaga": "KE-15", "Kisii": "KE-16",
        "Kisumu": "KE-17", "Kitui": "KE-18", "Kwale": "KE-19", "Laikipia": "KE-20",
        "Lamu": "KE-21", "Machakos": "KE-22", "Makueni": "KE-23", "Mandera": "KE-24",
        "Marsabit": "KE-25", "Meru": "KE-26", "Migori": "KE-27", "Mombasa": "KE-28",
        "Murang'a": "KE-29", "Nairobi": "KE-30", "Nakuru": "KE-31", "Nandi": "KE-32",
        "Narok": "KE-33", "Nyamira": "KE-34", "Nyandarua": "KE-35", "Nyeri": "KE-36",
        "Samburu": "KE-37", "Siaya": "KE-38", "Taita/Taveta": "KE-39", "Tana River": "KE-40",
        "Tharaka-Nithi": "KE-41", "Trans Nzoia": "KE-42", "Turkana": "KE-43", "Uasin Gishu": "KE-44",
        "Vihiga": "KE-45", "Wajir": "KE-46", "West Pokot": "KE-47"
    };

    // Reverse map for safe click resolution (FIX Point 10)
    const ID_COUNTY_MAP = Object.fromEntries(
        Object.entries(COUNTY_ID_MAP).map(([name, id]) => [id, name])
    );

    function initMap(config) {
        const countyData = config.countyData || {};

        // FIX Point 15: hoist max OUTSIDE the loop
        const maxCount = Math.max(...Object.values(countyData), 1);

        am4core.ready(function () {
            am4core.useTheme(am4themes_animated);
            var chart = am4core.create(config.containerId, am4maps.MapChart);
            chart.geodata = am4geodata_kenyaLow;
            chart.projection = new am4maps.projections.Mercator();

            // Zoom Control
            chart.zoomControl = new am4maps.ZoomControl();
            chart.zoomControl.slider.height = 100;

            // Ensure chart doesn't trap scroll entirely unless zoomed
            chart.chartContainer.wheelable = "none";

            var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());
            polygonSeries.useGeodata = true;

            // Configure tooltip
            polygonSeries.tooltip.background.fill = am4core.color("rgba(10,30,60,0.95)");
            polygonSeries.tooltip.background.stroke = am4core.color("rgba(0,180,180,0.5)");
            polygonSeries.tooltip.background.strokeWidth = 1;
            polygonSeries.tooltip.background.cornerRadius = 8;
            polygonSeries.tooltip.getFillFromObject = false;
            polygonSeries.tooltip.label.fill = am4core.color("#ffffff");
            polygonSeries.tooltip.label.textAlign = "middle";
            polygonSeries.tooltip.label.padding(10, 15, 10, 15);

            var polygonTemplate = polygonSeries.mapPolygons.template;
            polygonTemplate.tooltipHTML = `
        <div style="text-align:center;">
          <div style="font-weight:bold;font-size:14px;color:#cbd5e1;margin-bottom:4px;">{name}</div>
          <div style="font-size:24px;font-weight:900;color:#00e5ff;margin-bottom:2px;">{value}</div>
          <div style="font-size:11px;color:#94a3b8;border-top:1px solid rgba(255,255,255,0.1);padding-top:4px;">Submissions</div>
        </div>
      `;
            polygonTemplate.fill = am4core.color("rgba(255,255,255,0.06)");
            polygonTemplate.stroke = am4core.color("rgba(255,255,255,0.2)");
            polygonTemplate.strokeWidth = 1.2;
            polygonTemplate.cursorOverStyle = am4core.MouseCursorStyle.pointer;

            var hs = polygonTemplate.states.create("hover");
            hs.properties.fill = am4core.color("rgba(0, 229, 255, 0.4)");
            hs.properties.stroke = am4core.color("rgba(0, 229, 255, 0.8)");
            hs.properties.strokeWidth = 2;

            // FIX Point 15: use .map() — no re-declarations in loop
            const mapData = Object.keys(countyData).map(name => {
                const cnt = countyData[name] || 0;
                const intensity = cnt > 0 ? Math.max(0.25, cnt / maxCount) : 0.06;
                return {
                    name,
                    id: COUNTY_ID_MAP[name] || "",
                    value: cnt,
                    fill: am4core.color(cnt > 0 ? `rgba(212,175,55,${intensity})` : 'rgba(255,255,255,0.06)')
                };
            });
            polygonSeries.data = mapData;
            polygonTemplate.propertyFields.fill = "fill";

            // FIX Point 10: resolve name robustly on click
            polygonTemplate.events.on('hit', function (ev) {
                const ctx = ev.target.dataItem.dataContext;
                // fallback to reverse map lookup if geodata differs
                const countyName = ctx.name || ID_COUNTY_MAP[ctx.id] || "";
                if (!countyName) return;

                if (config.clickUrlBase) {
                    const url = new URL(config.clickUrlBase, window.location.origin);
                    url.searchParams.set('county', countyName);
                    if (config.hash) url.hash = config.hash;
                    window.location.href = url.toString();
                } else {
                    const url = new URL(window.location.href);
                    url.searchParams.set('county', countyName);
                    if (config.hash || url.hash) url.hash = config.hash || 'submissions';
                    window.location.href = url.toString();
                }
            });
        });
    }

    function initCharts(config) {
        if (!window.Chart) return;

        Chart.defaults.color = '#94a3b8';
        Chart.defaults.borderColor = 'rgba(255,255,255,0.08)';
        Chart.defaults.font.family = "'Inter', sans-serif";

        // 1. Trend Chart
        if (config.trend && document.getElementById(config.trend.id)) {
            new Chart(document.getElementById(config.trend.id), {
                type: 'line',
                data: {
                    labels: config.trend.labels,
                    datasets: [{
                        label: 'Submissions',
                        data: config.trend.values,
                        borderColor: '#008080',
                        backgroundColor: 'rgba(0,128,128,0.15)',
                        fill: true,
                        tension: 0.4,
                        pointRadius: 4,
                        pointBackgroundColor: '#008080',
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: config.maintainAspectRatio !== undefined ? config.maintainAspectRatio : true,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: { beginAtZero: true, ticks: { stepSize: 1 } },
                        x: { grid: { display: false } }
                    }
                }
            });
        }

        // 2. Sector Donut
        if (config.sector && document.getElementById(config.sector.id)) {
            const chartCanvas = document.getElementById(config.sector.id);
            const secChart = new Chart(chartCanvas, {
                type: 'doughnut',
                data: {
                    labels: config.sector.labels,
                    datasets: [{
                        data: config.sector.values,
                        backgroundColor: ['#008080', '#E2725B', '#CC7722', '#D4AF37', '#2E8B57', '#6366F1', '#EC4899', '#F59E0B', '#14B8A6', '#8B5CF6'],
                        borderWidth: 2,
                        borderColor: 'rgba(0,31,63,0.8)',
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: config.maintainAspectRatio !== undefined ? config.maintainAspectRatio : true,
                    plugins: {
                        legend: { position: 'bottom', labels: { boxWidth: 10, padding: 6, font: { size: 10 }, color: '#cbd5e1' } }
                    },
                    onClick: (e, activeEls, chart) => {
                        if (activeEls.length > 0) {
                            const index = activeEls[0].index;
                            const sectorLabel = chart.data.labels[index];
                            let url;
                            if (config.clickUrlBase) {
                                url = new URL(config.clickUrlBase, window.location.origin);
                            } else {
                                url = new URL(window.location.href);
                            }
                            url.searchParams.set('sector', sectorLabel);
                            if (config.hash) url.hash = config.hash;
                            window.location.href = url.toString();
                        }
                    },
                    onHover: (e, activeEls) => {
                        e.native.target.style.cursor = activeEls.length > 0 ? 'pointer' : 'default';
                    }
                }
            });
        }

        // 3. Rating Chart
        if (config.rating && document.getElementById(config.rating.id)) {
            new Chart(document.getElementById(config.rating.id), {
                type: 'bar',
                data: {
                    labels: ['1\u2605', '2\u2605', '3\u2605', '4\u2605', '5\u2605'],
                    datasets: [{
                        label: 'Submissions',
                        data: config.rating.values,
                        backgroundColor: ['#EF4444', '#F97316', '#EAB308', '#22C55E', '#008080'],
                        borderRadius: 6,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: config.maintainAspectRatio !== undefined ? config.maintainAspectRatio : true,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: { beginAtZero: true, ticks: { stepSize: 1 } },
                        x: { grid: { display: false } }
                    },
                    onClick: (e, activeEls, chart) => {
                        if (activeEls.length > 0) {
                            const index = activeEls[0].index;
                            const rating = index + 1;
                            let url;
                            if (config.clickUrlBase) {
                                url = new URL(config.clickUrlBase, window.location.origin);
                            } else {
                                url = new URL(window.location.href);
                            }
                            url.searchParams.set('rating', rating);
                            if (config.hash) url.hash = config.hash;
                            window.location.href = url.toString();
                        }
                    },
                    onHover: (e, activeEls) => {
                        e.native.target.style.cursor = activeEls.length > 0 ? 'pointer' : 'default';
                    }
                }
            });
        }

        // 4. Category Chart
        if (config.category && document.getElementById(config.category.id)) {
            new Chart(document.getElementById(config.category.id), {
                type: 'bar',
                data: {
                    labels: config.category.labels,
                    datasets: [{
                        label: 'Submissions',
                        data: config.category.values,
                        backgroundColor: '#D4AF37',
                        borderRadius: 4,
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: config.maintainAspectRatio !== undefined ? config.maintainAspectRatio : true,
                    plugins: { legend: { display: false } },
                    scales: {
                        x: { beginAtZero: true, ticks: { stepSize: 1 }, grid: { display: false } },
                        y: { ticks: { font: { size: 10 }, color: '#cbd5e1' } }
                    },
                    onClick: (e, activeEls, chart) => {
                        if (activeEls.length > 0) {
                            const index = activeEls[0].index;
                            const catId = config.category.ids[index];
                            let url;
                            if (config.clickUrlBase) {
                                url = new URL(config.clickUrlBase, window.location.origin);
                            } else {
                                url = new URL(window.location.href);
                            }
                            url.searchParams.set('subcategory', catId);
                            if (config.hash) url.hash = config.hash;
                            window.location.href = url.toString();
                        }
                    },
                    onHover: (e, activeEls) => {
                        e.native.target.style.cursor = activeEls.length > 0 ? 'pointer' : 'default';
                    }
                }
            });
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        if (window.SaniMapConfig) initMap(window.SaniMapConfig);
        if (window.SaniChartConfig) initCharts(window.SaniChartConfig);
    });
})();
