// Big Community Dashboard - Growth View
// Focus on aggregate statistics: cumulative growth, rates, period breakdowns

let currentPeriod = 90; // default period in days

let cumulativeChart = null;
let dailyGrowthChart = null;
let postsVsCommentsChart = null;

async function bigdash_loadSummaryCards() {
    try {
        const resp = await fetch("/api/dashboard/summary");
        if (!resp.ok) throw new Error("Failed to load summary");
        const data = await resp.json();

        document.getElementById("card-total-members").textContent = data.total_members;

        // Growth rate: members_last_30d / total_members * 100
        const growthRate = data.total_members > 0
            ? ((data.members_last_30d / data.total_members) * 100).toFixed(1)
            : "0.0";
        document.getElementById("card-growth-rate").textContent = growthRate + "%";
        document.getElementById("card-growth-rate-sub").textContent =
            `${data.members_last_30d} new (30d)`;

        // Posts per day (last 30 days)
        const postsPerDay = (data.posts_last_30d / 30).toFixed(1);
        document.getElementById("card-posts-day").textContent = postsPerDay;
        document.getElementById("card-posts-day-sub").textContent =
            `${data.posts_last_30d} total (30d)`;

        // Engagement: active_members_7d / total_members * 100
        const engagement = data.total_members > 0
            ? ((data.active_members_7d / data.total_members) * 100).toFixed(1)
            : "0.0";
        document.getElementById("card-engagement").textContent = engagement + "%";
        document.getElementById("card-engagement-sub").textContent =
            `${data.active_members_7d} active (7d)`;

        document.getElementById("card-total-members-sub").textContent =
            `${data.total_posts} posts, ${data.total_comments} comments`;

        // FB-013: Add info icon next to Total Members label
        var labelEl = document.querySelector('#card-total-members + .dash-card-label');
        if (labelEl && !labelEl.querySelector('.ck-help-icon')) {
            labelEl.insertAdjacentHTML('beforeend',
                ' <span class="ck-help-icon">?<span class="ck-help-tip">This shows members synced so far. catknows fetches active members first \u2014 more are added with each sync cycle.</span></span>');
        }
    } catch (e) {
        console.error("Error loading summary:", e);
    }
}

async function loadCumulativeGrowthChart() {
    try {
        const resp = await fetch(`/api/dashboard/growth?days=${currentPeriod}`);
        if (!resp.ok) throw new Error("Failed to load growth data");
        const data = await resp.json();

        const ctx = document.getElementById("cumulativeChart").getContext("2d");
        if (cumulativeChart) cumulativeChart.destroy();

        const themeColor = getComputedStyle(document.documentElement)
            .getPropertyValue('--brand-primary').trim() || '#4a90d9';

        cumulativeChart = new Chart(ctx, {
            type: "line",
            data: {
                labels: data.days,
                datasets: [
                    {
                        label: "Members (cumulative)",
                        data: data.joined,
                        borderColor: themeColor,
                        backgroundColor: themeColor + "22",
                        fill: true,
                        tension: 0.3,
                        pointRadius: 0,
                        borderWidth: 2,
                        yAxisID: "y",
                    },
                    {
                        label: "Posts (cumulative)",
                        data: data.posts,
                        borderColor: lib.getCSSVar('--color-success'),
                        backgroundColor: `rgba(${lib.getCSSVar('--color-success-rgb')}, 0.13)`,
                        fill: false,
                        tension: 0.3,
                        pointRadius: 0,
                        borderWidth: 2,
                        yAxisID: "y1",
                    },
                    {
                        label: "Comments (cumulative)",
                        data: data.comments,
                        borderColor: lib.getCSSVar('--color-warning'),
                        backgroundColor: `rgba(${lib.getCSSVar('--color-warning-rgb')}, 0.13)`,
                        fill: false,
                        tension: 0.3,
                        pointRadius: 0,
                        borderWidth: 2,
                        yAxisID: "y1",
                    },
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: "index", intersect: false },
                plugins: {
                    legend: { position: "top", labels: { usePointStyle: true, boxWidth: 8 } },
                    title: { display: true, text: `Cumulative Growth (${currentPeriod}d)`, font: { size: 14 } },
                },
                scales: {
                    x: {
                        ticks: {
                            maxTicksLimit: 12,
                            callback: function(val, i) {
                                const label = this.getLabelForValue(val);
                                return label ? label.substring(5) : '';
                            },
                        },
                        grid: { display: false },
                    },
                    y: {
                        type: "linear",
                        position: "left",
                        title: { display: true, text: "Members" },
                        beginAtZero: true,
                        grid: { color: lib.getCSSVar('--color-border') },
                    },
                    y1: {
                        type: "linear",
                        position: "right",
                        title: { display: true, text: "Posts / Comments" },
                        beginAtZero: true,
                        grid: { drawOnChartArea: false },
                    },
                },
            },
        });

        // Also update daily growth chart with same data
        renderDailyGrowthChart(data);
    } catch (e) {
        console.error("Error loading cumulative growth:", e);
    }
}

