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

const CAP_FIELDS = ['supports_vision', 'supports_tools', 'supports_thinking', 'context_window', 'max_output_tokens'];

export default function CapabilitiesSection() {
    const [overrides, setOverrides] = useState([]);
    const [models, setModels] = useState([]);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState(null); // model_id string or null

    const load = useCallback(async () => {
        try {
            const [o, m] = await Promise.all([
                sw.api.admin.models.overrides(),
                sw.api.admin.models.list().catch(() => []),
            ]);
            setOverrides(o.data || []);
            setModels(m || []);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

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

    async function saveOverride(modelId, field, value) {
        try {
            await sw.api.admin.models.setCapability(modelId, { [field]: value });
            sw.toast('Override saved', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function deleteOverride(modelId, overrideId) {
        try {
            await sw.api.admin.models.delCapability(modelId, overrideId);
            sw.toast('Override removed', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    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;">
                Override auto-detected model capabilities. ${overrides.length} active overrides.
            </p>

            <div class="admin-list">
                ${overrides.length === 0 && html`<div class="empty-hint">No capability overrides</div>`}
                ${overrides.map(o => html`
                    <div class="admin-surface-row" key=${o.id} style="flex-direction:column;align-items:stretch;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <strong style="flex:1;">${o.model_id || o.display_name || o.id}</strong>
                            <button class="btn-small btn-danger" onClick=${() => deleteOverride(o.model_id, o.id)}>Remove</button>
                        </div>
                        <div class="text-muted" style="font-size:12px;margin-top:4px;">
                            ${Object.entries(o).filter(([k]) => CAP_FIELDS.includes(k) && o[k] != null).map(([k, v]) =>
                                html`<span key=${k} class="badge" style="margin-right:4px;">${k}: ${String(v)}</span>`
                            )}
                        </div>
                    </div>
                `)}
            </div>

            <div class="settings-section" style="margin-top:24px;">
                <h4>Add Override</h4>
                <div class="form-row">
                    <div class="form-group"><label>Model</label>
                        <select value=${editing || ''} onChange=${e => setEditing(e.target.value || null)}>
                            <option value="">Select model\u2026</option>
                            ${models.map(m => html`<option key=${m.id} value=${m.model_id || m.id}>${m.display_name || m.model_id || m.id}</option>`)}
                        </select>
                    </div>
                </div>
                ${editing && html`
                    <div style="margin-top:8px;">
                        ${CAP_FIELDS.map(field => {
                            const isBool = field.startsWith('supports_');
                            return html`
                                <div key=${field} class="form-row" style="margin-bottom:4px;align-items:center;">
                                    <span style="width:180px;font-size:12px;">${field}</span>
                                    ${isBool
                                        ? html`
                                            <button class="btn-small btn-primary" onClick=${() => saveOverride(editing, field, true)}>true</button>
                                            <button class="btn-small" onClick=${() => saveOverride(editing, field, false)}>false</button>
                                        `
                                        : html`
                                            <input type="number" style="width:120px;" placeholder="value"
                                                   onKeyDown=${e => { if (e.key === 'Enter') saveOverride(editing, field, parseInt(e.target.value)); }} />
                                        `
                                    }
                                </div>
                            `;
                        })}
                    </div>
                `}
            </div>
        </div>
    `;
}
