/**
 * Admin > Routing > Health
 */
const { html } = window;
const { useState, useEffect, useCallback, useRef } = hooks;

export default function HealthSection() {
    const [providers, setProviders] = useState([]);
    const [loading, setLoading] = useState(true);
    const timerRef = useRef(null);

    const load = useCallback(async () => {
        try {
            const data = await sw.api.admin.providers.health();
            setProviders(data || []);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

    useEffect(() => {
        load();
        timerRef.current = setInterval(load, 30000);
        return () => clearInterval(timerRef.current);
    }, []);

    function statusClass(s) {
        if (s === 'healthy') return 'badge-active';
        if (s === 'degraded') return 'badge-pending';
        return 'badge-inactive';
    }

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

    return html`
        <div>
            <p class="text-muted" style="font-size:12px;margin-bottom:12px;">Auto-refreshes every 30s</p>
            <div class="stat-cards-grid">
                ${providers.length === 0 && html`<div class="empty-hint">No providers</div>`}
                ${providers.map(p => html`
                    <div class="dashboard-provider-card" key=${p.provider_config_id}>
                        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                            <strong>${p.provider_config_name || p.provider_config_id}</strong>
                            <span class="badge ${statusClass(p.status)}">${p.status}</span>
                        </div>
                        <div style="font-size:12px;color:var(--text-2);">
                            <div>Error rate: ${((p.error_rate || 0) * 100).toFixed(1)}%</div>
                            <div>Avg latency: ${Math.round(p.avg_latency_ms || 0)}ms</div>
                            <div>Timeout rate: ${((p.timeout_rate || 0) * 100).toFixed(1)}%</div>
                            <div>Rate limits: ${p.rate_limit_count || 0}</div>
                            ${p.last_error && html`<div style="color:var(--danger);margin-top:4px;font-size:11px;">Last error: ${p.last_error}</div>`}
                        </div>
                    </div>
                `)}
            </div>
        </div>
    `;
}