function renderDailyGrowthChart(data) {
    const ctx = document.getElementById("dailyGrowthChart").getContext("2d");
    if (dailyGrowthChart) dailyGrowthChart.destroy();

    const themeColor = getComputedStyle(document.documentElement)
        .getPropertyValue('--brand-primary').trim() || '#4a90d9';

    // Calculate 7-day moving average
    const ma7 = [];
    for (let i = 0; i < data.daily_joined.length; i++) {
        if (i < 6) {
            ma7.push(null);
        } else {
            let sum = 0;
            for (let j = i - 6; j <= i; j++) sum += data.daily_joined[j];
            ma7.push(+(sum / 7).toFixed(2));
        }
    }

    dailyGrowthChart = new Chart(ctx, {
        type: "bar",
        data: {
            labels: data.days,
            datasets: [
                {
                    label: "Daily New Members",
                    data: data.daily_joined,
                    backgroundColor: themeColor + "66",
                    borderColor: themeColor,
                    borderWidth: 1,
                    order: 2,
                },
                {
                    label: "7-day Moving Avg",
                    data: ma7,
                    type: "line",
                    borderColor: lib.getCSSVar('--color-error'),
                    borderWidth: 2,
                    pointRadius: 0,
                    tension: 0.4,
                    fill: false,
                    order: 1,
                },
            ],
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: "index", intersect: false },
            plugins: {
                legend: { position: "top", labels: { usePointStyle: true, boxWidth: 8 } },
                title: { display: true, text: "Daily Member Growth", font: { size: 13 } },
            },
            scales: {
                x: {
                    ticks: {
                        maxTicksLimit: 10,
                        callback: function(val) {
                            const label = this.getLabelForValue(val);
                            return label ? label.substring(5) : '';
                        },
                    },
                    grid: { display: false },
                },
                y: { beginAtZero: true, grid: { color: lib.getCSSVar('--color-border') } },
            },
        },
    });
}

async function loadPostsVsCommentsChart() {
    try {
        const resp = await fetch(`/api/activity/community?days=${currentPeriod}`);
        if (!resp.ok) throw new Error("Failed to load activity data");
        const data = await resp.json();

        const ctx = document.getElementById("postsVsCommentsChart").getContext("2d");
        if (postsVsCommentsChart) postsVsCommentsChart.destroy();

        const themeColor = getComputedStyle(document.documentElement)
            .getPropertyValue('--brand-primary').trim() || '#4a90d9';

        postsVsCommentsChart = new Chart(ctx, {
            type: "bar",
            data: {
                labels: data.days,
                datasets: [
                    {
                        label: "Posts",
                        data: data.posts,
                        backgroundColor: themeColor + "99",
                        borderColor: themeColor,
                        borderWidth: 1,
                    },
                    {
                        label: "Comments",
                        data: data.comments,
                        backgroundColor: `rgba(${lib.getCSSVar('--color-chart-neutral-rgb')}, 0.53)`,
                        borderColor: lib.getCSSVar('--color-chart-neutral'),
                        borderWidth: 1,
                    },
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: "index", intersect: false },
                plugins: {
                    legend: { position: "top", labels: { usePointStyle: true, boxWidth: 8 } },
                    title: { display: true, text: "Posts vs Comments (daily)", font: { size: 13 } },
                },
                scales: {
                    x: {
                        stacked: true,
                        ticks: {
                            maxTicksLimit: 10,
                            callback: function(val) {
                                const label = this.getLabelForValue(val);
                                return label ? label.substring(5) : '';
                            },
                        },
                        grid: { display: false },
                    },
                    y: {
                        stacked: true,
                        beginAtZero: true,
                        grid: { color: lib.getCSSVar('--color-border') },
                    },
                },
            },
        });
    } catch (e) {
        console.error("Error loading posts vs comments:", e);
    }
}

