'use client'; import { useState, useRef, useEffect } from 'react'; import { useEncryptID } from '@encryptid/sdk/ui/react'; interface SpaceInfo { slug: string; name: string; icon?: string; role?: string; } interface SpaceSwitcherProps { current?: string; name?: string; } export function SpaceSwitcher({ current = 'personal', name }: SpaceSwitcherProps) { const [open, setOpen] = useState(false); const [spaces, setSpaces] = useState([]); const [loaded, setLoaded] = useState(false); const ref = useRef(null); const { isAuthenticated } = useEncryptID(); useEffect(() => { function handleClick(e: MouseEvent) { if (ref.current && !ref.current.contains(e.target as Node)) { setOpen(false); } } document.addEventListener('click', handleClick); return () => document.removeEventListener('click', handleClick); }, []); const loadSpaces = async () => { if (loaded) return; try { const res = await fetch('/api/spaces'); if (res.ok) { const data = await res.json(); setSpaces(data.spaces || []); } } catch { // API not available — show empty } setLoaded(true); }; const handleOpen = async () => { const nowOpen = !open; setOpen(nowOpen); if (nowOpen && !loaded) { await loadSpaces(); } }; const displayName = name || current; const mySpaces = spaces.filter((s) => s.role); const publicSpaces = spaces.filter((s) => !s.role); return (
{open && (
{!loaded ? (
Loading spaces...
) : spaces.length === 0 ? ( <>
{isAuthenticated ? 'No spaces yet' : 'Sign in to see your spaces'}
setOpen(false)} > + Create new space ) : ( <> {mySpaces.length > 0 && ( <>
Your spaces
{mySpaces.map((s) => ( setOpen(false)} > {s.icon || '🌐'} {s.name} {s.role && ( {s.role} )} ))} )} {publicSpaces.length > 0 && ( <> {mySpaces.length > 0 &&
}
Public spaces
{publicSpaces.map((s) => ( setOpen(false)} > {s.icon || '🌐'} {s.name} ))} )} )}
); }