(function () {
    const metricCards = document.getElementById("metricCards");
    const topCustomers = document.getElementById("topCustomers");
    const recentInvoiceRows = document.getElementById("recentInvoiceRows");
    const recentPurchaseRows = document.getElementById("recentPurchaseRows");
    const lowStockRows = document.getElementById("lowStockRows");
    const stockAlertToggle = document.getElementById("stockAlertToggle");
    const stockAlertCountLabel = document.getElementById("stockAlertCountLabel");
    const dashboardTimestamp = document.getElementById("dashboardTimestamp");
    const activeCompanyText = document.getElementById("activeCompanyText");
    const quickAccessGrid = document.getElementById("quickAccessGrid");
    const snapshotGrid = document.getElementById("snapshotGrid");
    const moduleSummaryGrid = document.getElementById("moduleSummaryGrid");
    const insightRail = document.getElementById("insightRail");
    const summaryRangeLabel = document.getElementById("summaryRangeLabel");
    const salesTrendCanvas = document.getElementById("salesTrendChart");
    const monthlyTrendCanvas = document.getElementById("monthlyTrendChart");
    const topCustomerCanvas = document.getElementById("topCustomerChart");
    const heroQuickStat = document.getElementById("heroQuickStat");

    if (!metricCards || !topCustomers || !recentInvoiceRows || !recentPurchaseRows || !lowStockRows || !quickAccessGrid || !snapshotGrid || !moduleSummaryGrid || !insightRail) {
        return;
    }

    const quickLinks = [
        { title: "Sales Summary", description: "MTD and YTD business trend", url: "/Sales/Summary", icon: "fa-solid fa-chart-line", tone: "success" },
        { title: "Sales Invoices", description: "Find, print, and review invoices", url: "/Sales/Invoices", icon: "fa-solid fa-file-invoice-dollar", tone: "info" },
        { title: "Purchase Register", description: "Recent inward purchase bills", url: "/Sales/Purchases", icon: "fa-solid fa-basket-shopping", tone: "warning" },
        { title: "Stock Focus", description: "Low stock and batch watch", url: "/Dashboard", icon: "fa-solid fa-boxes-stacked", tone: "danger" },
        { title: "Reports", description: "Company and summary reports", url: "/Reports/SalesmanDailyHqtrCompany", icon: "fa-regular fa-chart-bar", tone: "indigo" },
        { title: "Masters", description: "Reference and setup area", url: "/Home/Privacy", icon: "fa-solid fa-layer-group", tone: "slate" }
    ];

    let salesTrendChart;
    let monthlyTrendChart;
    let topCustomerChart;
    let stockAlerts = [];
    let isShowingAllStockAlerts = false;

    renderQuickAccess();
    bindEvents();
    loadDashboard();

    function loadDashboard() {
        Promise.all([
            fetch("/api/dashboard/overview", { headers: { "X-Requested-With": "XMLHttpRequest" } }).then(handleJson),
            fetch("/api/sales/summary").then(handleJson),
            fetch("/api/sales/purchases?limit=8").then(handleJson)
        ])
            .then(function (results) {
                const overview = results[0];
                const summary = results[1];
                const purchases = results[2];

                renderMetrics(overview.metrics || []);
                renderTopCustomers(overview.topCustomers || []);
                renderInvoices(overview.recentInvoices || []);
                renderPurchases(purchases || []);
                stockAlerts = overview.stockAlerts || [];
                renderStock();
                syncStockAlertToggle();
                renderSnapshots(summary);
                renderModuleSummary(overview, summary, purchases || []);
                renderInsightRail(overview, summary, purchases || []);
                renderSalesTrend(summary.dailyTrend || []);
                renderMonthlyTrend(overview.monthlyTrend || []);
                renderTopCustomerChart(overview.topCustomers || []);

                if (dashboardTimestamp) dashboardTimestamp.textContent = overview.generatedAt || "";
                if (activeCompanyText && overview.companyName) activeCompanyText.textContent = overview.companyName;
                if (summaryRangeLabel) summaryRangeLabel.textContent = date(summary.fromDate) + " to " + date(summary.toDate);
                if (heroQuickStat) heroQuickStat.textContent = buildHeroStat(overview, summary, purchases || []);
            })
            .catch(renderError);
    }

    function bindEvents() {
        if (!stockAlertToggle) {
            return;
        }

        stockAlertToggle.addEventListener("click", function () {
            if (isShowingAllStockAlerts) {
                isShowingAllStockAlerts = false;
                renderStock();
                syncStockAlertToggle();
                return;
            }

            stockAlertToggle.disabled = true;
            stockAlertToggle.textContent = "Loading...";

            fetch("/api/dashboard/stock-alerts", { headers: { "X-Requested-With": "XMLHttpRequest" } })
                .then(handleJson)
                .then(function (items) {
                    stockAlerts = items || [];
                    isShowingAllStockAlerts = true;
                    renderStock();
                    syncStockAlertToggle();
                })
                .catch(function () {
                    stockAlertToggle.disabled = false;
                    stockAlertToggle.textContent = "View all";
                });
        });
    }

    function renderQuickAccess() {
        quickAccessGrid.innerHTML = quickLinks.map(function (item) {
            return '<a class="quick-dashboard-card ' + esc(item.tone) + '" href="' + esc(item.url) + '">' +
                '<div class="quick-dashboard-icon"><i class="' + esc(item.icon) + '"></i></div>' +
                '<div><h3>' + esc(item.title) + '</h3><p>' + esc(item.description) + '</p></div>' +
                '</a>';
        }).join("");
    }

    function renderMetrics(metrics) {
        metricCards.innerHTML = metrics.map(function (metric) {
            return '<article class="metric-card">' +
                '<span class="tone ' + esc(metric.tone || "info") + '">' + esc(metric.subtext || "") + '</span>' +
                '<h3>' + esc(metric.value || "") + '</h3>' +
                '<p>' + esc(metric.title || "") + '</p>' +
                '</article>';
        }).join("");
    }

    function renderModuleSummary(overview, summary, purchases) {
        const blocks = [
            { title: "Dashboard", note: "Live command center", meta: overview.generatedAt || "", icon: "fa-solid fa-grid-2" },
            { title: "Sales Summary", note: "MTD orders", meta: number(summary.mtd.orderCount) + " records", icon: "fa-solid fa-chart-line" },
            { title: "Sales Invoices", note: "Recent bills", meta: number((overview.recentInvoices || []).length) + " loaded", icon: "fa-solid fa-file-invoice-dollar" },
            { title: "Purchase Register", note: "Recent inward bills", meta: number((purchases || []).length) + " loaded", icon: "fa-solid fa-basket-shopping" },
            { title: "Stock Focus", note: "Low stock watch", meta: number((overview.stockAlerts || []).length) + " alerts", icon: "fa-solid fa-boxes-stacked" },
            { title: "Reports", note: "Business outputs", meta: "Ready", icon: "fa-regular fa-chart-bar" },
            { title: "Accounts", note: "Ledger workspace", meta: "Planned", icon: "fa-solid fa-wallet" },
            { title: "Utilities", note: "Session and tools", meta: overview.activeDatabaseName || "", icon: "fa-solid fa-screwdriver-wrench" }
        ];

        moduleSummaryGrid.innerHTML = blocks.map(function (block) {
            return '<article class="module-summary-card">' +
                '<div class="module-summary-icon"><i class="' + esc(block.icon) + '"></i></div>' +
                '<div><h3>' + esc(block.title) + '</h3><p>' + esc(block.note) + '</p><span>' + esc(block.meta) + '</span></div>' +
                '</article>';
        }).join("");
    }

    function renderInsightRail(overview, summary, purchases) {
        const recentInvoices = overview.recentInvoices || [];
        const purchaseRows = purchases || [];
        const avgOrder = summary && summary.mtd && summary.mtd.orderCount
            ? summary.mtd.orderValue / summary.mtd.orderCount
            : 0;
        const avgPurchase = purchaseRows.length
            ? purchaseRows.reduce(function (sum, item) { return sum + Number(item.totalAmount || 0); }, 0) / purchaseRows.length
            : 0;
        const taxRatio = summary && summary.mtd && summary.mtd.orderValue
            ? ((summary.mtd.taxValue / summary.mtd.orderValue) * 100)
            : 0;
        const customerLeader = overview.topCustomers && overview.topCustomers.length
            ? overview.topCustomers[0].partyName
            : "No customer data";

        const items = [
            { title: "Average order value", value: money(avgOrder), note: "Based on current MTD invoices" },
            { title: "Average purchase value", value: money(avgPurchase), note: "From recent inward documents" },
            { title: "GST to sales ratio", value: percent(taxRatio), note: "MTD tax share on billed value" },
            { title: "Top customer", value: customerLeader, note: number((overview.topCustomers || []).length) + " leaders tracked" },
            { title: "Invoice flow", value: number(recentInvoices.length) + " recent", note: "Latest sales documents on screen" },
            { title: "Stock watch", value: number((overview.stockAlerts || []).length) + " items", note: "Products below minimum level" }
        ];

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

    function renderTopCustomers(items) {
        topCustomers.innerHTML = items.map(function (item, index) {
            return '<article class="activity-item compact-item">' +
                '<div><h3>' + (index + 1) + ". " + esc(item.partyName || "") + '</h3><p>Customer contribution</p></div>' +
                '<span class="activity-status">' + money(item.amount || 0) + '</span>' +
                '</article>';
        }).join("");
    }

    function renderInvoices(items) {
        recentInvoiceRows.innerHTML = items.map(function (item) {
            return '<tr>' +
                '<td>' + esc(item.invoiceNo || "") + '</td>' +
                '<td>' + date(item.invoiceDate) + '</td>' +
                '<td>' + esc(item.partyName || "") + '</td>' +
                '<td class="text-end">' + money(item.totalAmount || 0) + '</td>' +
                '<td class="text-center">' +
                '<a class="btn btn-sm btn-outline-primary" href="/Sales/InvoicePrint/' + encodeURIComponent(item.invoiceNo || "") + '">Print</a>' +
                '</td>' +
                '</tr>';
        }).join("");
    }

    function renderPurchases(items) {
        recentPurchaseRows.innerHTML = items.map(function (item) {
            return '<tr>' +
                '<td>' + esc(item.invoiceNo || "") + '</td>' +
                '<td>' + date(item.invoiceDate) + '</td>' +
                '<td>' + esc(item.partyName || "") + '</td>' +
                '<td class="text-end">' + esc(item.itemCount || 0) + '</td>' +
                '<td class="text-end">' + money(item.totalAmount || 0) + '</td>' +
                '</tr>';
        }).join("");
    }

    function renderStock() {
        const visibleItems = isShowingAllStockAlerts ? stockAlerts : stockAlerts.slice(0, 10);

        lowStockRows.innerHTML = visibleItems.map(function (item) {
            return '<tr>' +
                '<td>' + esc(item.productName || "") + '</td>' +
                '<td>' + esc(item.companyName || "") + '</td>' +
                '<td class="text-end">' + qty(item.currentQty || 0) + '</td>' +
                '<td class="text-end">' + qty(item.minimumQty || 0) + '</td>' +
                '<td>' + esc(item.batchNo || "") + '</td>' +
                '</tr>';
        }).join("");

        if (!visibleItems.length) {
            lowStockRows.innerHTML = '<tr><td colspan="5" class="text-center text-muted py-4">No stock alerts found.</td></tr>';
        }
    }

    function syncStockAlertToggle() {
        if (!stockAlertToggle || !stockAlertCountLabel) {
            return;
        }

        const total = stockAlerts.length;
        const showing = isShowingAllStockAlerts ? total : Math.min(total, 10);

        stockAlertCountLabel.textContent = total ? ("Showing " + number(showing) + " of " + number(total)) : "No alerts";

        if (total > 10) {
            stockAlertToggle.hidden = false;
            stockAlertToggle.disabled = false;
            stockAlertToggle.textContent = isShowingAllStockAlerts ? "Show less" : "View all";
        } else {
            stockAlertToggle.hidden = true;
        }
    }

    function renderSnapshots(summary) {
        if (!summary) {
            snapshotGrid.innerHTML = "";
            return;
        }

        const cards = [
            { title: "MTD Orders", value: summary.mtd.orderCount, note: money(summary.mtd.orderValue) },
            { title: "YTD Orders", value: summary.ytd.orderCount, note: money(summary.ytd.orderValue) },
            { title: "Selected Tax", value: money(summary.customRange.taxValue), note: "Current range" },
            { title: "Selected Qty", value: qty(summary.customRange.quantity), note: "Current range" }
        ];

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

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

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

        salesTrendChart = new Chart(salesTrendCanvas, {
            type: "line",
            data: {
                labels: points.map(function (x) { return x.label; }),
                datasets: [{
                    label: "Sales Value",
                    data: points.map(function (x) { return x.value; }),
                    borderColor: "#0d6efd",
                    backgroundColor: "rgba(13,110,253,0.12)",
                    fill: true,
                    tension: 0.35,
                    pointRadius: 2.8,
                    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 " + Number(value).toLocaleString(); }
                        }
                    }
                }
            }
        });
    }

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

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

        monthlyTrendChart = new Chart(monthlyTrendCanvas, {
            type: "bar",
            data: {
                labels: points.map(function (x) { return x.label; }),
                datasets: [{
                    label: "Monthly Sales",
                    data: points.map(function (x) { return x.value; }),
                    borderRadius: 10,
                    backgroundColor: ["#0d6efd", "#2873f0", "#2c8fbf", "#1f9d68", "#f0ad4e", "#ff7a59"]
                }]
            },
            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 " + compactNumber(value); }
                        }
                    }
                }
            }
        });
    }

    function renderTopCustomerChart(items) {
        if (!topCustomerCanvas || typeof Chart === "undefined") {
            return;
        }

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

        topCustomerChart = new Chart(topCustomerCanvas, {
            type: "doughnut",
            data: {
                labels: items.map(function (x) { return x.partyName; }),
                datasets: [{
                    data: items.map(function (x) { return x.amount; }),
                    backgroundColor: ["#0d6efd", "#1f9d68", "#f0ad4e", "#ff7a59", "#6f42c1", "#17a2b8"],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                cutout: "68%"
            }
        });
    }

    function renderError(error) {
        metricCards.innerHTML = '<div class="alert alert-danger">Failed to load dashboard data: ' + esc(error.message || error) + "</div>";
    }

    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 percent(value) {
        return Number(value || 0).toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + "%";
    }

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

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

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

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

    function buildHeroStat(overview, summary, purchases) {
        const invoiceCount = summary && summary.mtd ? number(summary.mtd.orderCount) : "0";
        const purchaseCount = number((purchases || []).length);
        const stockCount = number((overview.stockAlerts || []).length);
        return invoiceCount + " MTD orders, " + purchaseCount + " purchase rows, " + stockCount + " stock alerts";
    }

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