// ==========================================
// ChatPane Kit — ModelSelector Component
// ==========================================
// Model dropdown loaded from sw.api.models.enabled().
// Independently importable.
//
// Usage:
//   html`<${ModelSelector} value=${modelId} onChange=${fn} />`

const { useState, useEffect } = window.hooks;
const html = window.html;

/**
 * @param {{ value: string, onChange: (id: string) => void }} props
 */
export function ModelSelector({ value, onChange }) {
    const [models, setModels] = useState([]);

    useEffect(() => {
        if (!window.sw?.api?.models?.enabled) return;
        let cancelled = false;
        window.sw.api.models.enabled().then(resp => {
            if (cancelled) return;
            const list = (resp.data || []).filter(m => !m.hidden);
            setModels(list);
            // Auto-select first model if no value set
            if (!value && list.length && onChange) {
                const first = list[0];
                const id = first.isPersona ? (first.personaId || first.id) : first.id;
                onChange(id);
            }
        }).catch(() => {});
        return () => { cancelled = true; };
    }, []);

    function _onChange(e) {
        onChange(e.target.value);
    }

    return html`
        <select class="sw-model-selector__select"
                title="Select model"
                value=${value || ''}
                onChange=${_onChange}
                disabled=${!models.length}>
            ${!models.length && html`
                <option value="" disabled selected>No models</option>`}
            ${models.map(m => {
                const id = m.isPersona ? (m.personaId || m.id) : m.id;
                const label = (m.isPersona ? '\ud83c\udfad ' : '') + (m.name || m.id);
                return html`<option key=${id} value=${id}>${label}</option>`;
            })}
        </select>`;
}
