document.addEventListener("DOMContentLoaded", () => {

    const toggle = document.getElementById("exportToggle");
    const items = document.getElementById("exportItems");
    const close = document.getElementById("exportClose");

    if (!toggle || !items) return;

    toggle.addEventListener("click", () => {
        items.classList.toggle("show");

        toggle.innerText = items.classList.contains("show")
            ? "Export ▾"
            : "Export ▸";
    });

    if (close) {
        close.addEventListener("click", () => {
            items.classList.remove("show");
            toggle.innerText = "Export ▸";
        });
    }

});

function openChartSelector() {

    if (typeof charts === "undefined" || Object.keys(charts).length === 0) {
        alert("Charts are still loading. Please try again.");
        return;
    }

    const modal = document.getElementById("chartModal");
    const list = document.getElementById("chartList");

    list.innerHTML = "";

    Object.keys(charts).forEach(id => {
        list.innerHTML += `
            <label style="display:block;margin-bottom:6px;">
                <input type="checkbox" value="${id}" checked>
                ${formatChartName(id)}
            </label>
        `;
    });
    list.innerHTML += `
        <label>
            <input type="checkbox" value="provinceMap" checked>
            Geographic Distribution
        </label>
    `;

    modal.style.display = "block";
}

function closeChartSelector() {
    document.getElementById("chartModal").style.display = "none";
}

function formatChartName(id) {
    const map = {
        trendChart: "Case Trend & Positivity",
        pathogenChart: "Pathogen Distribution",
        provinceMap: "Geographic Distribution",
        ageChart: "Age Distribution",
        sexChart: "Sex Distribution",
        subtypeChart: "Influenza Subtypes",
        sentinelChart: "Sentinel Site Distribution"
    };

    return map[id] || id;
}

async function exportSelectedCharts() {

    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF("p", "mm", "a4");

    const selected = document.querySelectorAll("#chartList input:checked");

    const margin = 10;
    const pageWidth = 210;
    const usableWidth = pageWidth - margin * 2;

    const gap = 5;
    const chartWidth = (usableWidth - gap) / 2;

    let y = 35;

    pdf.setFontSize(18);
    pdf.setFont(undefined, "bold");
    pdf.text(getReportTitle(), margin, 15);

    pdf.setFontSize(10);
    pdf.setFont(undefined, "normal");
    pdf.text(`Generated: ${new Date().toLocaleString()}`, margin, 22);

    pdf.setDrawColor(200);
    pdf.line(margin, 25, pageWidth - margin, 25);

    const items = [];

    for (const cb of selected) {

        if (cb.value === "provinceMap") {
            const mapImg = await getMapImage();

            if (mapImg) {
                items.push({
                    id: "provinceMap",
                    type: "map",
                    img: mapImg
                });
            }

            continue;
        }

        const chart = charts[cb.value];
        if (!chart) continue;

        items.push({
            id: cb.value,
            type: "chart",
            chart
        });
    }

    let i = 0;

    const FIXED_HEIGHT = 70;
    const FIXED_WIDTH = chartWidth;

    while (i < items.length) {

        const left = items[i];
        const right = items[i + 1] || null;

        let leftHeight = FIXED_HEIGHT;
        let rightHeight = 0;

        const xLeft = margin;

        pdf.setFontSize(11);
        pdf.setFont(undefined, "bold");
        pdf.text(formatChartName(left.id), xLeft, y - 3);

        let leftWidth = FIXED_WIDTH;
        let leftImg;

        if (left.type === "map") {
            leftWidth = FIXED_WIDTH;
            leftHeight = 60;
            leftImg = left.img;
        } else {
            leftImg = left.chart.toBase64Image();

            if (["doughnut", "pie"].includes(left.chart.config.type)) {
                const size = Math.min(FIXED_WIDTH, FIXED_HEIGHT);
                leftWidth = size;
                leftHeight = size;
            } else {
                leftHeight = FIXED_HEIGHT;
            }
        }

        const xLeftAdjusted = xLeft + (FIXED_WIDTH - leftWidth) / 2;

        pdf.addImage(
            leftImg,
            "PNG",
            xLeftAdjusted,
            y,
            leftWidth,
            leftHeight
        );

        if (right) {

            const xRight = margin + chartWidth + gap;

            pdf.setFontSize(11);
            pdf.setFont(undefined, "bold");
            pdf.text(formatChartName(right.id), xRight, y - 3);

            let rightWidth = FIXED_WIDTH;
            let rightImg;

            if (right.type === "map") {
                rightWidth = FIXED_WIDTH;
                rightHeight = 60;
                rightImg = right.img;
            } else {
                rightImg = right.chart.toBase64Image();

                if (["doughnut", "pie"].includes(right.chart.config.type)) {
                    const size = Math.min(FIXED_WIDTH, FIXED_HEIGHT);
                    rightWidth = size;
                    rightHeight = size;
                } else {
                    rightHeight = FIXED_HEIGHT;
                }
            }

            const xRightAdjusted = xRight + (FIXED_WIDTH - rightWidth) / 2;

            pdf.addImage(
                rightImg,
                "PNG",
                xRightAdjusted,
                y,
                rightWidth,
                rightHeight
            );

            i += 2;
        } else {
            i += 1;
        }

        // ===== ROW HEIGHT =====
        const rowHeight = Math.max(leftHeight, rightHeight);
        y += rowHeight + 12;

        // ===== PAGE BREAK =====
        if (y > 260) {
            pdf.addPage();
            y = 30;
        }
    }

    pdf.save("dashboard_report.pdf");
    closeChartSelector();
}
function prepareMapForExport() {
    if (!window.map) return;

    const bounds = L.featureGroup(Object.values(map._layers)).getBounds();

    if (bounds.isValid()) {
        map.setView([12.5, 104.9], 6);
    }
}
function exportFullDashboard() {

    const el = document.querySelector(".content-area");

    html2canvas(el, { scale: 2 }).then(canvas => {

        const img = canvas.toDataURL("image/png");

        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF("p", "mm", "a4");

        const width = 210;
        const height = (canvas.height * width) / canvas.width;

        pdf.addImage(img, "PNG", 0, 0, width, height);

        pdf.save("full_dashboard.pdf");

    });

    closeChartSelector();
}
async function getMapImage() {

    const mapEl = document.getElementById("provinceMap");
    if (!mapEl) return null;

    prepareMapForExport();

    // wait for map tiles to re-render
    await new Promise(resolve => setTimeout(resolve, 500));

    const canvas = await html2canvas(mapEl, {
        useCORS: true,
        scale: 2
    });

    return canvas.toDataURL("image/png");
}
function getReportTitle() {
    const program = window.PROGRAM_CODE || "Overview";

    const rangeType = document.getElementById("trend_range")?.value;

    if (rangeType === "custom") {
        const sy = document.getElementById("start_year")?.value;
        const sw = document.getElementById("start_week")?.value;
        const ey = document.getElementById("end_year")?.value;
        const ew = document.getElementById("end_week")?.value;

        return `${program} Report (W${sw}/${sy} – W${ew}/${ey})`;
    }

    return `${program} Report (Last ${rangeType} weeks)`;
}