Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 | 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 217x 81x 80x 80x 79x 79x 79x 1x 1x 1x 217x 76x 76x 74x 74x 1x 1x 217x 55x 55x 60x 60x 59x 59x 1x 1x 55x 217x 76x 76x 76x 75x 52x 75x 76x 217x 5x 5x 3x 217x 142x 2x 2x 217x 6x 6x 6x 6x 1x 1x 5x 5x 6x 1x 1x 4x 4x 4x 4x 4x 3x 3x 1x 2x 2x 2x 2x 2x 2x 1x 2x 2x 2x 4x 217x 6x 6x 6x 6x 6x 217x 8x 8x 8x 8x 7x 7x 7x 7x 1x 1x 217x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 1x 217x 150x 217x 171x 217x 135x 217x 118x 118x 217x 3x 2x 2x 2x 1x 1x 1x 1x 1x 2x 217x 3x 3x 1x 2x 2x 1x 1x 1x 217x 2x 2x 1x 1x 1x 217x 1x 1x 1x 1x 217x 4x 4x 217x 1x 1x 217x 3x 3x 3x 217x 3x 3x 2x 2x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 217x 217x 3x 3x 1x 2x 2x 1x 1x 1x 1x 217x 217x 76x 141x 2x 139x 3x 3x 118x 118x 118x 118x 118x 4x 3x 3x 4x 4x 1x 81x 1x 1x 1x 8x 1x 2x 3x 3x 236x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x | // Room cards grid — primary layout for project rooms on the detail page
// Shows full-width stacked room cards with inline media (cover + thumbnail strip),
// display preference toggle, and legacy conversion banner.
import { useState, useEffect, useCallback, useRef, useMemo, type DragEvent, type ChangeEvent } from "react";
import { notify } from "../../lib/notify";
import { useQueryClient } from "@tanstack/react-query";
import {
Star,
Plus,
Edit2,
Trash2,
GripVertical,
Upload,
LayoutGrid,
Image as ImageIcon,
ArrowRightLeft,
AlertTriangle,
X,
} from "lucide-react";
import {
proApi,
taxonomyApi,
ApiError,
getImageUrl,
getErrorMessage,
type Room,
type Media,
type RoomType,
type Project,
} from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import { Button } from "../ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "../ui/card";
import { RoomFormModal } from "../rooms/RoomFormModal";
import { RoomEditorModal } from "./RoomEditorModal";
import { MediaGrid } from "../rooms/MediaGrid";
import { MediaLightbox } from "../rooms/MediaLightbox";
import { useConfirmDialog } from "../../hooks";
import type { ProjectApiAdapter } from "./types";
import { API_BASE_URL } from "../../lib/api/base";
type RoomCardsGridProps = {
project: Project & { photos: unknown[] };
proId: string;
supportsRooms: boolean;
apiAdapter: ProjectApiAdapter;
onSave: (data: Partial<Project>) => Promise<void>;
onTotalMediaChange?: (count: number) => void;
};
export function RoomCardsGrid({
project,
proId,
supportsRooms,
apiAdapter,
onSave,
onTotalMediaChange,
}: RoomCardsGridProps) {
const { confirm, dialog: confirmDialog } = useConfirmDialog();
// Data state
const [rooms, setRooms] = useState<Room[]>([]);
const [roomTypes, setRoomTypes] = useState<RoomType[]>([]);
const [roomMediaMap, setRoomMediaMap] = useState<Record<number, Media[]>>(
{},
);
const [isLoading, setIsLoading] = useState(true);
// UI state
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
const [newRoomType, setNewRoomType] = useState("");
const [newRoomName, setNewRoomName] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
// Editor modal state
const [editingRoom, setEditingRoom] = useState<Room | null>(null);
// Media manager modal state
const [managingRoom, setManagingRoom] = useState<Room | null>(null);
const [managingRoomMedia, setManagingRoomMedia] = useState<Media[]>([]);
// Per-card upload state
const [uploadingRoomId, setUploadingRoomId] = useState<number | null>(null);
const fileInputRefs = useRef<Record<number, HTMLInputElement | null>>({});
const queryClient = useQueryClient();
// Lightbox state
const [lightboxRoomId, setLightboxRoomId] = useState<number | null>(null);
const [lightboxIndex, setLightboxIndex] = useState(0);
// Drag reorder state
const [draggedRoomId, setDraggedRoomId] = useState<number | null>(null);
const [dragOverRoomId, setDragOverRoomId] = useState<number | null>(null);
// Load rooms and room types
const loadRooms = useCallback(async () => {
if (!apiAdapter.getRooms) return;
try {
const response = await apiAdapter.getRooms(project.id);
Eif (response.data) {
setRooms(response.data);
return response.data;
}
} catch (err) {
console.error("Failed to load rooms:", err);
notify.error("Failed to load rooms. Please refresh the page.");
}
return [];
}, [apiAdapter, project.id]);
const loadRoomTypes = useCallback(async () => {
try {
const response = await taxonomyApi.getRoomTypes();
Eif (response.data) {
setRoomTypes(response.data);
}
} catch (err) {
console.error("Failed to load room types:", err);
notify.error("Failed to load room types.");
}
}, []);
const loadAllRoomMedia = useCallback(
async (roomsList: Room[]) => {
const mediaMap: Record<number, Media[]> = {};
await Promise.all(
roomsList.map(async (room) => {
try {
const response = await proApi.getMediaByRoom(proId, room.id);
Eif (response.data) {
mediaMap[room.id] = response.data;
}
} catch (err) {
console.error("Failed to load room media:", err);
mediaMap[room.id] = [];
}
}),
);
setRoomMediaMap(mediaMap);
},
[proId],
);
useEffect(() => {
const init = async () => {
setIsLoading(true);
const [roomsList] = await Promise.all([loadRooms(), loadRoomTypes()]);
if (roomsList && roomsList.length > 0) {
await loadAllRoomMedia(roomsList);
}
setIsLoading(false);
};
init();
}, [loadRooms, loadRoomTypes, loadAllRoomMedia]);
const refreshRooms = useCallback(async () => {
const roomsList = await loadRooms();
if (roomsList && roomsList.length > 0) {
await loadAllRoomMedia(roomsList);
}
}, [loadRooms, loadAllRoomMedia]);
// Report total media count to parent (used by PublishChecklist)
useEffect(() => {
if (!onTotalMediaChange) return;
const total = Object.values(roomMediaMap).reduce((sum, media) => sum + media.length, 0);
onTotalMediaChange(total);
}, [roomMediaMap, onTotalMediaChange]);
// -- Per-card media upload --
const uploadFileToRoom = useCallback(
async (roomId: number, file: File) => {
const imageTypes = ["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"];
const videoTypes = ["video/mp4", "video/webm", "video/quicktime"];
const allowedTypes = [...imageTypes, ...videoTypes];
if (!allowedTypes.includes(file.type)) {
notify.error("Invalid file type. Allowed: JPEG, PNG, WebP, GIF, AVIF, MP4, WebM, MOV");
return;
}
const isVideo = videoTypes.includes(file.type);
const maxSize = isVideo ? 500 * 1024 * 1024 : 10 * 1024 * 1024;
if (file.size > maxSize) {
notify.error(`File too large. Max size: ${isVideo ? "500MB" : "10MB"}`);
return;
}
setUploadingRoomId(roomId);
try {
const formData = new FormData();
formData.append("file", file);
const response = await fetch(
`${API_BASE_URL}/api/pro/${proId}/rooms/${roomId}/upload-media`,
{ method: "POST", credentials: "include", body: formData },
);
const data = await response.json();
if (!response.ok || !data.success) {
throw new ApiError(
data.error?.code || "UPLOAD_ERROR",
data.error?.message || "Failed to upload media",
response.status,
);
}
// Refresh media for this room
const mediaResponse = await proApi.getMediaByRoom(proId, roomId);
Eif (mediaResponse.data) {
const freshMedia = mediaResponse.data;
setRoomMediaMap((prev) => ({ ...prev, [roomId]: freshMedia }));
}
// Invalidate immediately + again after 1.5s to catch async cover image update
queryClient.invalidateQueries({ queryKey: queryKeys.projects.list(proId) });
setTimeout(() => {
queryClient.invalidateQueries({ queryKey: queryKeys.projects.list(proId) });
}, 1500);
notify.success("Media uploaded");
} catch (err) {
console.error("Failed to upload media:", err);
notify.error(getErrorMessage(err));
} finally {
setUploadingRoomId(null);
}
},
[proId, queryClient],
);
const handleFileSelect = useCallback(
async (roomId: number, e: ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
Iif (!files || files.length === 0) return;
for (let i = 0; i < files.length; i++) {
await uploadFileToRoom(roomId, files[i]);
}
// Reset the input so the same file can be re-selected
e.target.value = "";
},
[uploadFileToRoom],
);
// -- Media manager helpers --
const openMediaManager = useCallback(
async (room: Room) => {
setManagingRoom(room);
setManagingRoomMedia(roomMediaMap[room.id] || []);
// Fetch fresh media
try {
const response = await proApi.getMediaByRoom(proId, room.id);
Eif (response.data) {
const freshMedia = response.data;
setManagingRoomMedia(freshMedia);
setRoomMediaMap((prev) => ({ ...prev, [room.id]: freshMedia }));
}
} catch (err) {
console.error("Failed to load room media:", err);
notify.error("Failed to load room photos.");
}
},
[proId, roomMediaMap],
);
const handleMediaManagerChange = useCallback(async () => {
Iif (!managingRoom) return;
try {
const response = await proApi.getMediaByRoom(proId, managingRoom.id);
Eif (response.data) {
const freshMedia = response.data;
setManagingRoomMedia(freshMedia);
setRoomMediaMap((prev) => ({ ...prev, [managingRoom.id]: freshMedia }));
}
// Delayed invalidation to catch async cover image update on server
setTimeout(() => {
queryClient.invalidateQueries({ queryKey: queryKeys.projects.list(proId) });
}, 1500);
} catch (err) {
console.error("Failed to refresh room media:", err);
notify.error("Failed to refresh room photos.");
}
}, [proId, managingRoom, queryClient]);
// -- Helpers --
// O(1) room type lookup by code
const roomTypeMap = useMemo(
() => new Map(roomTypes.map((t) => [t.code, t])),
[roomTypes],
);
const getRoomTypeName = (code: string) => {
return roomTypeMap.get(code)?.displayName || code;
};
const getRoomIcon = (code: string) => {
return roomTypeMap.get(code)?.icon || "";
};
const getCoverImage = (roomId: number): Media | undefined => {
const media = roomMediaMap[roomId] || [];
return media.find((m) => m.isCover) || media[0];
};
// -- Room CRUD --
const handleAddRoom = async () => {
if (!newRoomType || !apiAdapter.createRoom) return;
setIsSubmitting(true);
try {
await apiAdapter.createRoom(project.id, {
roomType: newRoomType,
name: newRoomName || undefined,
});
setNewRoomType("");
setNewRoomName("");
setIsAddModalOpen(false);
await refreshRooms();
} catch (err) {
notify.error(getErrorMessage(err));
} finally {
setIsSubmitting(false);
}
};
const handleDeleteRoom = async (roomId: number) => {
Iif (!apiAdapter.deleteRoom) return;
if (
!(await confirm({
title: "Delete room",
description:
"Delete this room? All media in this room will also be deleted.",
confirmLabel: "Delete",
variant: "destructive",
}))
)
return;
try {
await apiAdapter.deleteRoom(roomId);
await refreshRooms();
notify.success("Room deleted");
} catch (err) {
notify.error(getErrorMessage(err));
}
};
const handleSetFeatured = async (roomId: number) => {
try {
await proApi.setDefaultRoom(proId, project.id, roomId);
await onSave({}); // refresh project to get updated defaultRoomId
notify.success("Featured room updated");
} catch (err) {
notify.error(getErrorMessage(err));
}
};
const handleSaveRoomEditor = async (data: {
roomType: string;
name?: string;
areaSqft?: number;
budgetSpent?: string;
materials?: string[];
}) => {
Iif (!editingRoom || !apiAdapter.updateRoom) return;
await apiAdapter.updateRoom(editingRoom.id, data as Parameters<NonNullable<typeof apiAdapter.updateRoom>>[1]);
await refreshRooms();
notify.success("Room updated");
};
// -- Drag to reorder rooms --
const handleRoomDragStart = (e: DragEvent<HTMLDivElement>, roomId: number) => {
setDraggedRoomId(roomId);
e.dataTransfer.effectAllowed = "move";
};
const handleRoomDragEnd = () => {
setDraggedRoomId(null);
setDragOverRoomId(null);
};
const handleRoomDragOver = (e: DragEvent<HTMLDivElement>, roomId: number) => {
e.preventDefault();
Iif (draggedRoomId === null || draggedRoomId === roomId) return;
setDragOverRoomId(roomId);
};
const handleRoomDrop = async (
e: DragEvent<HTMLDivElement>,
targetRoomId: number,
) => {
e.preventDefault();
if (draggedRoomId === null || draggedRoomId === targetRoomId) return;
Iif (!apiAdapter.reorderRooms) return;
const dragIdx = rooms.findIndex((r) => r.id === draggedRoomId);
const targetIdx = rooms.findIndex((r) => r.id === targetRoomId);
Iif (dragIdx === -1 || targetIdx === -1) return;
const newRooms = [...rooms];
const [moved] = newRooms.splice(dragIdx, 1);
newRooms.splice(targetIdx, 0, moved);
setRooms(newRooms);
setDraggedRoomId(null);
setDragOverRoomId(null);
try {
await apiAdapter.reorderRooms(
project.id,
newRooms.map((r) => r.id),
);
} catch (err) {
notify.error(getErrorMessage(err));
await refreshRooms();
}
};
// -- Legacy conversion --
const hasLegacyPhotos =
project.photos && project.photos.length > 0 && rooms.length === 0;
const handleLegacyConvert = async () => {
Iif (!apiAdapter.createRoom) return;
if (
!(await confirm({
title: "Convert to rooms",
description:
"This will create a default room and associate existing photos with it. You can organize them into separate rooms afterward.",
confirmLabel: "Convert",
variant: "default",
}))
)
return;
try {
// Create a default room
await apiAdapter.createRoom(project.id, {
roomType: "living_room",
name: "Main",
});
// Enable rooms mode
await onSave({ useRooms: true });
await refreshRooms();
notify.success("Project converted to rooms layout");
} catch (err) {
notify.error(getErrorMessage(err));
}
};
// -- Lightbox helpers --
const lightboxMedia = lightboxRoomId !== null ? (roomMediaMap[lightboxRoomId] || []) : [];
// Loading state
if (isLoading) {
return (
<div className="flex items-center justify-center h-32">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
</div>
);
}
if (!supportsRooms) {
return (
<p className="text-sm text-foreground-muted text-center py-8">
Room management is not available.
</p>
);
}
return (
<>
<div className="space-y-6">
{/* Legacy conversion banner */}
{hasLegacyPhotos && (
<div className="flex items-start gap-3 p-4 rounded-lg border border-amber-300 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-700">
<AlertTriangle className="h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="font-medium text-sm text-amber-800 dark:text-amber-200">
Convert to rooms layout
</h4>
<p className="text-sm text-amber-700 dark:text-amber-300 mt-1">
This project has {project.photos.length} photos but no rooms.
Convert to the rooms layout to organize photos by room and
unlock room-level metadata.
</p>
<Button
size="sm"
variant="outline"
className="mt-3"
onClick={handleLegacyConvert}
>
<ArrowRightLeft className="h-4 w-4 mr-1" />
Convert to rooms
</Button>
</div>
</div>
)}
{/* Room cards header */}
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-lg">Rooms</CardTitle>
<CardDescription>
{rooms.length === 0
? "Add rooms to organize your project media"
: `${rooms.length} room${rooms.length !== 1 ? "s" : ""} · Organize your project by rooms`}
</CardDescription>
</div>
<Button size="sm" onClick={() => setIsAddModalOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add Room
</Button>
</div>
</CardHeader>
<CardContent>
{rooms.length === 0 ? (
<button
type="button"
onClick={() => setIsAddModalOpen(true)}
className="flex flex-col items-center justify-center py-12 w-full border-2 border-dashed border-border-default rounded-lg cursor-pointer hover:border-primary-400 hover:bg-primary-50/50 transition-colors"
>
<Plus className="h-8 w-8 text-foreground-subtle mb-2" />
<p className="text-sm text-foreground-muted">
Click to add your first room
</p>
</button>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{rooms.map((room) => {
const media = roomMediaMap[room.id] || [];
const cover = getCoverImage(room.id);
const isDefault = project.defaultRoomId === room.id;
const isUploadingThis = uploadingRoomId === room.id;
return (
// biome-ignore lint/a11y/noStaticElementInteractions: drag-and-drop reorder card
<div
key={room.id}
draggable
onDragStart={(e) => handleRoomDragStart(e, room.id)}
onDragEnd={handleRoomDragEnd}
onDragOver={(e) => handleRoomDragOver(e, room.id)}
onDrop={(e) => handleRoomDrop(e, room.id)}
className={`border rounded-lg bg-background-elevated overflow-hidden transition-all ${
dragOverRoomId === room.id
? "ring-2 ring-primary-300 border-primary-300"
: "border-border-default"
} ${draggedRoomId === room.id ? "opacity-50" : ""}`}
>
{/* Title bar */}
<div className="flex items-center gap-1.5 px-2.5 py-2 border-b border-border-default">
<span className="p-0.5 text-foreground-subtle cursor-grab">
<GripVertical className="h-3.5 w-3.5" />
</span>
<span className="text-sm flex-shrink-0">{getRoomIcon(room.roomType)}</span>
<h3 className="font-medium text-sm truncate">
{room.name || getRoomTypeName(room.roomType)}
</h3>
{isDefault && (
<span className="flex items-center gap-0.5 text-[10px] font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300 px-1.5 py-0.5 rounded-full flex-shrink-0 ml-auto">
<Star className="h-2.5 w-2.5 fill-current" />
Default
</span>
)}
</div>
{/* Cover image area */}
<div className="aspect-[4/3] bg-background-muted relative">
{cover ? (
<button
type="button"
onClick={() => {
setLightboxRoomId(room.id);
setLightboxIndex(media.indexOf(cover));
}}
className="w-full h-full cursor-pointer hover:opacity-95 transition-opacity"
>
<img
src={getImageUrl(cover.storageKey)}
alt={room.name || getRoomTypeName(room.roomType)}
className="w-full h-full object-cover"
loading="lazy"
/>
</button>
) : (
<button
type="button"
onClick={() => fileInputRefs.current[room.id]?.click()}
disabled={isUploadingThis}
className="w-full h-full flex flex-col items-center justify-center cursor-pointer hover:bg-background-elevated transition-colors disabled:opacity-50"
>
<ImageIcon className="h-8 w-8 text-foreground-subtle mb-1" />
<span className="text-xs text-foreground-muted">Add images</span>
</button>
)}
{/* Photo count badge */}
{media.length > 0 && (
<div className="absolute bottom-2 right-2">
<span className="flex items-center gap-1 text-xs bg-overlay-dark text-foreground-inverse px-1.5 py-0.5 rounded">
<ImageIcon className="h-3 w-3" />
{media.length}
</span>
</div>
)}
{/* Upload spinner overlay */}
{isUploadingThis && (
<div className="absolute inset-0 bg-overlay-dark/30 flex items-center justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-white" />
</div>
)}
</div>
{/* Thumbnails + actions */}
<div className="p-2.5">
{/* Thumbnail strip */}
{media.length > 0 && (
<div className="flex gap-1 mb-2">
{media.slice(0, 4).map((item, idx) => (
<button
key={item.id}
type="button"
onClick={() => {
setLightboxRoomId(room.id);
setLightboxIndex(idx);
}}
className={`relative w-10 h-10 rounded overflow-hidden flex-shrink-0 cursor-pointer ring-1 ring-border-default hover:ring-2 hover:ring-primary-400 transition-all ${
item.isCover ? "ring-2 ring-primary-500" : ""
}`}
>
<img
src={getImageUrl(item.storageKey)}
alt={item.caption || `Photo ${idx + 1}`}
className="w-full h-full object-cover"
loading="lazy"
/>
{/* "+N more" overlay on last visible thumb */}
{idx === 3 && media.length > 4 && (
<span className="absolute inset-0 bg-overlay-dark/60 flex items-center justify-center text-xs font-medium text-white">
+{media.length - 4}
</span>
)}
</button>
))}
<button
type="button"
onClick={() => fileInputRefs.current[room.id]?.click()}
disabled={isUploadingThis}
className="w-10 h-10 rounded border border-dashed border-border-default flex items-center justify-center cursor-pointer hover:border-primary-400 hover:bg-primary-50/50 transition-colors disabled:opacity-50 flex-shrink-0"
title="Add images"
>
<Plus className="h-4 w-4 text-foreground-subtle" />
</button>
</div>
)}
{/* Action buttons */}
<div className="flex items-center gap-0.5 pt-1.5 border-t border-border-default">
{media.length > 0 && (
<button
type="button"
onClick={() => openMediaManager(room)}
className="p-1 text-foreground-muted hover:text-primary-600 hover:bg-primary-50 rounded transition-colors"
title="Manage media"
>
<LayoutGrid className="h-3.5 w-3.5" />
</button>
)}
<button
type="button"
onClick={() => fileInputRefs.current[room.id]?.click()}
disabled={isUploadingThis}
className="p-1 text-foreground-muted hover:text-primary-600 hover:bg-primary-50 rounded transition-colors disabled:opacity-50"
title="Upload media"
>
<Upload className="h-3.5 w-3.5" />
</button>
{!isDefault && (
<button
type="button"
onClick={() => handleSetFeatured(room.id)}
className="p-1 text-foreground-muted hover:text-amber-600 hover:bg-amber-50 rounded transition-colors"
title="Set as featured"
>
<Star className="h-3.5 w-3.5" />
</button>
)}
<button
type="button"
onClick={() => setEditingRoom(room)}
className="p-1 text-foreground-muted hover:text-primary-600 hover:bg-primary-50 rounded transition-colors"
title="Edit room"
>
<Edit2 className="h-3.5 w-3.5" />
</button>
{!isDefault && (
<button
type="button"
onClick={() => handleDeleteRoom(room.id)}
className="p-1 text-foreground-muted hover:text-error hover:bg-error-light rounded transition-colors ml-auto"
title="Delete room"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* Hidden file input */}
<input
ref={(el) => { fileInputRefs.current[room.id] = el; }}
type="file"
accept="image/jpeg,image/png,image/webp,image/gif,image/avif,video/mp4,video/webm,video/quicktime"
multiple
className="hidden"
onChange={(e) => handleFileSelect(room.id, e)}
/>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
</div>
{/* Lightbox */}
{lightboxRoomId !== null && lightboxMedia.length > 0 && (
<MediaLightbox
media={lightboxMedia}
currentIndex={lightboxIndex}
onClose={() => setLightboxRoomId(null)}
onNext={() => setLightboxIndex((i) => (i + 1) % lightboxMedia.length)}
onPrev={() => setLightboxIndex((i) => (i - 1 + lightboxMedia.length) % lightboxMedia.length)}
/>
)}
{/* Add Room Modal */}
<RoomFormModal
isOpen={isAddModalOpen}
editingRoom={null}
newRoomType={newRoomType}
newRoomName={newRoomName}
roomTypes={roomTypes}
isSubmitting={isSubmitting}
onClose={() => {
setIsAddModalOpen(false);
setNewRoomType("");
setNewRoomName("");
}}
onSubmit={handleAddRoom}
onRoomTypeChange={setNewRoomType}
onRoomNameChange={setNewRoomName}
/>
{/* Room Editor Modal */}
{editingRoom && (
<RoomEditorModal
isOpen={editingRoom !== null}
room={editingRoom}
roomTypes={roomTypes}
onClose={() => setEditingRoom(null)}
onSave={handleSaveRoomEditor}
/>
)}
{/* Media Manager Modal */}
{managingRoom && (
<div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
<div className="bg-background-elevated rounded-lg shadow-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto">
<div className="flex items-center justify-between px-4 py-3 border-b border-border-default sticky top-0 bg-background-elevated z-10">
<h3 className="font-semibold text-sm">
{getRoomIcon(managingRoom.roomType)}{" "}
{managingRoom.name || getRoomTypeName(managingRoom.roomType)} — Manage Media
</h3>
<button
type="button"
onClick={() => setManagingRoom(null)}
aria-label="Close"
className="p-1 text-foreground-subtle hover:text-foreground-muted"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="p-4">
<MediaGrid
proId={proId}
room={managingRoom}
media={managingRoomMedia}
onMediaChange={handleMediaManagerChange}
onBack={() => setManagingRoom(null)}
roomTypeName={getRoomTypeName(managingRoom.roomType)}
/>
</div>
</div>
</div>
)}
{confirmDialog}
</>
);
}
|