// ==========================================
// Chat Surface — Channel Settings Panel
// ==========================================
// Drawer for editing channel title, description, topic, ai_mode.
// Uses Drawer primitive + channels.update API.

import { Drawer } from '../../primitives/drawer.js';

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

const AI_MODES = [
    { value: 'auto', label: 'Auto (always reply)' },
    { value: 'mention_only', label: 'Mention only' },
    { value: 'off', label: 'Off' },
];

/**
 * @param {{ open: boolean, channelId: string, onClose: () => void }} props
 */
export function ChannelSettingsPanel({ open, channelId, onClose }) {
    const [channel, setChannel] = useState(null);
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [form, setForm] = useState({ title: '', description: '', topic: '', ai_mode: 'auto' });

    const load = useCallback(async () => {
        if (!channelId) return;
        setLoading(true);
        try {
            const data = await sw.api.channels.get(channelId);
            setChannel(data);
            setForm({
                title: data.title || '',
                description: data.description || '',
                topic: data.topic || '',
                ai_mode: data.ai_mode || 'auto',
            });
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, [channelId]);

    useEffect(() => {
        if (open && channelId) load();
    }, [open, channelId, load]);

    function _set(key, value) {
        setForm(prev => ({ ...prev, [key]: value }));
    }

    async function save(e) {
        e.preventDefault();
        setSaving(true);
        try {
            await sw.api.channels.update(channelId, {
                title: form.title || undefined,
                description: form.description || undefined,
                topic: form.topic || undefined,
                ai_mode: form.ai_mode || undefined,
            });
            sw.toast('Settings saved', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setSaving(false); }
    }

    if (!open) return null;

    return html`
        <${Drawer} open=${open} side="right" width="340px" title="Channel Settings" onClose=${onClose}>
            ${loading && !channel
                ? html`<div class="sw-panel-loading">Loading\u2026</div>`
                : html`
                    <form class="sw-settings-form" onSubmit=${save}>
                        <div class="sw-settings-field">
                            <label>Title</label>
                            <input type="text" value=${form.title}
                                   onInput=${e => _set('title', e.target.value)} />
                        </div>
                        <div class="sw-settings-field">
                            <label>Description</label>
                            <textarea rows="3" value=${form.description}
                                      onInput=${e => _set('description', e.target.value)} />
                        </div>
                        <div class="sw-settings-field">
                            <label>Topic</label>
                            <input type="text" value=${form.topic}
                                   onInput=${e => _set('topic', e.target.value)} />
                        </div>
                        <div class="sw-settings-field">
                            <label>AI Mode</label>
                            <select value=${form.ai_mode}
                                    onChange=${e => _set('ai_mode', e.target.value)}>
                                ${AI_MODES.map(m => html`
                                    <option key=${m.value} value=${m.value}>${m.label}</option>`)}
                            </select>
                        </div>
                        ${channel && html`
                            <div class="sw-settings-info">
                                <div><strong>Type:</strong> ${channel.channel_type || channel.type || '\u2014'}</div>
                                <div><strong>Created:</strong> ${channel.created_at ? new Date(channel.created_at).toLocaleDateString() : '\u2014'}</div>
                            </div>`}
                        <button type="submit" class="btn-md btn-primary sw-settings-save"
                                disabled=${saving}>
                            ${saving ? 'Saving\u2026' : 'Save'}
                        </button>
                    </form>`}
        <//>`;
}
