import ApexCharts from 'apexcharts';

export default function init() {
    const d = window.DASHBOARD_DATA || {
        labels: [], sent: [], delivered: [], failed: [], spark: [], readRate: 0,
    };

    // ===== KPI 1 sparkline =====
    const spark = document.querySelector("#kpi-spark");
    if (spark) {
        new ApexCharts(spark, {
            chart: { type: "bar", height: 32, sparkline: { enabled: true }, animations: { enabled: true, speed: 600 } },
            series: [{ name: "Sent/hr", data: d.spark.length ? d.spark : [0] }],
            plotOptions: { bar: {
                columnWidth: "60%", borderRadius: 2, distributed: true,
                colors: { ranges: [
                    { from: 0,  to: 9,    color: "#128C7E" },
                    { from: 10, to: 9999, color: "#25D366" },
                ] },
            } },
            dataLabels: { enabled: false },
            tooltip: { enabled: true, x: { show: false }, y: { formatter: (v) => v.toLocaleString() + " msg/h" } },
            states: { hover: { filter: { type: "darken", value: 0.92 } } },
        }).render();
    }

    // ===== KPI 2 read-rate radial donut =====
    const radial = document.querySelector("#kpi-readrate");
    if (radial) {
        new ApexCharts(radial, {
            chart: { type: "radialBar", height: 64, width: 64, sparkline: { enabled: true } },
            colors: ["#075E54"],
            series: [Number(d.readRate || 0)],
            plotOptions: { radialBar: {
                hollow: { size: "58%" },
                track:  { background: "rgba(11,31,28,0.06)", strokeWidth: "100%" },
                dataLabels: {
                    name: { show: false },
                    value: { show: true, fontSize: "10px", fontFamily: "JetBrains Mono, monospace", fontWeight: 600, color: "#075E54", offsetY: 4, formatter: (v) => Number(v).toFixed(1) },
                },
            } },
            stroke: { lineCap: "round" },
        }).render();
    }

    // ===== Message throughput — grouped bars with a working range filter =====
    const tp = document.querySelector("#chart-throughput");
    if (tp) {
        // Range datasets from the controller. Fall back to the legacy 7d
        // top-level fields so the chart still works if ranges are absent.
        const ranges = d.throughputRanges || {};
        const fallback7d = { labels: d.labels || [], sent: d.sent || [], delivered: d.delivered || [], failed: d.failed || [] };
        const getRange = (key) => ranges[key] || (key === "7d" ? fallback7d : { labels: [], sent: [], delivered: [], failed: [] });

        const subtitles = {
            "24h": "Outbound, delivered & failed events — hourly, last 24h.",
            "7d":  "Outbound, delivered & failed events — daily, last 7 days.",
            "30d": "Outbound, delivered & failed events — daily, last 30 days.",
            "qtd": "Outbound, delivered & failed events — daily, quarter to date.",
        };

        const initial = getRange("7d");
        const throughputChart = new ApexCharts(tp, {
            chart: { type: "bar", height: 220, fontFamily: "Inter, system-ui, sans-serif", toolbar: { show: false }, animations: { enabled: true, speed: 500 } },
            colors: ["#075E54", "#25D366", "#E87A5D"],
            series: [
                { name: "Sent",      data: initial.sent },
                { name: "Delivered", data: initial.delivered },
                { name: "Failed",    data: initial.failed },
            ],
            plotOptions: { bar: { columnWidth: "55%", borderRadius: 3 } },
            dataLabels: { enabled: false },
            grid: { borderColor: "#E5DFD0", strokeDashArray: 3 },
            xaxis: {
                categories: initial.labels,
                labels: { rotate: -45, rotateAlways: false, hideOverlappingLabels: true, trim: false, style: { fontFamily: "JetBrains Mono, monospace", fontSize: "10px", colors: "#6B807C" } },
                tickPlacement: "on",
                axisBorder: { show: false }, axisTicks: { show: false },
            },
            yaxis: {
                labels: {
                    formatter: (v) => v >= 1000 ? (v/1000).toFixed(0) + "k" : v,
                    style: { fontFamily: "JetBrains Mono, monospace", fontSize: "10px", colors: "#6B807C" },
                },
            },
            legend: { show: false },
            tooltip: { shared: true, intersect: false, y: { formatter: (v) => v.toLocaleString() + " msg" } },
        });
        throughputChart.render();
        // The dashboard cards play an entrance animation; ApexCharts can
        // measure a transformed (narrower) width at render time and cluster the
        // x-axis labels at the left. Force a re-measure once the layout settles.
        setTimeout(() => { try { window.dispatchEvent(new Event("resize")); } catch (e) {} }, 300);

        // Range buttons inside the chart card.
        const cardRangeButtons = document.querySelectorAll("[data-range]");
        const subtitleEl = document.querySelector("#throughput-subtitle");
        const setActive = (btn) => {
            cardRangeButtons.forEach((b) => {
                b.classList.remove("bg-ink-900", "text-paper-0");
                b.classList.add("text-ink-600");
            });
            if (btn) {
                btn.classList.remove("text-ink-600");
                btn.classList.add("bg-ink-900", "text-paper-0");
            }
        };

        // Shared range switcher — used by both the in-card toggle and the
        // header "Last 7 days ▾" dropdown so they stay in sync.
        const rangeLabels = { "24h": "Last 24 hours", "7d": "Last 7 days", "30d": "Last 30 days", "qtd": "Quarter to date" };
        const headerRangeLabel = document.querySelector("#dash-range-label");
        function applyRange(key) {
            const r = getRange(key);
            setActive(document.querySelector(`[data-range="${key}"]`));
            if (subtitleEl && subtitles[key]) subtitleEl.textContent = subtitles[key];
            if (headerRangeLabel && rangeLabels[key]) headerRangeLabel.textContent = rangeLabels[key];
            throughputChart.updateOptions({ xaxis: { categories: r.labels } }, false, false);
            throughputChart.updateSeries([
                { name: "Sent",      data: r.sent },
                { name: "Delivered", data: r.delivered },
                { name: "Failed",    data: r.failed },
            ], true);
        }

        cardRangeButtons.forEach((btn) => {
            btn.addEventListener("click", () => applyRange(btn.getAttribute("data-range")));
        });

        // Header date-range dropdown.
        const rangeBtn  = document.querySelector("#dash-range-btn");
        const rangeMenu = document.querySelector("#dash-range-menu");
        if (rangeBtn && rangeMenu) {
            rangeBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                rangeMenu.classList.toggle("hidden");
            });
            rangeMenu.querySelectorAll(".dash-range-opt").forEach((opt) => {
                opt.addEventListener("click", () => {
                    applyRange(opt.getAttribute("data-range"));
                    rangeMenu.classList.add("hidden");
                });
            });
            document.addEventListener("click", (e) => {
                if (!rangeMenu.contains(e.target) && e.target !== rangeBtn) rangeMenu.classList.add("hidden");
            });
        }
    }

    // ===== Export — download the throughput series as a CSV =====
    const exportBtn = document.querySelector("#dash-export");
    if (exportBtn) {
        exportBtn.addEventListener("click", () => {
            const labels = d.labels || [];
            const sent = d.sent || [], delivered = d.delivered || [], failed = d.failed || [];
            const rows = [["date", "sent", "delivered", "failed"]];
            for (let i = 0; i < labels.length; i++) {
                rows.push([labels[i], sent[i] ?? 0, delivered[i] ?? 0, failed[i] ?? 0]);
            }
            const csv = rows
                .map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(","))
                .join("\n");
            const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = `dashboard-throughput-${new Date().toISOString().slice(0, 10)}.csv`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            if (typeof window.toast === "function") window.toast("Exported throughput CSV.", "success");
        });
    }
}
