import React from 'react';
import {
DndContext,
MouseSensor,
TouchSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
type Modifier,
} from '@dnd-kit/core';
import {
SortableContext,
horizontalListSortingStrategy,
useSortable,
} from '@dnd-kit/sortable';
import { CSS as DndCSS } from '@dnd-kit/utilities';
import type { Session } from '@opencode-ai/sdk/v2';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Icon } from '@/components/icon/Icon';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import { useSessionTabsStore } from '@/stores/useSessionTabsStore';
import { useGlobalSessionsStore, resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore';
import { useSessionUIStore } from '@/sync/session-ui-store';
const restrictToXAxis: Modifier = ({ transform }) => ({ ...transform, y: 0 });
type SessionTab = { id: string; session: Session };
export type SessionTabMenuArgs = {
session: Session;
isActive: boolean;
select: () => void;
closeOtherTabs: () => void;
};
/**
* One tab, active or not. The tab drags to reorder; the menu and close
* controls sit in a hover-revealed overlay at the tab's end (menu first,
* close after it). The single session menu is supplied by the header via
* `renderMenu`, bound to this tab's session; right-click opens it without
* changing which tab is active. The overlay stays visible until the menu's
* close animation completes, so the popup never loses its anchor mid-flight
* (that was the top-left corner flash).
*/
const SessionTabItem: React.FC<{
tab: SessionTab;
isActive: boolean;
onSelect: (tab: SessionTab) => void;
onClose: (id: string) => void;
renderMenu: (args: SessionTabMenuArgs) => React.ReactNode;
closeOtherTabs: (id: string) => void;
onMenuOpenChangeComplete?: (open: boolean) => void;
children?: React.ReactNode;
}> = ({ tab, isActive, onSelect, onClose, renderMenu, closeOtherTabs, onMenuOpenChangeComplete, children }) => {
const { t } = useI18n();
const [menuOpen, setMenuOpen] = React.useState(false);
// Keeps the overlay (the menu's anchor) mounted through the close animation.
const [menuVisible, setMenuVisible] = React.useState(false);
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: tab.id });
const title = tab.session.title?.trim() || t('sessions.sidebar.session.untitled');
const overlayVisible = menuOpen || menuVisible;
const openMenu = React.useCallback(() => {
setMenuVisible(true);
setMenuOpen(true);
}, []);
return (