"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
DndContext,
type DragEndEvent,
type DragMoveEvent,
DragOverlay,
type DragStartEvent,
PointerSensor,
useDraggable,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import {
Backpack,
Crosshair,
FlaskConical,
Gem,
Glasses,
Hammer,
Headset,
Luggage,
Monitor,
MoonStar,
Package,
Palette,
Shield,
Shirt,
Tag,
Target,
Wrench,
} from "lucide-react";
import type { Asset } from "@/payload-types";
import {
ATTACHMENT_CATEGORIES,
findLockerMergeTarget,
getLockerGridOccupancy,
getLockerItemFootprint,
isAttachmentCompatible,
isLockerPlacementValid,
type LockerGridItem,
type LockerItemEquipment,
resolveAssetId,
} from "@/lib/locker";
import { GridCell } from "@/components/frontend/storage/GridCell";
import type { ActionResult } from "@/app/(frontend)/locker/actions";
import { cn } from "@/lib/utils";
export function getAssetIcon(assetType: Asset["assetType"], className?: string) {
const cls = className ?? "size-4";
switch (assetType) {
case "weapon":
return ;
case "magazine":
return ;
case "optic":
return ;
case "muzzle":
return ;
case "bipod":
return ;
case "uniform":
return ;
case "vest":
return ;
case "backpack":
return ;
case "helmet":
return ;
case "facewear":
return ;
case "nvg":
return ;
case "radio":
return ;
case "medical":
return ;
case "tool":
return ;
case "explosive":
return ;
case "skin":
return ;
case "miscellaneous":
return ;
default:
return ;
}
}
function assetThumbnailUrl(asset: Asset): string | null {
const thumb = asset["Asset Metadata"]?.thumbnail;
if (thumb && typeof thumb === "object" && "url" in thumb) return thumb.url ?? null;
return null;
}
function itemContainsCell(item: LockerGridItem, x: number, y: number): boolean {
const fp = getLockerItemFootprint(item.asset, item.rotated);
return (
x >= item.gridX && x < item.gridX + fp.width && y >= item.gridY && y < item.gridY + fp.height
);
}
export function LockerItemFace({
asset,
quantity,
rotated,
cellSize,
equipment,
}: {
asset: Asset;
quantity: number;
rotated?: boolean;
cellSize: number;
equipment?: LockerItemEquipment;
}) {
const fp = getLockerItemFootprint(asset, rotated ?? false);
const thumb = assetThumbnailUrl(asset);
const displayName = equipment?.customName?.trim() || asset.name;
const hasCustomName = !!equipment?.customName?.trim();
const hasSkin = equipment?.skin != null;
const attachmentCount = equipment?.attachments?.length ?? 0;
return (
{/* Subtle selection glow */}
{(hasSkin || attachmentCount > 0 || hasCustomName) && (
)}
{(hasSkin || attachmentCount > 0 || hasCustomName) && (
{hasCustomName && (
)}
{hasSkin && (
)}
{attachmentCount > 0 && (
{attachmentCount}
)}
)}
{thumb ? (

) : (
{getAssetIcon(asset.assetType, "size-4")}
)}
{displayName}
{quantity > 1 && (
{quantity.toLocaleString()}
)}
);
}
function DraggableLockerItem({
item,
cellSize,
onSelect,
selected,
highlight,
}: {
item: LockerGridItem;
cellSize: number;
onSelect: (item: LockerGridItem) => void;
selected: boolean;
highlight?: boolean;
}) {
const didDrag = useRef(false);
const fp = getLockerItemFootprint(item.asset, item.rotated);
const displayName = item.equipment?.customName?.trim() || item.asset.name;
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: `grid-item-${item.id}`,
data: { item },
});
useEffect(() => {
if (isDragging) didDrag.current = true;
}, [isDragging]);
const handleClick = useCallback(
(e: React.MouseEvent) => {
if (!didDrag.current) {
e.stopPropagation();
onSelect(item);
}
didDrag.current = false;
},
[item, onSelect],
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
onSelect(item);
},
[item, onSelect],
);
const style: React.CSSProperties = {
position: "absolute",
left: item.gridX * cellSize,
top: item.gridY * cellSize,
width: fp.width * cellSize - 2,
height: fp.height * cellSize - 2,
zIndex: 10,
transition: isDragging ? "none" : "left 0.15s ease, top 0.15s ease",
transform: CSS.Translate.toString(transform),
opacity: isDragging ? 0 : 1,
};
return (
);
}
interface LockerGridProps {
gridWidth: number;
gridHeight: number;
items: LockerGridItem[];
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: LockerGridItem | null) => void;
selectedItem: LockerGridItem | null;
highlightId?: string | null;
onAttachItem?: (weaponEntryId: string, attachmentEntryId: string) => Promise;
}
export function LockerGrid({
gridWidth,
gridHeight,
items,
onMoveItem,
onMergeStacks,
onRotateItem,
onRemoveItem,
onSelectItem,
selectedItem,
highlightId,
onAttachItem,
}: LockerGridProps) {
const [activeItem, setActiveItem] = useState(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null);
const [pendingRotated, setPendingRotated] = useState(false);
const [dragError, setDragError] = useState(null);
const dragErrorTimer = useRef | null>(null);
const [cellSize, setCellSize] = useState(48);
const gridRef = useRef(null);
const containerRef = useRef(null);
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 items) {
const fp = getLockerItemFootprint(item.asset, 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;
}, [items]);
const occupancy = getLockerGridOccupancy(items, gridWidth, gridHeight);
const hoverInfo = useMemo(() => {
if (!hoverPosition || !activeItem) return null;
const fp = getLockerItemFootprint(activeItem.asset, pendingRotated);
const isAttachment = ATTACHMENT_CATEGORIES.some(
(c) => c.assetType === activeItem.asset.assetType,
);
const targetItem =
items.find(
(it) => it.id !== activeItem.id && itemContainsCell(it, hoverPosition.x, hoverPosition.y),
) ?? null;
const mergeTarget = findLockerMergeTarget(
items,
activeItem,
hoverPosition.x,
hoverPosition.y,
pendingRotated,
);
let mode: "move" | "merge" | "attach" = "move";
if (mergeTarget) {
mode = "merge";
} else if (
isAttachment &&
targetItem?.asset.assetType === "weapon" &&
isAttachmentCompatible(targetItem.asset, activeItem.asset)
) {
const alreadyInstalled = (targetItem.equipment?.attachments ?? []).some(
(a) => resolveAssetId(a.asset) === activeItem.assetId,
);
if (!alreadyInstalled) {
mode = "attach";
}
}
const cells = new Set();
if (mode === "attach" && targetItem) {
const tFp = getLockerItemFootprint(targetItem.asset, targetItem.rotated);
for (let dx = 0; dx < tFp.width; dx++) {
for (let dy = 0; dy < tFp.height; dy++) {
cells.add(`${targetItem.gridX + dx},${targetItem.gridY + dy}`);
}
}
} else {
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 valid =
mode !== "move" ||
isLockerPlacementValid(
items,
activeItem.id,
hoverPosition.x,
hoverPosition.y,
fp.width,
fp.height,
gridWidth,
gridHeight,
);
return { cells, valid, isAttachDrop: mode === "attach" };
}, [hoverPosition, activeItem, items, gridWidth, gridHeight, pendingRotated]);
const handleDragStart = useCallback((event: DragStartEvent) => {
const data = event.active.data.current;
if (data?.item) {
const item = data.item as LockerGridItem;
setActiveItem(item);
setPendingRotated(item.rotated ?? false);
}
setHoverPosition(null);
setDragError(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 LockerGridItem | 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 = findLockerMergeTarget(items, item, targetX, targetY, pendingRotated);
if (mergeTarget) {
await onMergeStacks(item.id, mergeTarget.id);
return;
}
if (onAttachItem) {
const isAttachment = ATTACHMENT_CATEGORIES.some(
(c) => c.assetType === item.asset.assetType,
);
const targetItem =
items.find((it) => it.id !== item.id && itemContainsCell(it, targetX, targetY)) ?? null;
if (
isAttachment &&
targetItem?.asset.assetType === "weapon" &&
isAttachmentCompatible(targetItem.asset, item.asset)
) {
const alreadyInstalled = (targetItem.equipment?.attachments ?? []).some(
(a) => resolveAssetId(a.asset) === item.assetId,
);
if (!alreadyInstalled) {
const result = await onAttachItem(targetItem.id, item.id);
if (!result.success && result.error) {
setDragError(result.error);
if (dragErrorTimer.current) clearTimeout(dragErrorTimer.current);
dragErrorTimer.current = setTimeout(() => setDragError(null), 5000);
}
return;
}
}
}
const fp = getLockerItemFootprint(item.asset, pendingRotated);
const valid = isLockerPlacementValid(
items,
item.id,
targetX,
targetY,
fp.width,
fp.height,
gridWidth,
gridHeight,
);
if (valid) {
await onMoveItem(item.id, targetX, targetY, pendingRotated);
}
},
[
items,
gridWidth,
gridHeight,
onMoveItem,
onMergeStacks,
onAttachItem,
cellSize,
pendingRotated,
],
);
const handleBackgroundClick = useCallback(() => {
onSelectItem(null);
}, [onSelectItem]);
// Drag preview must track mid-drag rotation: dnd-kit pins the overlay
// container to the activator rect captured at drag start, so we override
// its width/height via the style prop (spread after the pinned rect).
const overlayFp = activeItem
? getLockerItemFootprint(activeItem.asset, pendingRotated)
: null;
return (
{/* Tactical grid frame */}
{Array.from({ length: gridHeight }, (_, y) =>
Array.from({ length: gridWidth }, (_, x) => {
const key = `${x},${y}`;
return (
);
}),
)}
{items.filter((item) => item.quantity >= 1).map((item) => (
))}
{/* Tactical metadata strip */}
USAGE
:
{occupancy.used} / {occupancy.total}
GRID
:
{gridWidth}×{gridHeight}
SELECT to inspect · DRAG to move · R to rotate
{dragError && (
{dragError}
)}
{/* Tactical drag overlay */}
{activeItem && (
)}
);
}