// ==========================================
// Chat Surface — useWorkspace Hook
// ==========================================
// Coordinator hook: manages active conversation, sidebar state.
// Persists active selection to sessionStorage for reload restore.

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

const STORAGE_KEY = 'sw-chat-active';

/**
 * @returns {{
 *   activeId: string|null,
 *   activeType: 'chat'|'channel'|null,
 *   sidebarOpen: boolean,
 *   setSidebarOpen: (v: boolean) => void,
 *   selectChat: (id: string) => void,
 *   selectChannel: (id: string) => void,
 *   clearSelection: () => void,
 * }}
 */
export function useWorkspace() {
    // Restore from sessionStorage
    const stored = _loadStored();
    const [activeId, setActiveId] = useState(stored.id);
    const [activeType, setActiveType] = useState(stored.type);
    const [channelType, setChannelType] = useState(stored.channelType || null);
    const [sidebarOpen, setSidebarOpen] = useState(true);

    // Persist on change
    useEffect(() => {
        if (activeId) {
            try {
                sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ id: activeId, type: activeType, channelType }));
            } catch (_) {}
        } else {
            sessionStorage.removeItem(STORAGE_KEY);
        }
    }, [activeId, activeType, channelType]);

    const select = useCallback((id, chType) => {
        setActiveId(id);
        setChannelType(chType || 'direct');
        // Map channel model type to workspace type
        const wsType = (chType === 'channel' || chType === 'group') ? 'channel' : 'chat';
        setActiveType(wsType);
        // Auto-close sidebar on mobile
        if (window.innerWidth < 768) setSidebarOpen(false);
    }, []);

    // Keep legacy aliases for any other callers
    const selectChat = useCallback((id) => select(id, 'direct'), [select]);
    const selectChannel = useCallback((id) => select(id, 'channel'), [select]);

    const clearSelection = useCallback(() => {
        setActiveId(null);
        setActiveType(null);
        setChannelType(null);
    }, []);

    return {
        activeId,
        activeType,
        channelType,
        sidebarOpen,
        setSidebarOpen,
        select,
        selectChat,
        selectChannel,
        clearSelection,
    };
}

function _loadStored() {
    try {
        const raw = sessionStorage.getItem(STORAGE_KEY);
        if (raw) {
            const obj = JSON.parse(raw);
            return { id: obj.id || null, type: obj.type || null, channelType: obj.channelType || null };
        }
    } catch (_) {}
    return { id: null, type: null, channelType: null };
}
