"use client";
import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react";
import {
DndContext,
type DragEndEvent,
type DragMoveEvent,
type DragStartEvent,
DragOverlay,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import { useDraggable } from "@dnd-kit/core";
import { ShieldAlert, Truck as TruckIcon } from "lucide-react";
import { GridCell } from "@/components/frontend/storage/GridCell";
import { cn } from "@/lib/utils";
/**
* Garage vehicle bay grid. Modeled on storage/InventoryGrid and
* locker/LockerGrid (dnd-kit, hover cell preview, R-to-rotate), but items are
* vehicle instances with per-template footprints. Dragging ONLY rearranges
* cells (server action moveGarageItem); real game movement is the explicit
* Dispatch/Store actions in GarageView. Dense data UI: plain shadcn + site
* dark theme, no dossier styling (D12).
*/
export interface GarageVehicleItem {
/** game-vehicles instance id. */
id: number;
name: string;
status: "idle" | "assigned" | "in_transit" | "damaged" | "destroyed";
gridX: number;
gridY: number;
rotated: boolean;
/** Template footprint at rotation 0. */
width: number;
height: number;
thumbnailUrl: string | null;
fuelPct: number | null;
healthPct: number | null;
/** Operation label when actively reserved ("Reserved for op X" badge). */
reservedFor?: string | null;
}
function footprint(item: { width: number; height: number; rotated: boolean }) {
return item.rotated
? { width: item.height, height: item.width }
: { width: item.width, height: item.height };
}
function cellsOf(x: number, y: number, w: number, h: number): string[] {
const cells: string[] = [];
for (let dx = 0; dx < w; dx++) {
for (let dy = 0; dy < h; dy++) {
cells.push(`${x + dx},${y + dy}`);
}
}
return cells;
}
function isPlacementValid(
items: GarageVehicleItem[],
excludeId: number,
x: number,
y: number,
w: number,
h: number,
gridWidth: number,
gridHeight: number,
): boolean {
if (x < 0 || y < 0 || x + w > gridWidth || y + h > gridHeight) return false;
const target = new Set(cellsOf(x, y, w, h));
for (const item of items) {
if (item.id === excludeId) continue;
const fp = footprint(item);
for (const cell of cellsOf(item.gridX, item.gridY, fp.width, fp.height)) {
if (target.has(cell)) return false;
}
}
return true;
}
/** Status tinting for the vehicle face (A4: destroyed stays visible, tinted). */
function statusTint(status: GarageVehicleItem["status"]): string | null {
switch (status) {
case "destroyed":
return "bg-red-500/40";
case "damaged":
return "bg-amber-500/30";
case "in_transit":
return "bg-sky-500/20";
default:
return null;
}
}
export function VehicleFace({
item,
cellSize,
dragging,
}: {
item: GarageVehicleItem;
cellSize: number;
dragging?: boolean;
}) {
const fp = footprint(item);
const cardW = fp.width * cellSize - 2;
const cardH = fp.height * cellSize - 2;
// Thumbnail caps are applied PRE-rotation, so for rotated cards the long
// edge must be capped by the card's HEIGHT (it becomes vertical after the
// 90deg turn) and vice versa. Pixel math, since % would resolve against
// the wrong axis of the already-rotated card. The rotated image is taken
// out of flow and anchored to the card centre so the 90deg turn happens
// around the card's middle (an in-flow image would rotate around its own
// top-biased box and clip against the card edge).
const thumbStyle: CSSProperties = item.rotated
? {
position: "absolute",
left: "50%",
top: "50%",
width: Math.floor(cardH * 0.85),
height: Math.floor(cardW * 0.85),
objectFit: "contain",
transform: "translate(-50%, -50%) rotate(90deg)",
}
: {
maxWidth: Math.floor(cardW * 0.85),
maxHeight: Math.floor(cardH * 0.55),
};
return (
{item.thumbnailUrl ? (
// eslint-disable-next-line @next/next/no-img-element

) : (
)}
{item.name}
{statusTint(item.status) && (
)}
{item.status === "destroyed" && (
)}
{item.reservedFor ? (
OP
) : null}
);
}
function DraggableVehicle({
item,
cellSize,
selected,
onSelect,
}: {
item: GarageVehicleItem;
cellSize: number;
selected: boolean;
onSelect: (item: GarageVehicleItem) => void;
}) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: `garage-item-${item.id}`,
data: { item },
});
const didDrag = useRef(false);
useEffect(() => {
if (isDragging) didDrag.current = true;
}, [isDragging]);
const fp = footprint(item);
return (
);
}
interface GarageGridProps {
gridWidth: number;
gridHeight: number;
items: GarageVehicleItem[];
canEdit: boolean;
onMoveItem: (
vehicleId: number,
gridX: number,
gridY: number,
rotated?: boolean,
) => Promise;
onSelectItem: (item: GarageVehicleItem | null) => void;
selectedItem: GarageVehicleItem | null;
}
export function GarageGrid({
gridWidth,
gridHeight,
items,
canEdit,
onMoveItem,
onSelectItem,
selectedItem,
}: GarageGridProps) {
const [activeItem, setActiveItem] = useState(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null);
const [pendingRotated, setPendingRotated] = useState(false);
const [cellSize, setCellSize] = useState(64);
const gridRef = useRef(null);
const containerRef = useRef(null);
// Chrome between the measured wrapper and the grid: the inventory frame's
// p-2 padding (8+8) plus its 1px borders (1+1).
const FRAME_CHROME_PX = 18;
// Responsive cell size: always fit the bay width into the container (the
// grid must never overflow, so no scrollbar can appear). The small floor is
// a legibility guard only; realistic containers never reach it.
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const observer = new ResizeObserver((entries) => {
const width = entries[0]?.contentRect.width ?? 0;
if (width > FRAME_CHROME_PX) {
setCellSize(
Math.max(24, Math.min(96, Math.floor((width - FRAME_CHROME_PX) / gridWidth))),
);
}
});
observer.observe(el);
return () => observer.disconnect();
}, [gridWidth]);
// R rotates the dragged vehicle while dragging (same gesture as locker).
useEffect(() => {
if (!activeItem) return;
const handler = (e: KeyboardEvent) => {
if (e.key === "r" || e.key === "R") {
e.preventDefault();
setPendingRotated((prev) => !prev);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [activeItem]);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
const occupiedCells = useMemo(() => {
const set = new Set();
for (const item of items) {
const fp = footprint(item);
for (const cell of cellsOf(item.gridX, item.gridY, fp.width, fp.height)) {
set.add(cell);
}
}
return set;
}, [items]);
const hoverInfo = useMemo(() => {
if (!activeItem || !hoverPosition) return null;
const w = pendingRotated ? activeItem.height : activeItem.width;
const h = pendingRotated ? activeItem.width : activeItem.height;
const valid = isPlacementValid(
items,
activeItem.id,
hoverPosition.x,
hoverPosition.y,
w,
h,
gridWidth,
gridHeight,
);
return { cells: new Set(cellsOf(hoverPosition.x, hoverPosition.y, w, h)), valid };
}, [activeItem, hoverPosition, pendingRotated, items, gridWidth, gridHeight]);
const handleDragStart = (event: DragStartEvent) => {
const item = event.active.data.current?.item as GarageVehicleItem | undefined;
if (!item) return;
setActiveItem(item);
setPendingRotated(item.rotated ?? false);
setHoverPosition(null);
};
const handleDragMove = (event: DragMoveEvent) => {
if (!activeItem) return;
const dx = Math.round(event.delta.x / cellSize);
const dy = Math.round(event.delta.y / cellSize);
const x = activeItem.gridX + dx;
const y = activeItem.gridY + dy;
const w = pendingRotated ? activeItem.height : activeItem.width;
const h = pendingRotated ? activeItem.width : activeItem.height;
if (x < 0 || y < 0 || x + w > gridWidth || y + h > gridHeight) {
setHoverPosition(null);
return;
}
setHoverPosition({ x, y });
};
const handleDragEnd = (event: DragEndEvent) => {
const item = activeItem;
setActiveItem(null);
setHoverPosition(null);
if (!item || !canEdit) return;
// Derive the target cell from the drag translation (pointer-anchored math
// like InventoryGrid: original cell + rounded delta).
const dx = Math.round(event.delta.x / cellSize);
const dy = Math.round(event.delta.y / cellSize);
const targetX = item.gridX + dx;
const targetY = item.gridY + dy;
if (dx === 0 && dy === 0) {
if (pendingRotated === item.rotated) return;
void onMoveItem(item.id, item.gridX, item.gridY, pendingRotated);
return;
}
const w = pendingRotated ? item.height : item.width;
const h = pendingRotated ? item.width : item.height;
if (
isPlacementValid(items, item.id, targetX, targetY, w, h, gridWidth, gridHeight)
) {
void onMoveItem(item.id, targetX, targetY, pendingRotated);
}
};
// 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
? {
width: pendingRotated ? activeItem.height : activeItem.width,
height: pendingRotated ? activeItem.width : activeItem.height,
}
: null;
return (
{Array.from({ length: gridHeight }).map((_, y) =>
Array.from({ length: gridWidth }).map((__, x) => {
const key = `${x},${y}`;
return (
);
}),
)}
{items.map((item) => (
))}
{items.length} parked
bay {gridWidth} × {gridHeight}
{canEdit && drag to move · R to rotate}
{activeItem ? (
) : null}
);
}