/**
 * UsageSection — personal usage statistics
 */
const { html } = window;
const { useState, useEffect } = hooks;

function esc(s) { return s == null ? '' : String(s); }
function fmt(n) { return n == null ? '0' : n.toLocaleString(); }

export function UsageSection() {
    const [usage, setUsage] = useState(null);

    useEffect(() => {
        // Use the generic API escape hatch since there's no dedicated namespace
        sw.api.get('/api/v1/profile/usage').then(data => {
            setUsage(data);
        }).catch(() => setUsage({}));
    }, []);

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

    const totals = usage.totals || usage;
    const byModel = usage.by_model || [];

    return html`
        <div class="settings-section">
            <h3>Totals</h3>
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:12px;">
                ${[
                    ['Requests', totals.request_count],
                    ['Input Tokens', totals.input_tokens],
                    ['Output Tokens', totals.output_tokens],
                    ['Total Tokens', totals.total_tokens],
                ].map(([label, val]) => html`
                    <div style="background:var(--bg-raised);border-radius:8px;padding:14px;">
                        <div style="font-size:11px;color:var(--text-3);margin-bottom:4px;">${label}</div>
                        <div style="font-size:18px;font-weight:600;">${fmt(val)}</div>
                    </div>
                `)}
            </div>
        </div>

        ${byModel.length > 0 && html`
            <div class="settings-section" style="margin-top:16px;">
                <h3>By Model</h3>
                <table class="admin-table">
                    <thead>
                        <tr><th>Model</th><th>Requests</th><th>Tokens</th></tr>
                    </thead>
                    <tbody>
                        ${byModel.map(m => html`
                            <tr>
                                <td style="font-size:13px;">${esc(m.model_id || m.model)}</td>
                                <td style="font-size:12px;">${fmt(m.request_count)}</td>
                                <td style="font-size:12px;">${fmt(m.total_tokens)}</td>
                            </tr>
                        `)}
                    </tbody>
                </table>
            </div>
        `}
    `;
}
