// ==========================================
// Chat Surface — Sidebar Component
// ==========================================
// Search bar, new chat, unified channel list with folders.
// Footer has UserMenu (avatar) — all navigation lives in the menu flyout.

import { SidebarItems }    from './sidebar-chats.js';
import { UserMenu }        from '../../shell/user-menu.js';

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

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>`;

const SEARCH_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">
        <circle cx="11" cy="11" r="8"/>
        <line x1="21" y1="21" x2="16.65" y2="16.65"/>
    </svg>`;

const COLLAPSE_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">
        <rect x="3" y="3" width="18" height="18" rx="2"/>
        <line x1="9" y1="3" x2="9" y2="21"/>
    </svg>`;

const FOLDER_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">
        <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
        <line x1="12" y1="11" x2="12" y2="17"/>
        <line x1="9" y1="14" x2="15" y2="14"/>
    </svg>`;

/**
 * @param {{
 *   sidebar: ReturnType<import('./use-sidebar.js').useSidebar>,
 *   activeId: string|null,
 *   onSelect: (id: string, type: string) => void,
 *   onNewChat: () => void,
 *   onCollapse: () => void,
 * }} props
 */
export function Sidebar({ sidebar, activeId, onSelect, onNewChat, onCreateChannel, onDeleteChat, onCollapse }) {
    const [newMenuOpen, setNewMenuOpen] = useState(false);
    const newMenuRef = useRef(null);

    const _onSearch = useCallback((e) => {
        sidebar.setSearch(e.target.value);
    }, [sidebar.setSearch]);

    const _onNewFolder = useCallback(async () => {
        const name = await window.sw.prompt('Folder name:', '');
        if (name && name.trim()) sidebar.createFolder(name.trim());
    }, [sidebar.createFolder]);

    // Close new-channel dropdown on outside click / Escape
    useEffect(() => {
        if (!newMenuOpen) return;
        function _close(e) {
            if (e.type === 'keydown' && e.key !== 'Escape') return;
            if (e.type === 'click' && newMenuRef.current?.contains(e.target)) return;
            setNewMenuOpen(false);
        }
        document.addEventListener('click', _close);
        document.addEventListener('keydown', _close);
        return () => {
            document.removeEventListener('click', _close);
            document.removeEventListener('keydown', _close);
        };
    }, [newMenuOpen]);

    const _newChannel = useCallback(async (type) => {
        setNewMenuOpen(false);
        if (type === 'direct') {
            onNewChat();
        } else if (type === 'dm') {
            const who = await window.sw.prompt('Username to DM:', '');
            if (who && who.trim()) onCreateChannel('dm', 'DM: ' + who.trim(), { participant: who.trim() });
        } else {
            const name = await window.sw.prompt((type === 'channel' ? 'Channel' : 'Group') + ' name:', '');
            if (name && name.trim()) onCreateChannel(type, name.trim());
        }
    }, [onNewChat, onCreateChannel]);

    return html`
        <div class="sw-chat-surface__sidebar" role="navigation" aria-label="Chat sidebar">
            ${/* Header: new chat + collapse */''}
            <div class="sw-chat-surface__sidebar-header">
                <div class="sw-chat-surface__new-menu-wrap" ref=${newMenuRef}>
                    <button class="sw-chat-surface__new-chat-btn"
                            onClick=${() => setNewMenuOpen(!newMenuOpen)}
                            title="New conversation"
                            aria-label="New conversation">
                        ${PLUS_SVG}
                        <span>New</span>
                    </button>
                    ${newMenuOpen && html`
                        <div class="sw-chat-surface__new-menu">
                            <button onClick=${() => _newChannel('direct')}>
                                <span class="sw-chat-surface__new-menu-icon">\u{1F4AC}</span> AI Chat
                            </button>
                            <button onClick=${() => _newChannel('channel')}>
                                <span class="sw-chat-surface__new-menu-icon">#</span> Channel
                            </button>
                            <button onClick=${() => _newChannel('group')}>
                                <span class="sw-chat-surface__new-menu-icon">\u{1F465}</span> Group
                            </button>
                            <button onClick=${() => _newChannel('dm')}>
                                <span class="sw-chat-surface__new-menu-icon">\u{1F4E8}</span> Direct Message
                            </button>
                        </div>`}
                </div>
                <button class="sw-chat-surface__new-folder-btn"
                        onClick=${_onNewFolder}
                        title="New folder"
                        aria-label="Create new folder">
                    ${FOLDER_PLUS_SVG}
                </button>
                <button class="sw-chat-surface__collapse-btn"
                        onClick=${onCollapse}
                        title="Collapse sidebar"
                        aria-label="Collapse sidebar">
                    ${COLLAPSE_SVG}
                </button>
            </div>

            ${/* Search */''}
            <div class="sw-chat-surface__search-wrap">
                <span class="sw-chat-surface__search-icon">${SEARCH_SVG}</span>
                <input class="sw-chat-surface__search"
                       type="text"
                       placeholder="Search\u2026"
                       value=${sidebar.search}
                       onInput=${_onSearch}
                       aria-label="Search chats and channels" />
            </div>

            ${/* Scrollable content */''}
            <div class="sw-chat-surface__sidebar-body">
                <${SidebarItems}
                    itemsByFolder=${sidebar.itemsByFolder}
                    folders=${sidebar.folders}
                    folderTree=${sidebar.folderTree}
                    activeId=${activeId}
                    onSelect=${onSelect}
                    onRename=${sidebar.renameChat}
                    onDelete=${onDeleteChat || sidebar.deleteChat}
                    onMoveToFolder=${sidebar.moveToFolder}
                    onMoveFolderTo=${sidebar.moveFolderTo}
                    onCreateFolder=${sidebar.createFolder}
                    onRenameFolder=${sidebar.renameFolder}
                    onDeleteFolder=${sidebar.deleteFolder} />
            </div>

            ${/* Footer: UserMenu only */''}
            <div class="sw-chat-surface__sidebar-footer">
                <${UserMenu} placement="up-right" />
            </div>
        </div>`;
}
