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

export default function KnowledgeSection({ teamId }) {
    const [kbs, setKbs] = useState([]);
    const [loading, setLoading] = useState(true);

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

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

    function fmtDate(d) {
        if (!d) return '\u2014';
        return new Date(d).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });
    }

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

    return html`
        <div>
            <div class="admin-list">
                ${kbs.length === 0 && html`<div class="empty-hint">No knowledge bases</div>`}
                ${kbs.map(k => html`
                    <div class="admin-surface-row" key=${k.id}>
                        <div style="flex:1;min-width:0;">
                            <strong>${k.name}</strong>
                            <span class="text-muted" style="margin-left:8px;font-size:12px;">${k.document_count || 0} docs</span>
                        </div>
                        <span class="text-muted" style="font-size:11px;">${fmtDate(k.created_at)}</span>
                    </div>
                `)}
            </div>
        </div>
    `;
}
