import { useEffect, useRef, useState } from 'react';
import {
DndContext,
DragOverlay,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragStartEvent,
type DragEndEvent,
type DragMoveEvent,
} from '@dnd-kit/core';
import { SortableContext, horizontalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
import { toast } from 'sonner';
import { useRackStore } from '../../store/useRackStore';
import { apiClient } from '../../api/client';
import { RackToolbar } from './RackToolbar';
import { RackColumn } from './RackColumn';
import { DevicePalette } from './DevicePalette';
import { AddModuleModal } from '../modals/AddModuleModal';
import { RackSkeleton } from '../ui/Skeleton';
import type { ModuleType } from '../../types';
import { MODULE_TYPE_COLORS, MODULE_TYPE_LABELS } from '../../lib/constants';
import { cn } from '../../lib/utils';
interface PendingDrop {
rackId: string;
uPosition: number;
type: ModuleType;
}
interface HoverSlot {
rackId: string;
uPosition: number;
}
function DragOverlayItem({ type }: { type: ModuleType }) {
const colors = MODULE_TYPE_COLORS[type];
return (
{MODULE_TYPE_LABELS[type]}
);
}
function ModuleDragOverlay({ label }: { label: string }) {
return (
{label}
);
}
/**
* Resolve which rack slot (if any) is under the pointer during a drag.
*
* Strategy: elementFromPoint at the current pointer coordinates.
* - ModuleBlock has pointer-events:none when isDragging, so it is transparent.
* - DragOverlay has pointer-events:none natively (dnd-kit).
* - RackSlot divs carry data-rack-id / data-u-pos attributes that we read here.
*
* This is intentionally independent of dnd-kit's collision detection, which
* cannot reliably distinguish 44px slot elements from large (~1800px) rack
* column sortable containers that share the same DndContext.
*/
function resolveSlotFromPoint(clientX: number, clientY: number): HoverSlot | null {
const el = document.elementFromPoint(clientX, clientY);
if (!el) return null;
const slotEl = el.closest('[data-rack-id][data-u-pos]') as HTMLElement | null;
if (!slotEl) return null;
const rackId = slotEl.dataset.rackId;
const uPos = parseInt(slotEl.dataset.uPos ?? '', 10);
if (!rackId || isNaN(uPos)) return null;
return { rackId, uPosition: uPos };
}
export function RackPlanner() {
const { racks, loading, fetchRacks, moveModule } = useRackStore();
const canvasRef = useRef(null);
// Drag state
const [activePaletteType, setActivePaletteType] = useState(null);
const [activeDragModuleLabel, setActiveDragModuleLabel] = useState(null);
const [draggingModuleId, setDraggingModuleId] = useState(null);
const [pendingDrop, setPendingDrop] = useState(null);
// hoverSlot drives the blue highlight on slots during drag.
// hoverSlotRef is the reliable read-path inside async handleDragEnd
// (avoids stale-closure issues with state).
const [hoverSlot, setHoverSlot] = useState(null);
const hoverSlotRef = useRef(null);
function updateHoverSlot(slot: HoverSlot | null) {
hoverSlotRef.current = slot;
setHoverSlot(slot);
}
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } })
);
useEffect(() => {
fetchRacks().catch(() => toast.error('Failed to load racks'));
}, [fetchRacks]);
function handleDragStart(event: DragStartEvent) {
const data = event.active.data.current as Record;
if (data?.dragType === 'palette') {
setActivePaletteType(data.type as ModuleType);
} else if (data?.dragType === 'module') {
setDraggingModuleId(data.moduleId as string);
setActiveDragModuleLabel(data.label as string);
}
updateHoverSlot(null);
}
function handleDragMove(event: DragMoveEvent) {
const data = event.active.data.current as Record;
// Only track slot hover for module and palette drags
if (data?.dragType !== 'module' && data?.dragType !== 'palette') {
updateHoverSlot(null);
return;
}
// Compute current pointer position from the activating event + accumulated delta
const activatorEvent = event.activatorEvent as PointerEvent;
const clientX = activatorEvent.clientX + event.delta.x;
const clientY = activatorEvent.clientY + event.delta.y;
updateHoverSlot(resolveSlotFromPoint(clientX, clientY));
}
async function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
// Capture hoverSlot BEFORE resetting state
const slot = hoverSlotRef.current;
setActivePaletteType(null);
setActiveDragModuleLabel(null);
setDraggingModuleId(null);
updateHoverSlot(null);
const dragData = active.data.current as Record;
// --- Palette → slot: open AddModuleModal pre-filled ---
if (dragData?.dragType === 'palette' && slot) {
setPendingDrop({
type: dragData.type as ModuleType,
rackId: slot.rackId,
uPosition: slot.uPosition,
});
return;
}
// --- Module → slot: move the module ---
if (dragData?.dragType === 'module' && slot) {
const moduleId = dragData.moduleId as string;
// No-op if dropped on own position
if (dragData.fromRackId === slot.rackId && dragData.fromUPosition === slot.uPosition) return;
try {
await moveModule(moduleId, slot.rackId, slot.uPosition);
toast.success('Module moved');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Move failed');
}
return;
}
// --- Rack header → rack header: reorder racks ---
if (!over) return;
const dropData = over.data.current as Record | undefined;
if (dragData?.dragType === 'rack' && dropData?.dragType === 'rack') {
const oldIndex = racks.findIndex((r) => r.id === active.id);
const newIndex = racks.findIndex((r) => r.id === over.id);
if (oldIndex === newIndex) return;
const reordered = arrayMove(racks, oldIndex, newIndex);
try {
await Promise.all(
reordered.map((rack, idx) =>
rack.displayOrder !== idx
? apiClient.racks.update(rack.id, { displayOrder: idx })
: Promise.resolve(rack)
)
);
await fetchRacks();
} catch {
toast.error('Failed to save rack order');
await fetchRacks();
}
}
}
const rackIds = racks.map((r) => r.id);
return (
{loading ? (
) : racks.length === 0 ? (
No racks yet
Click Add Rack in the toolbar to create your first rack.
) : (
{racks.map((rack) => (
))}
)}
{activePaletteType && }
{activeDragModuleLabel && }
{pendingDrop && (
setPendingDrop(null)}
rackId={pendingDrop.rackId}
uPosition={pendingDrop.uPosition}
initialType={pendingDrop.type}
/>
)}
);
}