// ==========================================
// Chat Surface — Root Component
// ==========================================
// Main chat surface: sidebar + workspace.
// Follows the settings/admin mount pattern.
//
// v0.37.10: New Preact surface replacing the legacy SPA.

import { ToastContainer } from '../../primitives/toast.js';
import { DialogStack }    from '../../shell/dialog-stack.js';
import { useWorkspace }   from './use-workspace.js';
import { useSidebar }     from './use-sidebar.js';
import { Sidebar }        from './sidebar.js';
import { ChatWorkspace }  from './chat-workspace.js';
import { useTools, ToolsPopup } from './tools-popup.js';

const { render } = window.preact;
const html = window.html;
const { useState, useCallback } = window.hooks;

const WRENCH_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="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0
                 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1
                 7.94-7.94l-3.76 3.76z"/>
    </svg>`;

function ChatSurface() {
    const workspace = useWorkspace();
    const sidebar = useSidebar({ activeId: workspace.activeId });
    const tools = useTools();
    const [toolsOpen, setToolsOpen] = useState(false);

    const _onNewChat = useCallback(async () => {
        try {
            const resp = await window.sw.api.channels.create({ type: 'direct', title: 'New Chat' });
            const ch = resp;
            if (ch?.id) {
                sidebar.reload();
                workspace.select(ch.id, 'direct');
            }
        } catch (err) {
            console.error('[chat] New chat failed:', err);
            window.sw?.toast?.('Failed to create chat', 'error');
        }
    }, [workspace.select, sidebar.reload]);

    const _onCreateChannel = useCallback(async (type, title, opts) => {
        try {
            const body = { type, title };
            if (opts?.participant) body.participants = [opts.participant];
            const resp = await window.sw.api.channels.create(body);
            const ch = resp;
            if (ch?.id) {
                sidebar.reload();
                workspace.select(ch.id, type);
            }
        } catch (err) {
            console.error('[chat] Create channel failed:', err);
            window.sw?.toast?.('Failed to create ' + type, 'error');
        }
    }, [workspace.select, sidebar.reload]);

    const _onDeleteChat = useCallback(async (id) => {
        await sidebar.deleteChat(id);
        if (id === workspace.activeId) workspace.clearSelection();
    }, [sidebar.deleteChat, workspace.activeId, workspace.clearSelection]);

    const _onChannelChange = useCallback((id) => {
        if (id) workspace.select(id, 'direct');
        else workspace.clearSelection();
    }, [workspace.select, workspace.clearSelection]);

    const _toggleSidebar = useCallback(() => {
        workspace.setSidebarOpen(!workspace.sidebarOpen);
    }, [workspace.sidebarOpen, workspace.setSidebarOpen]);

    const _toggleTools = useCallback(() => {
        setToolsOpen(v => !v);
    }, []);

    const _closeTools = useCallback(() => {
        setToolsOpen(false);
    }, []);

    // Tools button — shared between mobile bar and workspace header
    const toolsButton = html`
        <button class="sw-chat-surface__tools-btn"
                onClick=${_toggleTools}
                title="Tools"
                aria-label="Toggle tools"
                aria-expanded=${toolsOpen}>
            ${WRENCH_SVG}
            ${tools.disabled.size > 0 && html`
                <span class="sw-chat-surface__tools-badge">${tools.disabled.size}</span>`}
        </button>`;

    return html`
        <div class="sw-chat-surface">
            ${/* Mobile sidebar overlay */''}
            ${workspace.sidebarOpen && html`
                <div class="sw-chat-surface__sidebar-overlay"
                     onClick=${_toggleSidebar} />`}

            ${/* Sidebar */''}
            ${workspace.sidebarOpen && html`
                <${Sidebar}
                    sidebar=${sidebar}
                    activeId=${workspace.activeId}
                    onSelect=${workspace.select}
                    onNewChat=${_onNewChat}
                    onCreateChannel=${_onCreateChannel}
                    onDeleteChat=${_onDeleteChat}
                    onCollapse=${_toggleSidebar} />`}

            ${/* Main workspace */''}
            <div class="sw-chat-surface__main">
                <${ChatWorkspace}
                    activeId=${workspace.activeId}
                    activeType=${workspace.activeType}
                    channelType=${workspace.channelType}
                    onChannelChange=${_onChannelChange}
                    onNewChat=${_onNewChat}
                    onCreateChannel=${_onCreateChannel}
                    sidebarOpen=${workspace.sidebarOpen}
                    onToggleSidebar=${_toggleSidebar}
                    toolsButton=${toolsButton}
                    sidebar=${sidebar} />
                <${ToolsPopup}
                    open=${toolsOpen}
                    onClose=${_closeTools}
                    categories=${tools.categories}
                    disabled=${tools.disabled}
                    onToggle=${tools.toggle}
                    onToggleCategory=${tools.toggleCategory} />
            </div>
        </div>
        <${ToastContainer} />
        <${DialogStack} />
    `;
}

// ── Mount ────────────────────────────────────
const mount = document.getElementById('chat-mount');
if (mount) {
    render(html`<${ChatSurface} />`, mount);
    console.log('[chat] Surface mounted (v0.37.10)');
}

export { ChatSurface };
