/**
 * RolesSection — user model role overrides (requires BYOK providers)
 *
 * Each "role" (primary, fallback) can be overridden to use a personal
 * provider + model instead of the org default.
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

function esc(s) { return s == null ? '' : String(s); }

const ROLE_NAMES = ['primary', 'fallback'];

export function RolesSection() {
    const [providers, setProviders] = useState([]);
    const [models, setModels] = useState([]);
    const [roles, setRoles] = useState({});
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        (async () => {
            try {
                const [provResp, modResp, settings] = await Promise.all([
                    sw.api.providers.list(),
                    sw.api.models.enabled(),
                    sw.api.profile.settings(),
                ]);
                const provs = (provResp || [])
                    .filter(c => c.scope === 'personal');
                setProviders(provs);
                setModels(modResp.data || []);

                // Extract role overrides from settings
                const overrides = settings?.model_roles || {};
                setRoles(overrides);
            } catch (e) {
                console.warn('[settings/roles]', e.message);
            } finally {
                setLoading(false);
            }
        })();
    }, []);

    const setRoleProvider = useCallback((role, provId) => {
        setRoles(r => ({
            ...r,
            [role]: { ...(r[role] || {}), provider_config_id: provId, model_id: '' },
        }));
    }, []);

    const setRoleModel = useCallback((role, modelId) => {
        setRoles(r => ({
            ...r,
            [role]: { ...(r[role] || {}), model_id: modelId },
        }));
    }, []);

    const save = useCallback(async () => {
        setSaving(true);
        try {
            await sw.api.profile.updateSettings({ model_roles: roles });
            sw.emit('toast', { message: 'Roles saved', variant: 'success' });
        } catch (e) {
            sw.emit('toast', { message: e.message, variant: 'error' });
        } finally {
            setSaving(false);
        }
    }, [roles]);

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

    if (!providers.length) {
        return html`
            <div class="settings-section">
                <p style="color:var(--text-2);font-size:13px;">
                    Add a personal provider first to configure model role overrides.
                </p>
            </div>
        `;
    }

    return html`
        ${ROLE_NAMES.map(role => {
            const r = roles[role] || {};
            const provId = r.provider_config_id || '';
            const modelId = r.model_id || '';
            const filteredModels = provId
                ? models.filter(m => m.provider_config_id === provId)
                : [];
            return html`
                <div class="settings-section" style="margin-bottom:16px;">
                    <h3 style="text-transform:capitalize;">${role}</h3>
                    <div style="display:flex;gap:12px;">
                        <div class="form-group" style="flex:1;">
                            <label>Provider</label>
                            <select value=${provId}
                                    onChange=${e => setRoleProvider(role, e.target.value)}>
                                <option value="">\u2014 use org default \u2014</option>
                                ${providers.map(p => html`
                                    <option value=${p.id}>${esc(p.name)}</option>
                                `)}
                            </select>
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label>Model</label>
                            <select value=${modelId} disabled=${!provId}
                                    onChange=${e => setRoleModel(role, e.target.value)}>
                                <option value="">\u2014 select model \u2014</option>
                                ${filteredModels.map(m => html`
                                    <option value=${m.model_id || m.id}>
                                        ${esc(m.display_name || m.model_id || m.id)}
                                    </option>
                                `)}
                            </select>
                        </div>
                    </div>
                </div>
            `;
        })}
        <button class="btn-md btn-primary" disabled=${saving} onClick=${save}>
            ${saving ? 'Saving\u2026' : 'Save Roles'}
        </button>
    `;
}
