(function () {
    'use strict';

    const API_URL = `${ADMIN_BASE_URL}api/dashboard/summary.php`;
    const DEFAULT_RANGE = 'month';

    /* ================= UTILITIES ================= */

    const qsa = (s) => document.querySelectorAll(s);

    const safe = (v, f = '-') =>
        v === undefined || v === null || v === '' ? f : v;

    const safeNum = (v) =>
        Number.isFinite(Number(v)) ? Number(v) : 0;

    /* ================= API ================= */

    async function fetchDashboard(range = DEFAULT_RANGE) {
        try {
            const res = await fetch(`${API_URL}?range=${range}`, {
                headers: { 'Accept': 'application/json' },
                credentials: 'include'
            });

            const json = await res.json();

            if (json.status !== 'success') {
                console.warn('Dashboard API error:', json.message);
                return null;
            }

            return json.data;

        } catch (err) {
            console.error('Dashboard API failed:', err);
            return null;
        }
    }

    /* ================= COUNTS ================= */

    function renderCounts(data) {
        if (!data || !data.counts) return;

        const c = data.counts;

        /* ---- TOP CARDS ---- */
        updateCardValue('Total Website Traffic', safeNum(c.leads?.total));
        updateCardValue('New Subscribers', safeNum(c.subscribers));
        updateCardValue('Total Leads', safeNum(c.leads?.this_range));
        updateCardValue("Active FAQ's", safeNum(c.faqs));

        /* ---- KPI CARDS ---- */
        updateCardValue(
            'Total Dealers',
            `${safeNum(c.dealers?.active)} Active`,
            safeNum(c.dealers?.inactive)
        );

        updateCardValue(
            'Total Employees',
            `${safeNum(c.employees?.active)} Active`,
            safeNum(c.employees?.inactive)
        );

        updateCardValue(
            'Total Retail Products',
            `${safeNum(c.products?.retail)} Active`
        );

        updateCardValue(
            'Total Hospitality Products',
            `${safeNum(c.products?.hospitality)} Active`
        );
    }

    /* ================= TABLES ================= */

    function renderTable(title, rows, renderer) {
        const card = [...qsa('.card')].find(c =>
            c.querySelector('.card-title')?.innerText.trim() === title
        );
        if (!card) return;

        const tbody = card.querySelector('tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (!rows || rows.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="10" class="text-center text-muted">
                        No data available
                    </td>
                </tr>`;
            return;
        }

        rows.forEach((r, i) => {
            tbody.insertAdjacentHTML('beforeend', renderer(r, i));
        });
    }

    function renderLists(data) {
        if (!data || !data.lists) return;

        const l = data.lists;

        renderTable('Latest Blogs', l.latest_blogs, (r, i) => `
            <tr>
                <td>${i + 1}</td>
                <td>${safe(r.title)}</td>
                <td>-</td>
                <td>-</td>
                <td>${safe(r.date)}</td>
                <td>${safe(r.status)}</td>
                <td>-</td>
            </tr>
        `);

        renderTable('Latest Faq', l.latest_faqs, (r, i) => `
            <tr>
                <td>${i + 1}</td>
                <td>${safe(r.title)}</td>
                <td>-</td>
                <td>-</td>
                <td>${safe(r.date)}</td>
                <td>${safe(r.status)}</td>
                <td>-</td>
            </tr>
        `);

        renderTable('Top Performing Dealers', l.top_dealers, (r, i) => `
            <tr>
                <td>${i + 1}</td>
                <td>${safe(r.dealer_name)}</td>
                <td>-</td>
                <td>${safeNum(r.total_leads)}</td>
                <td>-</td>
                <td>Active</td>
                <td>-</td>
            </tr>
        `);

        renderTable('Top Performing Pages', l.latest_pages, (r, i) => `
            <tr>
                <td>${i + 1}</td>
                <td>${safe(r.title)}</td>
                <td>-</td>
                <td>-</td>
                <td>-</td>
                <td>${safe(r.status)}</td>
                <td>-</td>
            </tr>
        `);

        renderTable('Top Performin Cities (Leads)', l.top_cities, (r, i) => `
            <tr>
                <td>${i + 1}</td>
                <td>${safe(r.city)}</td>
                <td>${safeNum(r.total_leads)}</td>
                <td>-</td>
                <td>-</td>
                <td>Active</td>
                <td>-</td>
            </tr>
        `);
    }

    /* ================= DOM HELPERS ================= */

    function updateCardValue(label, mainValue, subValue = null) {
        const cardBody = [...qsa('.card-body')].find(b =>
            b.querySelector('span, p')?.innerText.trim() === label
        );

        if (!cardBody) return;

        const h = cardBody.querySelector('h3, h4');
        if (h) h.innerText = mainValue;

        if (subValue !== null) {
            const p = cardBody.querySelector('p.mb-0');
            if (p) p.innerText = subValue;
        }
    }

    /* ================= INIT ================= */

    document.addEventListener('DOMContentLoaded', async () => {
        const data = await fetchDashboard(DEFAULT_RANGE);
        renderCounts(data);
        renderLists(data);
    });

})();
