All files / src/pages/admin home-page.tsx

96.61% Statements 57/59
83.33% Branches 40/48
95.83% Functions 23/24
96.36% Lines 53/55

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                                                                            62x     62x     5x       5x     5x 5x           62x 35x     62x   12x   62x                                                                     30x                         2x     2x                                                                                       9x                                                                                             27x 27x 27x 27x   27x 4x     27x   3x 3x 3x 2x   1x               27x   3x 3x 3x 2x   1x                     27x   27x 1x                       26x 27x   27x 27x   27x                                                                                               2x                             3x                                                 2x                             6x     2x                   2x                       1x   1x 1x             1x   1x 1x                
import { useState, useCallback, useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Camera, ExternalLink, Plus, Search, X } from "lucide-react";
 
import {
	Card,
	CardContent,
	CardHeader,
} from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { adminApi, getImageUrl } from "../../lib/api";
import type { HomePageProjectSummary } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import { useAdminHomePageCuration } from "../../hooks/queries/useAdminQueries";
 
// Minimum picker row — only the fields we need to render the search list.
type PickerRow = {
	id: string;
	title: string;
	coverImage: string | null;
	proId: string;
};
 
// ─── Search-as-you-type project picker modal ─────────────────────────────────
 
function ProjectPickerModal({
	open,
	onClose,
	onPick,
	title,
	excludeIds,
}: {
	open: boolean;
	onClose: () => void;
	onPick: (project: PickerRow) => void;
	title: string;
	excludeIds: Set<string>;
}) {
	const [search, setSearch] = useState("");
 
	// Debounce-free for MVP — admin picker is rarely opened and results cap at 20.
	const { data, isLoading } = useQuery({
		queryKey: ["admin", "projects", "picker", search],
		queryFn: async () => {
			const params: Record<string, string> = {
				status: "published",
				limit: "20",
			};
			Iif (search.trim()) {
				params.search = search.trim();
			}
			const res = await adminApi.listProjects(params);
			return (res.data ?? []) as PickerRow[];
		},
		enabled: open,
		staleTime: 30 * 1000,
	});
 
	useEffect(() => {
		if (!open) setSearch("");
	}, [open]);
 
	if (!open) return null;
 
	const rows = (data ?? []).filter((p) => !excludeIds.has(p.id));
 
	return (
		<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
			<div className="w-full max-w-2xl rounded-lg bg-background-elevated border border-border-default shadow-xl">
				<div className="flex items-center justify-between border-b border-border-default p-4">
					<h2 className="text-lg font-semibold text-foreground-default">
						{title}
					</h2>
					<button
						type="button"
						onClick={onClose}
						aria-label="Close"
						className="p-1 text-foreground-muted hover:text-foreground-default"
					>
						<X className="h-5 w-5" />
					</button>
				</div>
 
				<div className="p-4">
					<div className="relative">
						<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
						<input
							type="search"
							value={search}
							onChange={(e) => setSearch(e.target.value)}
							placeholder="Search published projects by title…"
							className="w-full rounded-md border border-border-default bg-background-default py-2 pl-9 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500/40"
							// biome-ignore lint/a11y/noAutofocus: focus the field as the modal opens
							autoFocus
						/>
					</div>
 
					<div className="mt-4 max-h-[400px] overflow-y-auto">
						{isLoading ? (
							<div className="space-y-2">
								{[1, 2, 3].map((i) => (
									<div
										key={i}
										className="h-16 animate-pulse rounded bg-background-muted"
									/>
								))}
							</div>
						) : rows.length === 0 ? (
							<p className="py-8 text-center text-sm text-foreground-muted">
								No matching published projects.
							</p>
						) : (
							<ul className="divide-y divide-border-default">
								{rows.map((project) => (
									<li key={project.id}>
										<button
											type="button"
											onClick={() => onPick(project)}
											className="flex w-full items-center gap-3 py-2.5 px-1 text-left hover:bg-background-muted rounded"
										>
											{project.coverImage ? (
												<img
													src={getImageUrl(project.coverImage)}
													alt=""
													className="h-12 w-16 rounded object-cover"
												/>
											) : (
												<div className="flex h-12 w-16 items-center justify-center rounded bg-background-muted">
													<Camera className="h-4 w-4 text-foreground-subtle" />
												</div>
											)}
											<div className="min-w-0 flex-1">
												<p className="truncate text-sm font-medium text-foreground-default">
													{project.title}
												</p>
											</div>
										</button>
									</li>
								))}
							</ul>
						)}
					</div>
				</div>
			</div>
		</div>
	);
}
 
