"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { DndContext, type DragEndEvent, type DragMoveEvent, DragOverlay, type DragStartEvent, PointerSensor, useSensor, useSensors, } from "@dnd-kit/core"; import { GameStructure, Resource, Structure } from "@/payload-types"; import { getGridOccupancy, getItemFootprint, type GridItem, isValidPlacement, } from "@/lib/logistics"; import { GridItemComponent } from "./GridItem"; import { GridCell } from "./GridCell"; function DragOverlayContent({ item, cellSize, rotated, }: { item: GridItem; cellSize: number; rotated?: boolean; }) { const resource = item.resource as Resource; const effective = rotated ?? item.rotated; const { width, height } = getItemFootprint(resource, effective); const bgColor = resource.color ?? "oklch(0.269 0 0)"; return (
{resource.icon && typeof resource.icon === "object" && "url" in resource.icon && ( {resource.name} )} {resource.name} {item.amount > 1 && ( {item.amount.toLocaleString()} )}
); } function findMergeTarget( items: GridItem[], dragged: GridItem, targetX: number, targetY: number, rotated?: boolean, ): GridItem | null { const effective = rotated ?? dragged.rotated; const fp = getItemFootprint(dragged.resource as Resource, effective); const targetCells = new Set(); for (let dx = 0; dx < fp.width; dx++) { for (let dy = 0; dy < fp.height; dy++) { targetCells.add(`${targetX + dx},${targetY + dy}`); } } for (const other of items) { if (other.id === dragged.id) continue; if (other.resourceId !== dragged.resourceId) continue; const otherFp = getItemFootprint(other.resource as Resource, other.rotated); for (let dx = 0; dx < otherFp.width; dx++) { for (let dy = 0; dy < otherFp.height; dy++) { if (targetCells.has(`${other.gridX + dx},${other.gridY + dy}`)) { return other; } } } } return null; } interface InventoryGridProps { structure: GameStructure & { type: Structure }; storedResources: GridItem[]; onMoveItem: (entryId: string, gridX: number, gridY: number, rotated?: boolean) => Promise; onMergeStacks: (sourceId: string, targetId: string) => Promise; onRotateItem: (entryId: string) => Promise; onRemoveItem: (entryId: string) => Promise; onSelectItem: (item: GridItem | null) => void; selectedItem: GridItem | null; } export function InventoryGrid({ structure, storedResources, onMoveItem, onMergeStacks, onRotateItem, onRemoveItem, onSelectItem, selectedItem, }: InventoryGridProps) { const [activeItem, setActiveItem] = useState(null); const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null); const [pendingRotated, setPendingRotated] = useState(false); const [cellSize, setCellSize] = useState(48); const gridRef = useRef(null); const containerRef = useRef(null); const gridWidth = structure.type.xSize ?? 1; const gridHeight = structure.type.ySize ?? 1; useEffect(() => { const el = containerRef.current; if (!el) return; const observer = new ResizeObserver((entries) => { for (const entry of entries) { const w = entry.contentRect.width; const computed = Math.floor(w / gridWidth); setCellSize(Math.max(32, Math.min(computed, 80))); } }); observer.observe(el); return () => observer.disconnect(); }, [gridWidth]); useEffect(() => { if (!activeItem) return; const onKey = (e: KeyboardEvent) => { if (e.key === "r" || e.key === "R") { e.preventDefault(); setPendingRotated((v) => !v); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [activeItem]); const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 5 }, }), ); const occupiedCells = useMemo(() => { const cells = new Set(); for (const item of storedResources) { const fp = getItemFootprint(item.resource as Resource, item.rotated); for (let dx = 0; dx < fp.width; dx++) { for (let dy = 0; dy < fp.height; dy++) { cells.add(`${item.gridX + dx},${item.gridY + dy}`); } } } return cells; }, [storedResources]); const occupancy = getGridOccupancy(storedResources, gridWidth, gridHeight); const hoverInfo = useMemo(() => { if (!hoverPosition || !activeItem) return null; const res = activeItem.resource as Resource; const fp = getItemFootprint(res, pendingRotated); const cells = new Set(); for (let dx = 0; dx < fp.width; dx++) { for (let dy = 0; dy < fp.height; dy++) { cells.add(`${hoverPosition.x + dx},${hoverPosition.y + dy}`); } } const mergeTarget = findMergeTarget( storedResources, activeItem, hoverPosition.x, hoverPosition.y, pendingRotated, ); const valid = mergeTarget !== null || isValidPlacement( storedResources, activeItem.id, hoverPosition.x, hoverPosition.y, fp.width, fp.height, gridWidth, gridHeight, ); return { cells, valid }; }, [hoverPosition, activeItem, storedResources, gridWidth, gridHeight, pendingRotated]); const handleDragStart = useCallback((event: DragStartEvent) => { const data = event.active.data.current; if (data?.item) { const item = data.item as GridItem; setActiveItem(item); setPendingRotated(item.rotated ?? false); } setHoverPosition(null); }, []); const handleDragMove = useCallback( (event: DragMoveEvent) => { const { activatorEvent, delta } = event; const gridEl = gridRef.current; if (!gridEl) return; const rect = gridEl.getBoundingClientRect(); if (!("clientX" in activatorEvent)) return; const px = (activatorEvent as PointerEvent).clientX + delta.x; const py = (activatorEvent as PointerEvent).clientY + delta.y; const x = Math.floor((px - rect.left) / cellSize); const y = Math.floor((py - rect.top) / cellSize); if (x < 0 || y < 0 || x >= gridWidth || y >= gridHeight) { setHoverPosition(null); return; } setHoverPosition({ x, y }); }, [gridWidth, gridHeight, cellSize], ); const handleDragEnd = useCallback( async (event: DragEndEvent) => { setActiveItem(null); setHoverPosition(null); const { active, activatorEvent, delta } = event; const item = active.data.current?.item as GridItem | undefined; if (!item) return; const gridEl = gridRef.current; if (!gridEl) return; const rect = gridEl.getBoundingClientRect(); if (!("clientX" in activatorEvent)) return; const px = (activatorEvent as PointerEvent).clientX + delta.x; const py = (activatorEvent as PointerEvent).clientY + delta.y; const targetX = Math.floor((px - rect.left) / cellSize); const targetY = Math.floor((py - rect.top) / cellSize); if (targetX < 0 || targetY < 0 || targetX >= gridWidth || targetY >= gridHeight) return; if (targetX === item.gridX && targetY === item.gridY) { if (pendingRotated === item.rotated) return; await onMoveItem(item.id, targetX, targetY, pendingRotated); return; } const mergeTarget = findMergeTarget(storedResources, item, targetX, targetY, pendingRotated); if (mergeTarget) { await onMergeStacks(item.id, mergeTarget.id); return; } const res = item.resource as Resource; const fp = getItemFootprint(res, pendingRotated); const valid = isValidPlacement( storedResources, item.id, targetX, targetY, fp.width, fp.height, gridWidth, gridHeight, ); if (valid) { await onMoveItem(item.id, targetX, targetY, pendingRotated); } }, [storedResources, gridWidth, gridHeight, onMoveItem, onMergeStacks, cellSize, pendingRotated], ); const handleBackgroundClick = useCallback(() => { onSelectItem(null); }, [onSelectItem]); return (
{Array.from({ length: gridHeight }, (_, y) => Array.from({ length: gridWidth }, (_, x) => { const key = `${x},${y}`; return ( ); }), )} {storedResources.map((item) => ( ))}
{occupancy.used} / {occupancy.total} cells used {gridWidth} x {gridHeight}
{ // dnd-kit pins the overlay container to the activator rect // from drag start; override width/height so mid-drag rotation // resizes the preview (style is spread after the pinned rect). const fp = getItemFootprint(activeItem.resource as Resource, pendingRotated); return { width: fp.width * cellSize - 2, height: fp.height * cellSize - 2 }; })() : undefined } > {activeItem && ( )}
); }