// ==========================================
// ChatPane Kit — ChatHistory Component
// ==========================================
// Channel history select + new-chat button.
// Independently importable.
//
// Usage:
//   html`<${ChatHistory} channelId=${id} onSelect=${fn} onNew=${fn} />`

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

const PLUS_SVG = html`
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <line x1="12" y1="5" x2="12" y2="19"/>
        <line x1="5" y1="12" x2="19" y2="12"/>
    </svg>`;

/**
 * @param {{ channelId: string|null, onSelect: (id: string) => void, onNew: () => void }} props
 */
export function ChatHistory({ channelId, onSelect, onNew }) {
    const [channels, setChannels] = useState([]);

    function _load() {
        if (!window.sw?.api?.channels?.list) return;
        window.sw.api.channels.list({ page: 1, per_page: 20, channel_type: 'direct' })
            .then(resp => {
                setChannels(resp || []);
            })
            .catch(() => {});
    }

    useEffect(() => { _load(); }, [channelId]);

    function _onChange(e) {
        const val = e.target.value;
        if (val) onSelect(val);
        else onNew();
    }

    return html`
        <div class="sw-chat-pane__header-left">
            <select class="sw-chat-history__select"
                    title="Switch chat"
                    value=${channelId || ''}
                    onChange=${_onChange}>
                <option value="">New conversation</option>
                ${channels.map(ch => html`
                    <option key=${ch.id} value=${ch.id}>${ch.title || 'Untitled'}</option>`)}
            </select>
            <button class="sw-chat-history__new-btn" title="New chat" onClick=${onNew}>
                ${PLUS_SVG}
            </button>
        </div>`;
}
