/**
 * GeneralSection — user preferences (default surface)
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export function GeneralSection() {
    const [surfaces, setSurfaces] = useState([]);
    const [defaultSurface, setDefaultSurface] = useState('');
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        (async () => {
            try {
                const [s, surfList] = await Promise.all([
                    sw.api.profile.settings(),
                    sw.api.get('/api/v1/surfaces').catch(() => []),
                ]);
                const sObj = s || {};
                setDefaultSurface(sObj.default_surface || '');
                setSurfaces((surfList || []).filter(s => s.route?.startsWith('/s/')));
            } catch (e) {
                console.warn('[settings/general] Load failed:', e.message);
            }
        })();
    }, []);

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

    return html`
        <div class="settings-section">
            <h3>Default Surface</h3>
            <div class="form-group">
                <label>Landing page after login</label>
                <select value=${defaultSurface} onChange=${e => setDefaultSurface(e.target.value)}>
                    <option value="">-- Use global default --</option>
                    ${surfaces.map(s => html`<option key=${s.id} value=${s.id}>${s.icon ? s.icon + ' ' : ''}${s.title || s.id}</option>`)}
                </select>
            </div>
            <span style="font-size:12px;color:var(--text-3);">
                Override the global default set by your administrator.
                If your chosen surface is uninstalled, the global default is used.
            </span>
        </div>
        <button class="btn-md btn-primary" style="margin-top:12px;"
                disabled=${saving} onClick=${save}>
            ${saving ? 'Saving\u2026' : 'Save'}
        </button>
    `;
}
