import { useState } from 'react';
import { Brain, ChevronRight, Plus, Archive, Check } from 'lucide-react';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { getPersonaById } from '@/lib/personas';
import { useFocusTrap } from '@/hooks/useFocusTrap';
import type { Workspace } from '@/lib/types';
import { motion, AnimatePresence } from 'framer-motion';
import WorkspaceActionsMenu from '../WorkspaceActionsMenu';
import { isDevNoiseWorkspace, compareWorkspaceRecency, workspaceCounts } from '@/lib/workspace-counts';
interface WorkspaceSwitcherProps {
open: boolean;
onClose: () => void;
workspaces: Workspace[];
activeWorkspaceId: string | null;
onSelect: (id: string) => void;
/** G1 (UX-Northstar 2026-06-13): create from the switcher itself. */
onCreateNew?: () => void;
/** W2B: jump to the full workspace shelf when the switcher is capped. */
onViewAll?: () => void;
/** P1b D3: load failure — an errored empty list must not read as "No workspaces". */
error?: string | null;
onRetry?: () => void;
}
// W2B: cap the un-searchable switcher list so the ~55-row store doesn't flood a
// 256px scrollbox; the rest is one click away via "view all".
const MAX_SWITCHER_ROWS = 12;
/** Compact relative time — disambiguates same-named workspaces (issue 2b). */
function relativeTime(iso?: string): string | null {
if (!iso) return null;
const t = new Date(iso).getTime();
if (Number.isNaN(t)) return null;
const mins = Math.round((Date.now() - t) / 60_000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hrs = Math.round(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.round(hrs / 24);
if (days < 7) return `${days}d ago`;
return `${Math.round(days / 7)}w ago`;
}
function WorkspaceRow({ ws, isActive, isDuplicateName, onSelect }: {
ws: Workspace;
isActive: boolean;
/** True when another visible workspace shares this name — show a date subtitle. */
isDuplicateName: boolean;
onSelect: (id: string) => void;
}) {
const persona = ws.persona ? getPersonaById(ws.persona) : null;
// On a name collision, append last-active so two "Research Hub"s differ.
const rel = isDuplicateName ? relativeTime(ws.lastActive ?? ws.updatedAt) : null;
// Never render an empty subtitle row: prefer "group · rel", fall back to whichever exists.
const subtitle = rel ? (ws.group ? `${ws.group} · ${rel}` : rel) : (ws.group || null);
return (
);
}
const WorkspaceSwitcher = ({ open, onClose, workspaces, activeWorkspaceId, onSelect, onCreateNew, onViewAll, error, onRetry }: WorkspaceSwitcherProps) => {
const [showArchived, setShowArchived] = useState(false);
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped within the dialog,
// focus moves in on open and restores on close — the same shared hook the
// other modal overlays use. Replaces the prior Escape-only handler (which
// had no focus trap or restore, so keyboard users tabbed out into the shell).
const dialogRef = useFocusTrap(open, onClose);
if (!open) return null;
const visibleWorkspaces = workspaces.filter(
ws => ws.id === activeWorkspaceId || !isDevNoiseWorkspace(ws.name),
);
// W2B: recency-sorted (most recent first, missing timestamps last), then
// capped so the un-searchable list can't flood the scrollbox.
const activeListFull = visibleWorkspaces
.filter(ws => ws.status !== 'archived')
.sort(compareWorkspaceRecency);
const activeList = activeListFull.slice(0, MAX_SWITCHER_ROWS);
const hiddenCount = activeListFull.length - activeList.length;
const totalCount = workspaceCounts(workspaces).total;
const archivedList = visibleWorkspaces.filter(ws => ws.status === 'archived');
// Names shared by more than one visible workspace — those rows get a date
// subtitle so they're tellable apart (issue 2b).
const nameCounts = new Map();
for (const ws of visibleWorkspaces) {
const k = ws.name.trim().toLowerCase();
nameCounts.set(k, (nameCounts.get(k) ?? 0) + 1);
}
const isDup = (ws: Workspace) => (nameCounts.get(ws.name.trim().toLowerCase()) ?? 0) > 1;
return (
e.stopPropagation()}
>
Switch Workspace
One workspace per project or area. Each remembers its own work.
{activeList.map(ws => (
{ onSelect(id); onClose(); }}
/>
))}
{hiddenCount > 0 && (
)}
{visibleWorkspaces.length === 0 && (
error ? (
Couldn’t load workspaces. Retrying when the connection is back.
{onRetry && (
)}
) : (
No workspaces
)
)}
{archivedList.length > 0 && (
{showArchived && archivedList.map(ws => (
{ onSelect(id); onClose(); }}
/>
))}
)}
{onCreateNew && (
)}
Ctrl+Tab to toggle
);
};
export default WorkspaceSwitcher;