// Small Community Dashboard - Growth View
// Focus on individual members: recent joins, top contributors, activity chart

async function smalldash_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("sm-card-total-members").textContent = data.total_members;
        document.getElementById("card-new-7d").textContent = data.members_last_7d;
        document.getElementById("card-posts-7d").textContent = data.posts_last_7d;
        document.getElementById("card-active-7d").textContent = data.active_members_7d;

        // Update subtitle with additional context
        document.getElementById("sm-card-total-members-sub").textContent =
            `${data.members_last_30d} joined (30d)`;
        document.getElementById("card-new-7d-sub").textContent =
            `${data.members_last_30d} joined (30d)`;
        document.getElementById("card-posts-7d-sub").textContent =
            `${data.posts_last_30d} posts (30d)`;
        document.getElementById("card-active-7d-sub").textContent =
            `of ${data.total_members} total`;

        // FB-013: Add info icon next to Total Members label
        var smLabelEl = document.querySelector('#sm-card-total-members + .dash-card-label');
        if (smLabelEl && !smLabelEl.querySelector('.ck-help-icon')) {
            smLabelEl.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 loadRecentMembers() {
    const container = document.getElementById("recent-members-list");
    try {
        const resp = await fetch("/api/dashboard/recent-members?limit=30");
        if (!resp.ok) throw new Error("Failed to load recent members");
        const members = await resp.json();

        if (members.length === 0) {
            container.innerHTML = '<div style="padding:20px;color:var(--color-text-secondary);">No member data available yet.</div>';
            return;
        }

        let html = '';
        for (const m of members) {
            const imgSrc = m.picture_url
                ? `/api/image/${m.skool_id}`
                : '';
            const imgTag = imgSrc
                ? `<img src="${imgSrc}" style="width:36px;height:36px;border-radius:50%;object-fit:cover;" onerror="this.style.display='none'">`
                : `<div style="width:36px;height:36px;border-radius:50%;background:var(--brand-primary);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold;font-size:14px;">${(m.name||'?')[0].toUpperCase()}</div>`;

            const activity = m.post_count + m.comment_count;
            let badge = '';
            if (activity === 0) badge = '<span style="color:var(--color-error);font-size:0.75em;">inactive</span>';
            else if (activity >= 10) badge = '<span style="color:var(--color-success);font-size:0.75em;">active</span>';
            else badge = '<span style="color:var(--color-warning);font-size:0.75em;">low activity</span>';

            html += `
            <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;border-bottom:1px solid var(--color-border);">
                ${imgTag}
                <div style="flex:1;min-width:0;">
                    <div style="font-weight:600;font-size:0.9em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${escapeHtml(m.name)}</div>
                    <div style="font-size:0.75em;color:var(--color-text-secondary);">Joined ${m.joined_at || 'unknown'} ${badge}</div>
                </div>
                <div style="text-align:right;font-size:0.8em;color:var(--color-text-secondary);white-space:nowrap;">
                    ${m.post_count}p / ${m.comment_count}c
                </div>
            </div>`;
        }
        container.innerHTML = html;
    } catch (e) {
        console.error("Error loading recent members:", e);
        container.innerHTML = '<div style="padding:20px;color:var(--color-error);">Failed to load recent members.</div>';
    }
}

async function loadTopContributors() {
    const container = document.getElementById("top-contributors-list");
    try {
        const resp = await fetch("/api/dashboard/top-contributors?days=30&limit=15");
        if (!resp.ok) throw new Error("Failed to load top contributors");
        const contributors = await resp.json();

        if (contributors.length === 0) {
            container.innerHTML = '<div style="padding:20px;color:var(--color-text-secondary);">No contributor data available yet.</div>';
            return;
        }

        let html = '';
        contributors.forEach((c, i) => {
            const imgSrc = c.picture_url
                ? `/api/image/${c.skool_id}`
                : '';
            const imgTag = imgSrc
                ? `<img src="${imgSrc}" style="width:32px;height:32px;border-radius:50%;object-fit:cover;" onerror="this.style.display='none'">`
                : `<div style="width:32px;height:32px;border-radius:50%;background:var(--brand-primary);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:bold;font-size:12px;">${(c.name||'?')[0].toUpperCase()}</div>`;

            const rank = i + 1;
            const rankColor = rank <= 3 ? 'var(--brand-primary)' : 'var(--color-text-secondary)';

            html += `
            <div style="display:flex;align-items:center;gap:8px;padding:6px 12px;border-bottom:1px solid var(--color-border);">
                <span style="font-weight:bold;color:${rankColor};font-size:0.85em;width:20px;text-align:right;">#${rank}</span>
                ${imgTag}
                <div style="flex:1;min-width:0;">
                    <div style="font-weight:600;font-size:0.85em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${escapeHtml(c.name)}</div>
                    <div style="font-size:0.7em;color:var(--color-text-secondary);">${c.post_count} posts, ${c.comment_count} comments</div>
                </div>
                <div style="text-align:right;font-size:0.75em;color:var(--color-text-secondary);">
                    ${c.likes_received} likes
                </div>
            </div>`;
        });
        container.innerHTML = html;
    } catch (e) {
        console.error("Error loading top contributors:", e);
        container.innerHTML = '<div style="padding:20px;color:var(--color-error);">Failed to load top contributors.</div>';
    }
}

let activityChart = null;

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

        const ctx = document.getElementById("activityChart").getContext("2d");

        if (activityChart) activityChart.destroy();

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

        activityChart = new Chart(ctx, {
            type: "line",
            data: {
                labels: data.days,
                datasets: [
                    {
                        label: "Posts",
                        data: data.posts,
                        borderColor: themeColor,
                        backgroundColor: themeColor + "33",
                        fill: true,
                        tension: 0.3,
                        pointRadius: 0,
                        borderWidth: 2,
                    },
                    {
                        label: "Comments",
                        data: data.comments,
                        borderColor: lib.getCSSVar('--color-chart-neutral'),
                        backgroundColor: `rgba(${lib.getCSSVar('--color-chart-neutral-rgb')}, 0.13)`,
                        fill: true,
                        tension: 0.3,
                        pointRadius: 0,
                        borderWidth: 2,
                    },
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: "index", intersect: false },
                plugins: {
                    legend: { position: "top", labels: { usePointStyle: true, boxWidth: 8 } },
                },
                scales: {
                    x: {
                        ticks: {
                            maxTicksLimit: 12,
                            callback: function(val, i) {
                                const label = this.getLabelForValue(val);
                                return label ? label.substring(5) : ''; // MM-DD
                            },
                        },
                        grid: { display: false },
                    },
                    y: { beginAtZero: true, grid: { color: lib.getCSSVar('--color-border') } },
                },
            },
        });
    } catch (e) {
        console.error("Error loading activity chart:", e);
    }
}

async function updateDashActivityCutoff(val) {
    const days = parseInt(val) || 90;
    await ConfigEntry.set('activity_cutoff_days', String(days));
    loadActivityChart(days);
}

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

    // Read activity cutoff config
    const cutoffVal = await ConfigEntry.get('activity_cutoff_days');
    const days = parseInt(cutoffVal) || 90;
    const cutoffInput = document.getElementById('activityCutoffDays');
    if (cutoffInput) cutoffInput.value = days;

    // Load all sections in parallel
    await Promise.all([
        smalldash_loadSummaryCards(),
        loadRecentMembers(),
        loadTopContributors(),
        loadActivityChart(days),
    ]);

    lib.hideLoading();
}