// ─── Single project tile (used by hero + featured list) ─────────────────────
 
function ProjectTile({
	project,
	badge,
	onRemove,
	removeLabel,
}: {
	project: HomePageProjectSummary;
	badge?: { text: string; tone: "curated" | "muted" };
	onRemove: () => void;
	removeLabel: string;
}) {
	return (
		<div className="flex items-center gap-3 rounded-md border border-border-default bg-background-default p-3">
			{project.coverImage ? (
				<img
					src={getImageUrl(project.coverImage)}
					alt=""
					className="h-16 w-24 rounded object-cover"
				/>
			) : (
				<div className="flex h-16 w-24 items-center justify-center rounded bg-background-muted">
					<Camera className="h-5 w-5 text-foreground-subtle" />
				</div>
			)}
			<div className="min-w-0 flex-1">
				<p className="truncate text-sm font-medium text-foreground-default">
					{project.title}
				</p>
				<p className="truncate text-xs text-foreground-muted">
					Status: {project.status}
				</p>
				{badge && (
					<span
						className={`mt-1 inline-block rounded px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
							badge.tone === "curated"
								? "bg-green-100 text-green-700"
								: "bg-background-muted text-foreground-muted"
						}`}
					>
						{badge.text}
					</span>
				)}
			</div>
			<Button
				variant="outline"
				size="sm"
				onClick={onRemove}
			>
				<X className="h-4 w-4 mr-1" />
				{removeLabel}
			</Button>
		</div>
	);
}
 
// ─── Main page ──────────────────────────────────────────────────────────────
 
