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

export default function RolesSection() {
    const [roles, setRoles] = useState({});
    const [models, setModels] = useState([]);
    const [loading, setLoading] = useState(true);
    const [dirty, setDirty] = useState({});

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

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

    function updateRole(roleName, field, value) {
        setDirty(prev => ({
            ...prev,
            [roleName]: { ...(prev[roleName] || {}), [field]: value },
        }));
    }

    async function saveRole(roleName) {
        const changes = dirty[roleName];
        if (!changes) return;
        try {
            // Get current role config and merge changes
            const current = await sw.api.admin.roles.get(roleName);
            const updated = { ...current, ...changes };
            await sw.api.admin.roles.update(roleName, updated);
            sw.toast(`Role "${roleName}" saved`, 'success');
            setDirty(prev => { const n = { ...prev }; delete n[roleName]; return n; });
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

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

    return html`
        <div>
            ${Object.keys(roles).length === 0 && html`<div class="empty-hint">No roles configured</div>`}
            ${Object.entries(roles).map(([name, config]) => {
                const changes = dirty[name] || {};
                const primary = changes.primary_model ?? config.primary_model ?? '';
                const fallback = changes.fallback_model ?? config.fallback_model ?? '';

                return html`
                    <div class="settings-section" key=${name} style="margin-bottom:16px;padding:12px;border:1px solid var(--border);border-radius:var(--radius);">
                        <h4 style="margin:0 0 8px;">${name}</h4>
                        <div class="form-row">
                            <div class="form-group"><label>Primary Model</label>
                                <select value=${primary} onChange=${e => updateRole(name, 'primary_model', e.target.value)}>
                                    <option value="">-- None --</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 class="form-group"><label>Fallback Model</label>
                                <select value=${fallback} onChange=${e => updateRole(name, 'fallback_model', e.target.value)}>
                                    <option value="">-- None --</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>
                        ${dirty[name] && html`<button class="btn-small btn-primary" style="margin-top:8px;" onClick=${() => saveRole(name)}>Save</button>`}
                    </div>
                `;
            })}
        </div>
    `;
}
