/**
 * Team Admin > Usage
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function UsageSection({ teamId }) {
    const [usage, setUsage] = useState(null);
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        try {
            const data = await sw.api.teams.usage(teamId);
            setUsage(data);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, [teamId]);

    useEffect(() => { load(); }, [load]);

    function fmtNum(n) {
        if (n == null) return '\u2014';
        return n.toLocaleString();
    }

    if (loading) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    return html`
        <div>
            ${usage?.totals && html`
                <div class="stat-cards-grid" style="margin-bottom:16px;">
                    <div class="stat-card"><div class="stat-value">${fmtNum(usage.totals.total_tokens)}</div><div class="stat-label">Total Tokens</div></div>
                    <div class="stat-card"><div class="stat-value">${fmtNum(usage.totals.total_requests)}</div><div class="stat-label">Total Requests</div></div>
                    <div class="stat-card"><div class="stat-value">$${(usage.totals.total_cost || 0).toFixed(2)}</div><div class="stat-label">Total Cost</div></div>
                </div>
            `}

            ${usage?.results && usage.results.length > 0 && html`
                <h4 style="margin:16px 0 8px;">Usage by Day</h4>
                <div class="admin-list">
                    ${usage.results.map((r, i) => html`
                        <div class="admin-surface-row" key=${i}>
                            <span style="width:100px;">${r.date || r.day || '\u2014'}</span>
                            <span style="flex:1;">${fmtNum(r.tokens)} tokens</span>
                            <span class="text-muted" style="font-size:12px;">${r.requests || 0} requests</span>
                            <span class="text-muted" style="font-size:12px;">$${(r.cost || 0).toFixed(2)}</span>
                        </div>
                    `)}
                </div>
            `}

            ${(!usage?.totals && !usage?.results) && html`
                <div class="empty-hint">No usage data available</div>
            `}
        </div>
    `;
}