export function AdminHomePagePage() {
	const queryClient = useQueryClient();
	const { data, isLoading, isError } = useAdminHomePageCuration();
	const [pickerOpen, setPickerOpen] = useState<null | "hero" | "featured">(null);
	const [errorMsg, setErrorMsg] = useState<string | null>(null);
 
	const invalidate = useCallback(() => {
		queryClient.invalidateQueries({ queryKey: queryKeys.admin.homePage.all });
	}, [queryClient]);
 
	const setHero = useCallback(
		async (projectId: string | null) => {
			setErrorMsg(null);
			try {
				await adminApi.setHero(projectId);
				invalidate();
			} catch (err) {
				setErrorMsg(
					err instanceof Error ? err.message : "Failed to update hero",
				);
			}
		},
		[invalidate],
	);
 
	const setFeatured = useCallback(
		async (projectId: string, isFeatured: boolean) => {
			setErrorMsg(null);
			try {
				await adminApi.setProjectFeatured(projectId, isFeatured);
				invalidate();
			} catch (err) {
				setErrorMsg(
					err instanceof Error
						? err.message
						: "Failed to update featured projects",
				);
			}
		},
		[invalidate],
	);
 
	const marketplaceUrl =
		import.meta.env.VITE_MARKETPLACE_URL || "http://localhost:7003";
 
	if (isError) {
		return (
			<div className="space-y-4">
				<h1 className="text-2xl font-bold text-foreground-default">
					Home page
				</h1>
				<div className="rounded-md bg-error-light border border-error/20 p-4 text-sm text-error">
					Failed to load home page curation. Please refresh.
				</div>
			</div>
		);
	}
 
	const hero = data?.hero ?? null;
	const featured = data?.featured ?? [];
 
	const heroExcludeIds = new Set<string>(hero ? [hero.id] : []);
	const featuredExcludeIds = new Set<string>(featured.map((p) => p.id));
 
	return (
		<div className="space-y-6">
			<div className="flex items-baseline justify-between">
				<div>
					<h1 className="text-3xl font-bold text-foreground-default">
						Home page
					</h1>
					<p className="mt-1 text-sm text-foreground-muted">
						Pick the hero project and the featured projects shown on the
						marketplace home page. Cache refreshes within 60 seconds.
					</p>
				</div>
				<Button variant="ghost" size="sm" asChild>
					<a
						href={marketplaceUrl}
						target="_blank"
						rel="noopener noreferrer"
					>
						View marketplace
						<ExternalLink className="ml-1.5 h-3.5 w-3.5" />
					</a>
				</Button>
			</div>
 
			{errorMsg && (
				<div className="rounded-md bg-error-light border border-error/20 p-3 text-sm text-error">
					{errorMsg}
				</div>
			)}
 
			{/* Hero */}
			<Card>
				<CardHeader>
					<h2 className="text-2xl font-semibold leading-none tracking-tight text-foreground-default">
						Hero project
					</h2>
					<p className="mt-1 text-sm text-foreground-muted">
						When set, this project replaces the algorithmic hero (which picks
						the first project with at least 3 photos).
					</p>
				</CardHeader>
				<CardContent>
					{isLoading ? (
						<div className="h-20 animate-pulse rounded bg-background-muted" />
					) : hero ? (
						<ProjectTile
							project={hero}
							badge={{ text: "Curated", tone: "curated" }}
							onRemove={() => setHero(null)}
							removeLabel="Clear hero"
						/>
					) : (
						<div className="rounded-md border border-dashed border-border-default bg-background-muted/40 p-6 text-center">
							<p className="text-sm text-foreground-muted">
								No hero project pinned. Homepage uses the algorithmic
								fallback.
							</p>
						</div>
					)}
					<div className="mt-3">
						<Button
							variant="outline"
							size="sm"
							onClick={() => setPickerOpen("hero")}
						>
							<Plus className="h-4 w-4 mr-1.5" />
							{hero ? "Replace hero" : "Choose hero project"}
						</Button>
					</div>
				</CardContent>
			</Card>
 
			{/* Featured projects */}
			<Card>
				<CardHeader>
					<h2 className="text-2xl font-semibold leading-none tracking-tight text-foreground-default">
						Featured projects
					</h2>
					<p className="mt-1 text-sm text-foreground-muted">
						Shown in the "Latest Projects" section. Order is automatic (by
						quality score) and not manually editable. When empty, the homepage
						falls back to the most recent published projects.
					</p>
				</CardHeader>
				<CardContent>
					{isLoading ? (
						<div className="space-y-2">
							{[1, 2].map((i) => (
								<div
									key={i}
									className="h-20 animate-pulse rounded bg-background-muted"
								/>
							))}
						</div>
					) : featured.length === 0 ? (
						<div className="rounded-md border border-dashed border-border-default bg-background-muted/40 p-6 text-center">
							<p className="text-sm text-foreground-muted">
								No featured projects pinned. Homepage shows the latest 12.
							</p>
						</div>
					) : (
						<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
							{featured.map((project) => (
								<ProjectTile
									key={project.id}
									project={project}
									onRemove={() => setFeatured(project.id, false)}
									removeLabel="Unfeature"
								/>
							))}
						</div>
					)}
					<div className="mt-3">
						<Button
							variant="outline"
							size="sm"
							onClick={() => setPickerOpen("featured")}
						>
							<Plus className="h-4 w-4 mr-1.5" />
							Add featured project
						</Button>
					</div>
				</CardContent>
			</Card>
 
			{/* Picker modal */}
			<ProjectPickerModal
				open={pickerOpen === "hero"}
				onClose={() => setPickerOpen(null)}
				onPick={async (p) => {
					setPickerOpen(null);
					await setHero(p.id);
				}}
				title="Choose hero project"
				excludeIds={heroExcludeIds}
			/>
			<ProjectPickerModal
				open={pickerOpen === "featured"}
				onClose={() => setPickerOpen(null)}
				onPick={async (p) => {
					setPickerOpen(null);
					await setFeatured(p.id, true);
				}}
				title="Add featured project"
				excludeIds={featuredExcludeIds}
			/>
		</div>
	);
}