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 | 8x 8x 8x 8x 92x 92x 4x 4x 1x 1x 3x 1x 1x 2x 1x 1x 1x 1x 1x 92x 6x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 92x 184x 92x 92x 44x 4x 4x 4x 4x 2x 1x 1x 4x 4x 4x 44x 8x 8x 44x 1x 44x 6x 6x 6x 4x 4x 6x 2x 2x 1x 1x 1x 44x 2x 2x 2x 1x 1x 1x 1x 1x 44x 44x 1x 43x 44x 1x 6x 1x 92x 92x 92x 8x | import { useState, useCallback, useEffect, useRef } from "react";
import { Link, useParams } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { Camera, Check, ExternalLink, X } from "lucide-react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { adminApi, getImageUrl } from "../../lib/api";
import type { RoomCategoryMedia } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import {
useAdminRoomCategory,
useAdminRoomCategoryMedia,
} from "../../hooks/queries/useAdminQueries";
import { ApiError } from "../../lib/api";
// ─── Toast ────────────────────────────────────────────────────────────────────
type ToastState = {
id: number;
message: string;
variant: "success" | "error";
};
function Toast({
toast,
onDismiss,
}: {
toast: ToastState;
onDismiss: (id: number) => void;
}) {
useEffect(() => {
const timer = setTimeout(() => onDismiss(toast.id), 4000);
return () => clearTimeout(timer);
}, [toast.id, onDismiss]);
return (
<div
className={`flex items-center gap-2 px-4 py-3 rounded text-sm font-medium text-white shadow-lg ${
toast.variant === "success"
? "bg-foreground-default"
: "bg-amber-700"
}`}
role="status"
aria-live="polite"
>
{toast.variant === "success" ? "✓" : "⚠"} {toast.message}
</div>
);
}
// ─── Photo cell ───────────────────────────────────────────────────────────────
type PhotoCellProps = {
media: RoomCategoryMedia;
isSelected: boolean;
colIndex: number;
rowIndex: number;
totalCols: number;
totalItems: number;
onSelect: (media: RoomCategoryMedia) => void;
onKeyNav: (
colIndex: number,
rowIndex: number,
direction: "up" | "down" | "left" | "right",
) => void;
cellRef: (el: HTMLButtonElement | null) => void;
};
function PhotoCell({
media,
isSelected,
colIndex,
rowIndex,
onSelect,
onKeyNav,
cellRef,
}: PhotoCellProps) {
const altText =
media.altText || `${media.proBusinessName} - ${media.projectTitle}`;
const handleKeyDown = (e: React.KeyboardEvent) => {
Iif (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onSelect(media);
} else if (e.key === "ArrowUp") {
e.preventDefault();
onKeyNav(colIndex, rowIndex, "up");
} else if (e.key === "ArrowDown") {
e.preventDefault();
onKeyNav(colIndex, rowIndex, "down");
} else if (e.key === "ArrowLeft") {
e.preventDefault();
onKeyNav(colIndex, rowIndex, "left");
E} else if (e.key === "ArrowRight") {
e.preventDefault();
onKeyNav(colIndex, rowIndex, "right");
}
};
return (
<button
ref={cellRef}
type="button"
aria-pressed={isSelected}
aria-label={`Select ${altText} as cover`}
onClick={() => onSelect(media)}
onKeyDown={handleKeyDown}
className={`relative aspect-[4/3] rounded cursor-pointer outline-none transition-transform duration-75 group p-0 border-0 bg-transparent text-left ${
isSelected
? "ring-2 ring-primary-600 scale-[1.01]"
: "ring-2 ring-transparent hover:scale-[1.02] focus-visible:ring-primary-600 focus-visible:shadow-[0_0_0_3px_rgba(196,106,74,0.2)]"
}`}
>
<img
src={getImageUrl(media.url)}
alt={altText}
className="w-full h-full object-cover rounded"
loading="lazy"
/>
{/* Selected checkmark badge */}
{isSelected && (
<div className="absolute top-1 right-1 w-[22px] h-[22px] rounded-full bg-primary-600 flex items-center justify-center">
<Check className="h-3 w-3 text-white" strokeWidth={3} />
</div>
)}
{/* Pro badge overlay — revealed on hover/focus */}
<div className="absolute bottom-1.5 left-1.5 right-1.5 bg-black/70 rounded px-1.5 py-1 text-[11px] text-white leading-tight opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100 transition-opacity duration-75 pointer-events-none">
{media.proBusinessName} · {media.projectTitle}
</div>
</button>
);
}
// ─── Main page ────────────────────────────────────────────────────────────────
export function AdminRoomCategoryDetailPage() {
const params = useParams({ strict: false }) as { code?: string };
const code = params.code ?? "";
const queryClient = useQueryClient();
const [sortBy, setSortBy] = useState<"recent" | "popular">("recent");
const [optimisticSelectedId, setOptimisticSelectedId] = useState<
number | null | undefined
>(undefined); // undefined = use server value
const [toasts, setToasts] = useState<ToastState[]>([]);
const toastIdRef = useRef(0);
const { data: category, isLoading: catLoading, isError: catError } =
useAdminRoomCategory(code || null);
const {
data: media,
isLoading: mediaLoading,
isError: mediaError,
refetch: refetchMedia,
} = useAdminRoomCategoryMedia(code || null, sortBy);
// The resolved selected media id: optimistic takes precedence over server state
const selectedMediaId =
optimisticSelectedId !== undefined
? optimisticSelectedId
: category?.coverMediaId ?? null;
// Arrow-key navigation between gallery cells
// We store refs by flat index (row * cols + col)
const COLS = 3;
const cellRefs = useRef<Map<number, HTMLButtonElement>>(new Map());
const setCellRef = useCallback(
(flatIndex: number) => (el: HTMLButtonElement | null) => {
if (el) {
cellRefs.current.set(flatIndex, el);
} else {
cellRefs.current.delete(flatIndex);
}
},
[],
);
const handleKeyNav = useCallback(
(
colIndex: number,
rowIndex: number,
direction: "up" | "down" | "left" | "right",
) => {
const totalItems = media?.length ?? 0;
let newCol = colIndex;
let newRow = rowIndex;
if (direction === "left") newCol = Math.max(0, colIndex - 1);
else if (direction === "right") newCol = Math.min(COLS - 1, colIndex + 1);
else if (direction === "up") newRow = Math.max(0, rowIndex - 1E);
else if (direction === "down") newRow = rowIndex + 1;
const newFlat = newRow * COLS + newCol;
Eif (newFlat < totalItems && newFlat >= 0) {
cellRefs.current.get(newFlat)?.focus();
}
},
[media?.length],
);
const addToast = useCallback((message: string, variant: ToastState["variant"]) => {
const id = ++toastIdRef.current;
setToasts((prev) => [...prev, { id, message, variant }]);
}, []);
const dismissToast = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const handleSelectPhoto = useCallback(
async (selectedMedia: RoomCategoryMedia) => {
// Optimistic update
setOptimisticSelectedId(selectedMedia.id);
try {
await adminApi.setRoomCategoryCover(code, selectedMedia.id);
// Invalidate both list and detail queries
queryClient.invalidateQueries({
queryKey: queryKeys.admin.roomCategories.all,
});
addToast(
`${category?.label ?? "Category"} cover updated. Homepage refreshes within 60 seconds.`,
"success",
);
// Keep optimistic selection in sync
setOptimisticSelectedId(undefined);
} catch (err) {
// Roll back optimistic update
setOptimisticSelectedId(undefined);
if (err instanceof ApiError && err.status === 409) {
addToast(
"That photo was removed by the pro. Please pick another.",
"error",
);
// Refetch gallery to drop the deleted photo
refetchMedia();
} else {
addToast(
"Failed to set cover. Please try again.",
"error",
);
}
}
},
[code, category?.label, queryClient, addToast, refetchMedia],
);
const handleClearCover = useCallback(async () => {
setOptimisticSelectedId(null);
try {
await adminApi.clearRoomCategoryCover(code);
queryClient.invalidateQueries({
queryKey: queryKeys.admin.roomCategories.all,
});
addToast("Curated cover cleared. Algorithmic selection will be used.", "success");
setOptimisticSelectedId(undefined);
} catch {
setOptimisticSelectedId(undefined);
addToast("Failed to clear cover. Please try again.", "error");
}
}, [code, queryClient, addToast]);
const marketplaceUrl = import.meta.env.VITE_MARKETPLACE_URL || "http://localhost:7003";
if (catError) {
return (
<div className="space-y-4">
<div className="text-sm text-foreground-muted">
<Link to="/admin/room-categories" className="hover:text-primary-600">
Room categories
</Link>
{" / "}
<span>{code}</span>
</div>
<div className="rounded-md bg-error-light border border-error/20 p-4 text-sm text-error">
Failed to load room category. Please refresh.
</div>
</div>
);
}
const categoryLabel = category?.label ?? code;
return (
<div className="space-y-6">
{/* Breadcrumb */}
<div className="text-sm text-foreground-muted">
<Link to="/admin/room-categories" className="hover:text-primary-600">
Room categories
</Link>
{" / "}
<span className="text-foreground-default">{categoryLabel}</span>
</div>
{/* Page title */}
<div>
<div className="flex items-baseline gap-3">
<h1 className="text-2xl font-bold text-foreground-default">
{catLoading ? (
<span className="inline-block h-7 w-32 bg-background-muted rounded animate-pulse" />
) : (
categoryLabel
)}
</h1>
{category && !catLoading && (
<span className="text-sm text-foreground-subtle">
{category.projectCount} projects · {category.photoCount} photos available
</span>
)}
</div>
</div>
{/* Two-panel layout */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* LEFT: Current cover */}
<Card>
<CardHeader>
<CardTitle>Current cover</CardTitle>
<p className="text-sm text-foreground-muted mt-1">
This image appears on the marketplace homepage and the /rooms/{code} page.
</p>
</CardHeader>
<CardContent>
{catLoading ? (
<div
className="w-full rounded aspect-[4/3] animate-pulse"
style={{
background:
"linear-gradient(110deg, #f0efed 8%, #fafaf9 18%, #f0efed 33%)",
backgroundSize: "200% 100%",
animation: "shimmer 1.5s infinite",
}}
/>
) : category?.coverMediaUrl ? (
<>
{/* Cover image with source badge */}
<div className="relative aspect-[4/3] rounded overflow-hidden border border-border-default">
<img
src={getImageUrl(category.coverMediaUrl)}
alt={category.coverMediaAlt || categoryLabel}
className="w-full h-full object-cover"
/>
<div
className={`absolute top-3 left-3 text-[11px] font-bold uppercase tracking-wide px-2 py-1 rounded ${
category.coverSource === "curated"
? "bg-green-100 text-green-700"
: "bg-amber-100 text-amber-700"
}`}
>
{category.coverSource === "curated" ? "Curated" : "Algorithmic"}
</div>
</div>
{/* Attribution */}
<p className="text-sm text-foreground-muted mt-3">
From{" "}
<strong className="text-foreground-default">
{category.coverProjectTitle}
</strong>{" "}
by{" "}
<strong className="text-foreground-default">
{category.coverProName}
</strong>
{category.coverUploadedAt && (
<>
{" · uploaded "}
{Math.floor(
(Date.now() - new Date(category.coverUploadedAt).getTime()) /
(1000 * 60 * 60 * 24),
)}{" "}
days ago
</>
)}
</p>
{/* Actions */}
<div className="flex gap-2 mt-3">
{category.coverSource === "curated" && (
<Button
variant="outline"
size="sm"
onClick={handleClearCover}
className="text-amber-700 border-amber-200 hover:bg-amber-50"
>
<X className="h-4 w-4 mr-1.5" />
Clear curated cover
</Button>
)}
<Button
variant="ghost"
size="sm"
asChild
>
<a
href={`${marketplaceUrl}/rooms/${code}`}
target="_blank"
rel="noopener noreferrer"
>
View on homepage
<ExternalLink className="h-3.5 w-3.5 ml-1.5" />
</a>
</Button>
</div>
</>
) : (
/* Empty cover state */
<>
<div className="w-full aspect-[4/3] rounded border border-border-default bg-background-muted flex flex-col items-center justify-center gap-2">
<Camera className="h-8 w-8 text-foreground-subtle" />
<span className="text-sm text-foreground-subtle">No cover image</span>
</div>
<p className="text-sm text-foreground-muted mt-3">
Pros need to upload {categoryLabel.toLowerCase()} photos before this
category can get a cover.
</p>
</>
)}
</CardContent>
</Card>
{/* RIGHT: Photo picker */}
<Card>
<CardHeader>
<CardTitle>Pick from {categoryLabel.toLowerCase()} photos</CardTitle>
<p className="text-sm text-foreground-muted mt-1">
Click any photo to set it as the {categoryLabel.toLowerCase()} category cover.
</p>
</CardHeader>
<CardContent>
{/* Toolbar */}
<div className="flex items-center gap-3 pb-4 mb-4 border-b border-border-default flex-wrap">
<span className="text-sm text-foreground-muted">
{mediaLoading ? "Loading…" : `${media?.length ?? 0} photos · sorted by upload date`}
</span>
<select
value={sortBy}
onChange={(e) =>
setSortBy(e.target.value as "recent" | "popular")
}
className="ml-auto text-sm border border-border-default rounded px-2.5 py-1 bg-background-elevated focus:outline-none focus:ring-2 focus:ring-primary-500/40"
aria-label="Sort photos"
>
<option value="recent">Most recent</option>
<option value="popular">Most viewed</option>
</select>
</div>
{/* Gallery */}
{mediaLoading ? (
<div className="grid grid-cols-3 gap-2 lg:grid-cols-3 md:grid-cols-4">
{[1, 2, 3, 4, 5, 6].map((i) => (
<div
key={i}
className="aspect-[4/3] rounded animate-pulse"
style={{
background:
"linear-gradient(110deg, #f0efed 8%, #fafaf9 18%, #f0efed 33%)",
backgroundSize: "200% 100%",
animationDelay: `${(i - 1) * 0.1}s`,
}}
/>
))}
</div>
) : mediaError ? (
<div className="rounded border border-error/20 bg-error-light p-4 text-sm text-error">
Failed to load photos.{" "}
<button
type="button"
onClick={() => refetchMedia()}
className="underline"
>
Retry
</button>
</div>
) : !media || media.length === 0 ? (
<div className="rounded border border-dashed border-border-default bg-background-muted/40 p-12 text-center">
<p className="font-semibold text-foreground-default mb-2">
No {categoryLabel.toLowerCase()} photos available yet
</p>
<p className="text-sm text-foreground-muted mb-4">
Pros haven't published any projects with{" "}
{categoryLabel.toLowerCase()} photos yet. Until they do,
this category will show a generic placeholder on the marketplace.
</p>
<Button variant="outline" size="sm" asChild>
<Link to="/admin/pros">
View pros without {categoryLabel.toLowerCase()} photos →
</Link>
</Button>
</div>
) : (
<ul
className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-3 gap-2 max-h-[480px] overflow-y-auto pr-1 list-none p-0 m-0"
aria-label={`${categoryLabel} photos`}
>
{media.map((item, index) => {
const col = index % COLS;
const row = Math.floor(index / COLS);
return (
<li key={item.id} className="contents">
<PhotoCell
media={item}
isSelected={item.id === selectedMediaId}
colIndex={col}
rowIndex={row}
totalCols={COLS}
totalItems={media.length}
onSelect={handleSelectPhoto}
onKeyNav={handleKeyNav}
cellRef={setCellRef(index)}
/>
</li>
);
})}
</ul>
)}
</CardContent>
</Card>
</div>
{/* Toast container */}
<div className="fixed bottom-4 right-4 flex flex-col gap-2 z-50">
{toasts.map((toast) => (
<Toast key={toast.id} toast={toast} onDismiss={dismissToast} />
))}
</div>
</div>
);
}
|