(function () {
    const fromInput = document.getElementById("summaryFromDate");
    const toInput = document.getElementById("summaryToDate");
    const loadBtn = document.getElementById("loadSummaryBtn");
    const resetBtn = document.getElementById("resetSummaryBtn");
    const exportBtn = document.getElementById("exportSummaryBtn");
    const cards = document.getElementById("summaryCards");
    const insightGrid = document.getElementById("summaryInsightGrid");
    const signalList = document.getElementById("summarySignalList");
    const tableBody = document.querySelector("#summaryTable tbody");
    const rangeLabel = document.getElementById("salesSummaryRangeLabel");
    const dailyTrendLabel = document.getElementById("dailyTrendLabel");
    const peakDayLabel = document.getElementById("peakDayLabel");
    const presetHost = document.getElementById("summaryPresetButtons");
    const trendCanvas = document.getElementById("summaryTrendChart");
    const mixCanvas = document.getElementById("summaryMixChart");
    const volumeCanvas = document.getElementById("summaryVolumeChart");
    const taxCanvas = document.getElementById("summaryTaxChart");
    let latestRows = [];
    let latestData = null;
    let trendChart;
    let mixChart;
    let volumeChart;
    let taxChart;

    if (!fromInput || !toInput || !loadBtn || !cards || !tableBody || !presetHost || !insightGrid || !signalList) {
        return;
    }

    applyPreset("30");
    bindEvents();
    load();

    function bindEvents() {
        loadBtn.addEventListener("click", load);
        resetBtn?.addEventListener("click", function () {
            applyPreset("30");
            setActivePreset("30");
            load();
        });
        exportBtn?.addEventListener("click", exportCsv);

        presetHost.addEventListener("click", function (event) {
            const button = event.target.closest("button[data-range]");
            if (!button) {
                return;
            }

            const range = button.getAttribute("data-range");
            applyPreset(range);
            setActivePreset(range);
            load();
        });
    }

    function load() {
        loadBtn.disabled = true;
        fetch("/api/sales/summary?fromDate=" + encodeURIComponent(fromInput.value) + "&toDate=" + encodeURIComponent(toInput.value))
            .then(handleJson)
            .then(function (data) {
                latestData = data;
                latestRows = [
                    { label: "Selected Range", data: data.customRange },
                    { label: "MTD", data: data.mtd },
                    { label: "YTD", data: data.ytd }
                ];

                renderCards(data);
                renderTable();
                renderInsights(data);
                renderSignals(data);
                renderTrend(data.dailyTrend || []);
                renderMixChart(data);
                renderVolumeChart(data);
                renderTaxChart(data);

                if (rangeLabel) {
                    rangeLabel.textContent = date(data.fromDate) + " to " + date(data.toDate);
                }
                if (dailyTrendLabel) {
                    dailyTrendLabel.textContent = number((data.dailyTrend || []).length) + " points loaded";
                }
                if (peakDayLabel) {
                    const strongestDay = getPeakDay(data.dailyTrend || []);
                    peakDayLabel.textContent = strongestDay.label === "No trend data"
                        ? strongestDay.label
                        : strongestDay.label + " • " + money(strongestDay.value);
                }
            })
            .finally(function () {
                loadBtn.disabled = false;
            });
    }

    function renderCards(data) {
        const selectedAverage = averageOrderValue(data.customRange);
        const mtdAverage = averageOrderValue(data.mtd);
        const valueShare = data.ytd.orderValue ? ((data.customRange.orderValue / data.ytd.orderValue) * 100) : 0;

        cards.innerHTML = [
            metric("Selected Sales", money(data.customRange.orderValue), "info", number(data.customRange.orderCount) + " orders"),
            metric("Selected Qty", qty(data.customRange.quantity), "success", "Billed quantity"),
            metric("MTD Sales", money(data.mtd.orderValue), "warning", number(data.mtd.orderCount) + " MTD orders"),
            metric("YTD Sales", money(data.ytd.orderValue), "danger", number(data.ytd.orderCount) + " YTD orders"),
            metric("Avg Order Value", money(selectedAverage), "indigo", "Selected range"),
            metric("Range Share", percent(valueShare), "slate", "Of YTD value")
        ].join("");
    }

    function renderTable() {
        tableBody.innerHTML = latestRows.map(function (row) {
            const average = averageOrderValue(row.data);
            const taxPercentValue = taxPercent(row.data);

            return "<tr>" +
                "<td>" + esc(row.label) + "</td>" +
                '<td class="text-end">' + number(row.data.orderCount) + "</td>" +
                '<td class="text-end">' + money(row.data.orderValue) + "</td>" +
                '<td class="text-end">' + money(row.data.taxValue) + "</td>" +
                '<td class="text-end">' + qty(row.data.quantity) + "</td>" +
                '<td class="text-end">' + money(average) + "</td>" +
                '<td class="text-end">' + percent(taxPercentValue) + "</td>" +
                "</tr>";
        }).join("");
    }

    function renderInsights(data) {
        const selectedAverage = averageOrderValue(data.customRange);
        const mtdAverage = averageOrderValue(data.mtd);
        const ytdAverage = averageOrderValue(data.ytd);
        const selectedTaxRatio = taxPercent(data.customRange);

        const items = [
            { title: "Selected avg order", value: money(selectedAverage), note: "Per invoice in chosen range" },
            { title: "MTD avg order", value: money(mtdAverage), note: "Month to date order size" },
            { title: "YTD avg order", value: money(ytdAverage), note: "Year to date order size" },
            { title: "Selected tax ratio", value: percent(selectedTaxRatio), note: "Tax share in selected billing" }
        ];

        insightGrid.innerHTML = items.map(function (item) {
            return '<article class="summary-insight-card">' +
                "<span>" + esc(item.title) + "</span>" +
                "<strong>" + esc(item.value) + "</strong>" +
                "<p>" + esc(item.note) + "</p>" +
                "</article>";
        }).join("");
    }

    function renderSignals(data) {
        const selectedAverage = averageOrderValue(data.customRange);
        const mtdAverage = averageOrderValue(data.mtd);
        const orderDelta = data.mtd.orderCount ? ((data.customRange.orderCount / data.mtd.orderCount) * 100) : 0;
        const qtyDelta = data.mtd.quantity ? ((data.customRange.quantity / data.mtd.quantity) * 100) : 0;
        const strongestDay = getPeakDay(data.dailyTrend || []);

        const items = [
            {
                label: "Order intensity",
                value: percent(orderDelta),
                note: "Selected order count compared with MTD orders"
            },
            {
                label: "Quantity intensity",
                value: percent(qtyDelta),
                note: "Selected billed quantity compared with MTD quantity"
            },
            {
                label: "Average ticket gap",
                value: money(selectedAverage - mtdAverage),
                note: "Selected average order minus MTD average order"
            },
            {
                label: "Peak day",
                value: strongestDay.label,
                note: strongestDay.label === "No trend data" ? "No daily points available" : (money(strongestDay.value) + " billed on peak day")
            }
        ];

        signalList.innerHTML = items.map(function (item) {
            return '<article class="summary-signal-item">' +
                "<div><span>" + esc(item.label) + "</span><p>" + esc(item.note) + "</p></div>" +
                "<strong>" + esc(item.value) + "</strong>" +
                "</article>";
        }).join("");
    }

    function renderTrend(points) {
        if (!trendCanvas || typeof Chart === "undefined") {
            return;
        }

        if (trendChart) {
            trendChart.destroy();
        }

        trendChart = new Chart(trendCanvas, {
            type: "line",
            data: {
                labels: points.map(function (point) { return point.label; }),
                datasets: [{
                    label: "Daily Sales",
                    data: points.map(function (point) { return point.value; }),
                    borderColor: "#0d6efd",
                    backgroundColor: "rgba(13,110,253,0.10)",
                    fill: true,
                    tension: 0.34,
                    pointRadius: 2.5,
                    pointHoverRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: "#6b8096", font: { size: 10 } }
                    },
                    y: {
                        grid: { color: "rgba(16,32,51,0.06)" },
                        ticks: {
                            color: "#6b8096",
                            font: { size: 10 },
                            callback: function (value) { return "Rs " + compact(value); }
                        }
                    }
                }
            }
        });
    }

    function renderMixChart(data) {
        if (!mixCanvas || typeof Chart === "undefined") {
            return;
        }

        if (mixChart) {
            mixChart.destroy();
        }

        mixChart = new Chart(mixCanvas, {
            type: "bar",
            data: {
                labels: ["Selected", "MTD", "YTD"],
                datasets: [{
                    label: "Sales Value",
                    data: [data.customRange.orderValue, data.mtd.orderValue, data.ytd.orderValue],
                    backgroundColor: ["#2c8fbf", "#1f9d68", "#0d6efd"],
                    borderRadius: 10
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: "#6b8096", font: { size: 10 } }
                    },
                    y: {
                        grid: { color: "rgba(16,32,51,0.06)" },
                        ticks: {
                            color: "#6b8096",
                            font: { size: 10 },
                            callback: function (value) { return "Rs " + compact(value); }
                        }
                    }
                }
            }
        });
    }

    function renderVolumeChart(data) {
        if (!volumeCanvas || typeof Chart === "undefined") {
            return;
        }

        if (volumeChart) {
            volumeChart.destroy();
        }

        volumeChart = new Chart(volumeCanvas, {
            data: {
                labels: ["Selected", "MTD", "YTD"],
                datasets: [{
                    type: "bar",
                    label: "Quantity",
                    data: [data.customRange.quantity, data.mtd.quantity, data.ytd.quantity],
                    backgroundColor: ["rgba(31,157,104,0.78)", "rgba(44,143,191,0.74)", "rgba(13,110,253,0.78)"],
                    borderRadius: 10,
                    yAxisID: "y"
                }, {
                    type: "line",
                    label: "Orders",
                    data: [data.customRange.orderCount, data.mtd.orderCount, data.ytd.orderCount],
                    borderColor: "#ff7a59",
                    backgroundColor: "#ff7a59",
                    tension: 0.3,
                    pointRadius: 3,
                    yAxisID: "y1"
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        labels: { boxWidth: 10, color: "#556b84", font: { size: 10 } }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: "#6b8096", font: { size: 10 } }
                    },
                    y: {
                        grid: { color: "rgba(16,32,51,0.06)" },
                        ticks: { color: "#6b8096", font: { size: 10 } }
                    },
                    y1: {
                        position: "right",
                        grid: { display: false },
                        ticks: { color: "#6b8096", font: { size: 10 } }
                    }
                }
            }
        });
    }

    function renderTaxChart(data) {
        if (!taxCanvas || typeof Chart === "undefined") {
            return;
        }

        if (taxChart) {
            taxChart.destroy();
        }

        taxChart = new Chart(taxCanvas, {
            type: "doughnut",
            data: {
                labels: ["Selected Tax", "MTD Tax", "YTD Tax"],
                datasets: [{
                    data: [data.customRange.taxValue, data.mtd.taxValue, data.ytd.taxValue],
                    backgroundColor: ["#ff7a59", "#f0ad4e", "#5f6cf4"],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: "bottom",
                        labels: { boxWidth: 10, color: "#556b84", font: { size: 10 } }
                    }
                },
                cutout: "68%"
            }
        });
    }

    function exportCsv() {
        if (!latestData) {
            return;
        }

        const rows = [
            ["Range", "Orders", "Value", "Tax", "Qty", "AvgOrder", "TaxPercent"],
            ["Selected Range", latestData.customRange.orderCount, latestData.customRange.orderValue, latestData.customRange.taxValue, latestData.customRange.quantity, averageOrderValue(latestData.customRange), taxPercent(latestData.customRange)],
            ["MTD", latestData.mtd.orderCount, latestData.mtd.orderValue, latestData.mtd.taxValue, latestData.mtd.quantity, averageOrderValue(latestData.mtd), taxPercent(latestData.mtd)],
            ["YTD", latestData.ytd.orderCount, latestData.ytd.orderValue, latestData.ytd.taxValue, latestData.ytd.quantity, averageOrderValue(latestData.ytd), taxPercent(latestData.ytd)]
        ];
        download("sales-summary.csv", rows.map(function (row) { return row.join(","); }).join("\n"));
    }

    function metric(title, value, tone, note) {
        return '<article class="metric-card">' +
            '<span class="tone ' + esc(tone) + '">' + esc(note) + "</span>" +
            "<h3>" + esc(value) + "</h3>" +
            "<p>" + esc(title) + "</p>" +
            "</article>";
    }

    function applyPreset(range) {
        const today = new Date();
        let from = new Date(today);
        let to = new Date(today);

        if (range === "7") {
            from.setDate(to.getDate() - 6);
        } else if (range === "month") {
            from = new Date(today.getFullYear(), today.getMonth(), 1);
        } else if (range === "year") {
            from = new Date(today.getFullYear(), 0, 1);
        } else {
            from.setDate(to.getDate() - 29);
        }

        fromInput.value = toDateInput(from);
        toInput.value = toDateInput(to);
    }

    function setActivePreset(range) {
        presetHost.querySelectorAll("button[data-range]").forEach(function (button) {
            button.classList.toggle("active", button.getAttribute("data-range") === range);
        });
    }

    function getPeakDay(points) {
        if (!points.length) {
            return { label: "No trend data", value: 0 };
        }

        return points.reduce(function (peak, point) {
            return Number(point.value || 0) > Number(peak.value || 0) ? point : peak;
        }, points[0]);
    }

    function averageOrderValue(block) {
        const orders = Number(block.orderCount || 0);
        return orders ? Number(block.orderValue || 0) / orders : 0;
    }

    function taxPercent(block) {
        const value = Number(block.orderValue || 0);
        return value ? (Number(block.taxValue || 0) / value) * 100 : 0;
    }

    function download(name, text) {
        const blob = new Blob([text], { type: "text/csv;charset=utf-8;" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = name;
        a.click();
        URL.revokeObjectURL(url);
    }

    function handleJson(response) {
        if (!response.ok) {
            throw new Error("Request failed");
        }
        return response.json();
    }

    function money(value) {
        return "Rs. " + Number(value || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function qty(value) {
        return Number(value || 0).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 });
    }

    function number(value) {
        return Number(value || 0).toLocaleString();
    }

    function percent(value) {
        return Number(value || 0).toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + "%";
    }

    function compact(value) {
        return Number(value || 0).toLocaleString(undefined, { notation: "compact", maximumFractionDigits: 1 });
    }

    function date(value) {
        return value ? new Date(value).toLocaleDateString("en-GB") : "";
    }

    function esc(value) {
        return String(value ?? "")
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#39;");
    }

    function toDateInput(value) {
        const year = value.getFullYear();
        const month = String(value.getMonth() + 1).padStart(2, "0");
        const day = String(value.getDate()).padStart(2, "0");
        return year + "-" + month + "-" + day;
    }
}());
