// ==========================================
// Chat Surface — ChatWorkspace Component
// ==========================================
// Header bar (model selector, tools, sidebar toggle) + ChatPane.
// ChatPane runs standalone=false — the surface manages navigation.

import { ChatPane, ModelSelector, useChat } from '../../components/chat-pane/index.js';
import { NotificationBell } from '../../shell/notification-bell.js';
import { ChannelMembersPanel } from './channel-members-panel.js';
import { ChannelSettingsPanel } from './channel-settings-panel.js';
import { UserPicker } from '../../primitives/user-picker.js';

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


const PANEL_SVG = html`
    <svg width="15" height="15" 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 PEOPLE_SVG = html`
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
        <circle cx="9" cy="7" r="4"/>
        <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
        <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
    </svg>`;

const GEAR_SVG = html`
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="3"/>
        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
    </svg>`;

/**
 * @param {{
 *   activeId: string|null,
 *   activeType: 'chat'|'channel'|null,
 *   onChannelChange: (id: string) => void,
 *   onNewChat: () => void,
 *   sidebarOpen: boolean,
 *   onToggleSidebar: () => void,
 *   toolsButton?: any,
 * }} props
 */
export function ChatWorkspace({
    activeId, activeType, channelType, onChannelChange, onNewChat, onCreateChannel,
    sidebarOpen, onToggleSidebar, toolsButton, sidebar,
}) {
    const chatRef = useRef(null);
    const [selectedModel, setSelectedModel] = useState(null);
    const [membersOpen, setMembersOpen] = useState(false);
    const [settingsOpen, setSettingsOpen] = useState(false);
    const activeChannel = sidebar?.items?.find(c => c.id === activeId);
    const showModelSelector = (activeChannel?.ai_mode || 'auto') !== 'off';

    // Close panels on channel switch
    useEffect(() => {
        setMembersOpen(false);
        setSettingsOpen(false);
    }, [activeId]);

    // Sync model selection into ChatPane's useChat
    useEffect(() => {
        if (selectedModel && chatRef.current?.setModel) {
            chatRef.current.setModel(selectedModel);
        }
    }, [selectedModel]);

    // When activeId changes, tell ChatPane to switch channel
    useEffect(() => {
        if (chatRef.current) {
            chatRef.current.setChannel(activeId);
        }
    }, [activeId]);

    // Dashboard view when no channel selected
    if (!activeId) {
        return html`
            <div class="sw-chat-surface__workspace">
                <div class="sw-chat-surface__workspace-header">
                    <div class="sw-chat-surface__workspace-header-left">
                        ${!sidebarOpen && html`
                            <button class="sw-chat-surface__sidebar-toggle"
                                    onClick=${onToggleSidebar}
                                    title="Show sidebar"
                                    aria-label="Show sidebar">
                                ${PANEL_SVG}
                            </button>`}
                    </div>
                    <div class="sw-chat-surface__workspace-header-right">
                        <${NotificationBell} onNavigate=${onChannelChange} />
                    </div>
                </div>
                <${ChatDashboard} onNewChat=${onNewChat} onCreateChannel=${onCreateChannel}
                                  items=${sidebar?.items} onNavigate=${onChannelChange} />
            </div>`;
    }

    return html`
        <div class="sw-chat-surface__workspace">
            <div class="sw-chat-surface__workspace-header">
                <div class="sw-chat-surface__workspace-header-left">
                    ${!sidebarOpen && html`
                        <button class="sw-chat-surface__sidebar-toggle"
                                onClick=${onToggleSidebar}
                                title="Show sidebar"
                                aria-label="Show sidebar">
                            ${PANEL_SVG}
                        </button>`}
                </div>
                <div class="sw-chat-surface__workspace-header-right">
                    ${showModelSelector && html`
                        <${ModelSelector}
                            value=${selectedModel}
                            onChange=${setSelectedModel} />`}
                    <button class="sw-chat-surface__header-btn"
                            onClick=${() => setMembersOpen(v => !v)}
                            title="Members"
                            aria-label="Members">
                        ${PEOPLE_SVG}
                    </button>
                    <button class="sw-chat-surface__header-btn"
                            onClick=${() => setSettingsOpen(v => !v)}
                            title="Channel settings"
                            aria-label="Channel settings">
                        ${GEAR_SVG}
                    </button>
                    <${NotificationBell} onNavigate=${onChannelChange} />
                    ${toolsButton}
                </div>
            </div>
            <${ChatPane}
                channelId=${activeId}
                standalone=${false}
                modelId=${selectedModel}
                handleRef=${chatRef}
                onChannelChange=${onChannelChange}
                className="sw-chat-surface__chat-pane" />
            <${ChannelMembersPanel}
                open=${membersOpen}
                channelId=${activeId}
                onClose=${() => setMembersOpen(false)} />
            <${ChannelSettingsPanel}
                open=${settingsOpen}
                channelId=${activeId}
                onClose=${() => setSettingsOpen(false)} />
        </div>`;
}

// ── Dashboard (no chat selected) ────────────

function ChatDashboard({ onNewChat, onCreateChannel, items, onNavigate }) {
    const recentItems = (items || []).slice(0, 8);
    const [showDmPicker, setShowDmPicker] = useState(false);

    async function _create(type) {
        if (type === 'dm') {
            setShowDmPicker(true);
            return;
        }
        const label = type === 'channel' ? 'Channel' : 'Group';
        const name = await window.sw.prompt(label + ' name:', '');
        if (name && name.trim()) onCreateChannel(type, name.trim());
    }

    const _onDmSelect = useCallback((user) => {
        setShowDmPicker(false);
        const name = user.display_name || user.username;
        onCreateChannel('dm', 'DM: ' + name, { participant: user.username || user.id });
    }, [onCreateChannel]);

    return html`
        <div class="sw-chat-dashboard">
            <div class="sw-chat-dashboard__welcome">
                <h2 class="sw-chat-dashboard__title">Chat Switchboard</h2>
                <p class="sw-chat-dashboard__hint">Start a conversation or browse your channels.</p>
            </div>
            <div class="sw-chat-dashboard__actions">
                <button class="sw-chat-dashboard__card" onClick=${onNewChat}>
                    <span class="sw-chat-dashboard__card-icon">\u{1F4AC}</span>
                    <span class="sw-chat-dashboard__card-label">New AI Chat</span>
                </button>
                <button class="sw-chat-dashboard__card" onClick=${() => _create('channel')}>
                    <span class="sw-chat-dashboard__card-icon">#</span>
                    <span class="sw-chat-dashboard__card-label">New Channel</span>
                </button>
                <button class="sw-chat-dashboard__card" onClick=${() => _create('group')}>
                    <span class="sw-chat-dashboard__card-icon">\u{1F465}</span>
                    <span class="sw-chat-dashboard__card-label">New Group</span>
                </button>
                <button class="sw-chat-dashboard__card" onClick=${() => _create('dm')}>
                    <span class="sw-chat-dashboard__card-icon">\u{1F4E8}</span>
                    <span class="sw-chat-dashboard__card-label">Direct Message</span>
                </button>
            </div>
            ${showDmPicker && html`
                <div class="sw-chat-dashboard__dm-picker">
                    <h3 class="sw-chat-dashboard__section-title">Start a DM</h3>
                    <${UserPicker}
                        onSelect=${_onDmSelect}
                        placeholder="Search for a user\u2026"
                        autoFocus=${true} />
                    <button class="btn-small"
                            style="margin-top: 8px;"
                            onClick=${() => setShowDmPicker(false)}>Cancel</button>
                </div>`}
            ${recentItems.length > 0 && html`
                <div class="sw-chat-dashboard__recent">
                    <h3 class="sw-chat-dashboard__section-title">Recent</h3>
                    <div class="sw-chat-dashboard__recent-list">
                        ${recentItems.map(ch => html`
                            <div class="sw-chat-dashboard__recent-item" key=${ch.id}
                                 onClick=${() => onNavigate?.(ch.id)}
                                 style="cursor: pointer">
                                <span class="sw-chat-dashboard__recent-icon">
                                    ${ch.type === 'channel' || ch.type === 'group' ? '#' : '\u{1F4AC}'}
                                </span>
                                <span class="sw-chat-dashboard__recent-title">${ch.title || 'Untitled'}</span>
                            </div>`)}
                    </div>
                </div>`}
        </div>`;
}