async function loadGrowthTable() {
    const container = document.getElementById("growth-table-body");
    try {
        // Fetch long-term growth data (use max of currentPeriod and 365)
        const fetchDays = Math.max(currentPeriod, 365);
        const resp = await fetch(`/api/dashboard/growth?days=${fetchDays}`);
        if (!resp.ok) throw new Error("Failed to load growth data");
        const data = await resp.json();

        // Group by month
        const months = {};
        for (let i = 0; i < data.days.length; i++) {
            const monthKey = data.days[i].substring(0, 7); // YYYY-MM
            if (!months[monthKey]) {
                months[monthKey] = { joined: 0, posts: 0 };
            }
            months[monthKey].joined += data.daily_joined[i];
            months[monthKey].posts += data.daily_posts[i];
        }

        // Sort months descending
        const sortedMonths = Object.keys(months).sort().reverse();

        let html = '';
        for (const month of sortedMonths.slice(0, 12)) {
            const m = months[month];
            html += `
            <tr>
                <td style="padding:6px 12px;font-weight:600;">${month}</td>
                <td style="padding:6px 12px;text-align:right;">${m.joined}</td>
                <td style="padding:6px 12px;text-align:right;">${m.posts}</td>
            </tr>`;
        }
        container.innerHTML = html || '<tr><td colspan="3" style="padding:12px;color:var(--color-text-secondary);">No data</td></tr>';
    } catch (e) {
        console.error("Error loading growth table:", e);
        container.innerHTML = '<tr><td colspan="3" style="padding:12px;color:var(--color-error);">Failed to load</td></tr>';
    }
}

function setPeriod(days) {
    currentPeriod = days;
    ConfigEntry.set("bigdash.period", days.toString()).then();

    // Update button styles
    document.querySelectorAll("#tab-growth .period-btn").forEach(btn => {
        btn.style.fontWeight = parseInt(btn.dataset.days) === days ? "bold" : "normal";
        btn.style.textDecoration = parseInt(btn.dataset.days) === days ? "underline" : "none";
    });

    // Reload charts with new period
    lib.showLoading("Updating charts...");
    Promise.all([
        loadCumulativeGrowthChart(),
        loadPostsVsCommentsChart(),
        loadGrowthTable(),
    ]).then(() => lib.hideLoading());
}

async function initBigDash() {
    lib.showLoading("Loading dashboard...");

    // Restore saved period
    const savedPeriod = await ConfigEntry.get("bigdash.period");
    if (savedPeriod && parseInt(savedPeriod) > 0) {
        currentPeriod = parseInt(savedPeriod);
    }

    // Set initial button state
    document.querySelectorAll("#tab-growth .period-btn").forEach(btn => {
        btn.style.fontWeight = parseInt(btn.dataset.days) === currentPeriod ? "bold" : "normal";
        btn.style.textDecoration = parseInt(btn.dataset.days) === currentPeriod ? "underline" : "none";
    });

    // Load all sections in parallel
    await Promise.all([
        bigdash_loadSummaryCards(),
        loadCumulativeGrowthChart(),
        loadPostsVsCommentsChart(),
        loadGrowthTable(),
    ]);

    lib.hideLoading();
}
