All files / src/components/projects ProjectCreationWizard.tsx

92.36% Statements 133/144
87.35% Branches 76/87
92.85% Functions 26/28
95.45% Lines 126/132

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                                                                                                                        1x                     429x   429x 429x       429x 429x     429x 429x 429x         429x 429x 429x 429x 429x   429x                             429x                     429x     429x     429x 36x 36x 20x 20x       20x           429x 4x 4x       429x 32x 32x       429x 429x   429x 4x 4x       429x 32x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           429x 59x 25x 25x 1x 1x 59x     429x 69x                   429x 23x         429x     429x 25x 25x 2x 2x   23x   23x 23x 23x 22x         21x 22x 21x 21x       1x           22x   1x         429x 3x 3x 3x 3x 3x   3x 3x 3x 2x 2x 2x                                                                     2x   1x   3x       429x 2x 2x 2x     429x 1x     429x 2x 2x 2x 2x 1x   1x 1x 1x 1x     1x       429x 1x 1x 1x     429x         427x             854x                                                                       427x         312x 312x 1x                                                                         429x                                       2x                                                         429x     429x 17x                                                     410x                                                                                                    
import { useQueryClient } from "@tanstack/react-query";
import {
	normalizeProjectTitle,
	projectTitleErrorMessage,
	validateProjectTitle,
} from "@interioring/utils/validation/project-title";
import { ArrowLeft, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useDialogAccessibility } from "../../hooks";
import { useIsMobile } from "../../hooks/useIsMobile";
import { useCreateProject } from "../../hooks/mutations/useProjectMutations";
import { useRoomTypes } from "../../hooks/queries/useTaxonomyQueries";
import { getErrorMessage, proApi } from "../../lib/api";
import { notify } from "../../lib/notify";
import { queryKeys } from "../../lib/query-keys";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { BasicInfoSection } from "./form-sections";
import { RoomPhotosStep } from "./RoomPhotosStep.subcomponent";
import { RoomsInProjectRows } from "./RoomsInProjectRows.subcomponent";
import { useRoomUpload } from "./use-room-upload.hook";
 
/**
 * Add project — TWO steps, not three (plan §1.6).
 *
 * WHAT CHANGED
 * Step 3 was a room list plus "Add another": a page of its own, after the step
 * that created the room, for a decision that is really the running tally of
 * step 2. It is folded in — `RoomsInProjectRows` is now a band under the room
 * form — and the step count drops to the two things a pro is actually
 * deciding: what the project is, and what is in it.
 *
 * "Done — 2 rooms, 10 photos" **states what it is finishing**, which is the
 * copy shape worth keeping: a terminal button that names its own result cannot
 * be misread as "next".
 *
 * MOBILE
 * Multi-step, so by the approved mobile rule this is a full page on mobile,
 * not a drawer: a wizard whose body scrolls inside a 50%-height sheet is how
 * step 2's dropzone ends up off screen.
 */
 
interface ProjectCreationWizardProps {
	isOpen: boolean;
	onClose: () => void;
	onComplete: (projectId: string) => void;
	proId: string;
}
 
interface RoomState {
	roomType: string;
	name: string;
	areaSqft: string;
	styleTags: string[];
	budgetSpent: string;
	materials: string[];
	roomId?: number;
	photoCount: number;
}
 
const STEPS = [
	{ id: 1, label: "Basics" },
	{ id: 2, label: "Rooms & photos" },
] as const;
 
export function ProjectCreationWizard({
	isOpen,
	onClose,
	onComplete,
	proId,
}: ProjectCreationWizardProps) {
	const queryClient = useQueryClient();
 
	const [currentStep, setCurrentStep] = useState(1);
	const [createdProjectId, setCreatedProjectId] = useState<string | null>(null);
 
	// Tracks whether the user completed the wizard via Done
	// (regression #585 — discard orphaned draft projects on close).
	const finishedRef = useRef(false);
	const createdProjectIdRef = useRef<string | null>(null);
 
	// Step 1 — basics
	const [title, setTitle] = useState("");
	const [description, setDescription] = useState("");
	const [titleErrorMessage, setTitleErrorMessage] = useState<string | null>(
		null,
	);
 
	// Step 2 — rooms
	const [rooms, setRooms] = useState<RoomState[]>([]);
	const [currentRoomIndex, setCurrentRoomIndex] = useState(0);
	const [roomType, setRoomType] = useState("");
	const [roomName, setRoomName] = useState("");
	const [isSavingRoom, setIsSavingRoom] = useState(false);
 
	const { data: roomTypes = [] } = useRoomTypes();
 
	const {
		fileInputRef,
		isDragOver,
		isUploading,
		roomMedia,
		setRoomMedia,
		loadRoomMedia,
		handleFileSelect,
		handleDragOver,
		handleDragLeave,
		handleDrop,
		handleSetCover,
		resetRoomMedia,
	} = useRoomUpload({
		proId,
		roomType,
		roomName,
		createdProjectId,
		rooms,
		currentRoomIndex,
		setRooms,
		setCurrentRoomIndex,
	});
 
	const createProjectMutation = useCreateProject(proId);
 
	const isSubmitting =
		createProjectMutation.isPending || isSavingRoom || isUploading;
 
	// Discard orphaned draft on close/unmount (#585)
	const discardPendingDraft = () => {
		const pendingProjectId = createdProjectIdRef.current;
		if (pendingProjectId && !finishedRef.current) {
			createdProjectIdRef.current = null;
			void proApi
				.deleteProject(proId, pendingProjectId)
				.catch(() => {})
				.finally(() => {
					queryClient.invalidateQueries({
						queryKey: queryKeys.projects.lists(),
					});
				});
		}
	};
	const handleClose = () => {
		discardPendingDraft();
		onClose();
	};
 
	// biome-ignore lint/correctness/useExhaustiveDependencies: cleanup on unmount only
	useEffect(() => {
		return () => {
			discardPendingDraft();
		};
	}, []);
 
	const { dialogRef, handleFocusTrap } = useDialogAccessibility(handleClose);
	const isMobile = useIsMobile();
 
	const resetRoomForm = () => {
		setRoomType("");
		setRoomName("");
	};
 
	// biome-ignore lint/correctness/useExhaustiveDependencies: reset on open/close only
	useEffect(() => {
		if (!isOpen) {
			setCurrentStep(1);
			setCreatedProjectId(null);
			createdProjectIdRef.current = null;
			finishedRef.current = false;
			setTitle("");
			setDescription("");
			setTitleErrorMessage(null);
			setRooms([]);
			setCurrentRoomIndex(0);
			resetRoomForm();
			resetRoomMedia();
		}
	}, [isOpen]);
 
	// Re-populate the room form when the pro picks a saved room to edit.
	// biome-ignore lint/correctness/useExhaustiveDependencies: only on step/index change
	useEffect(() => {
		if (currentStep !== 2) return;
		const room = rooms[currentRoomIndex];
		if (!room?.roomId) return;
		setRoomType(room.roomType);
		setRoomName(room.name || "");
		loadRoomMedia(room.roomId);
	}, [currentStep, currentRoomIndex]);
 
	const getRoomTypeName = (code: string) =>
		roomTypes.find((t) => t.code === code)?.displayName || code;
 
	/**
	 * The rows, with the live photo count substituted for the room the form is
	 * showing. `useRoomUpload` creates a room on its first upload with
	 * `photoCount: 0` and only `handleSaveRoom` writes the stored figure back,
	 * so reading `rooms[i].photoCount` alone would print a stale 0 next to a
	 * strip of visible thumbnails — and on the Done button, which states what
	 * it is finishing.
	 */
	const roomRows = rooms.map((room, index) =>
		index === currentRoomIndex
			? { ...room, photoCount: roomMedia.length }
			: room,
	);
 
	const totalPhotos = roomRows.reduce((sum, room) => sum + room.photoCount, 0);
 
	/** Step 1 → 2. Creates the draft project the rooms hang off. */
	const handleContinue = async () => {
		const titleError = validateProjectTitle(title);
		if (titleError) {
			setTitleErrorMessage(projectTitleErrorMessage(titleError));
			return;
		}
		const normalizedTitle = normalizeProjectTitle(title);
 
		try {
			let projectId = createdProjectId;
			if (!projectId) {
				const result = await createProjectMutation.mutateAsync({
					title: normalizedTitle,
					description: description || null,
					useRooms: true,
				});
				projectId = result?.id || null;
				if (projectId) {
					setCreatedProjectId(projectId);
					createdProjectIdRef.current = projectId;
				}
			} else {
				// The project exists from a prior attempt — just update it.
				await proApi.updateProject(proId, projectId, {
					title: normalizedTitle,
					description: description || null,
					useRooms: true,
				});
			}
			setCurrentStep(2);
		} catch (err) {
			notify.error(getErrorMessage(err));
		}
	};
 
	/** Persists the room the form is showing, without leaving step 2. */
	const handleSaveRoom = async () => {
		Iif (!createdProjectId || !roomType) return;
		setIsSavingRoom(true);
		try {
			const roomData: { roomType: string; name?: string } = { roomType };
			Iif (roomName) roomData.name = roomName;
 
			const existingRoom = rooms[currentRoomIndex];
			if (existingRoom?.roomId) {
				await proApi.updateRoom(proId, existingRoom.roomId, roomData);
				setRooms((prev) =>
					prev.map((r, i) =>
						i === currentRoomIndex
							? {
									...r,
									roomType,
									name: roomName,
									photoCount: roomMedia.length,
								}
							: r,
					),
				);
			} else E{
				const response = await proApi.createRoom(
					proId,
					createdProjectId,
					roomData,
				);
				const createdRoom = response.data;
				if (createdRoom) {
					const newIndex = rooms.length;
					setRooms((prev) => [
						...prev,
						{
							roomType,
							name: roomName,
							areaSqft: "",
							styleTags: [],
							budgetSpent: "",
							materials: [],
							roomId: createdRoom.id,
							photoCount: roomMedia.length,
						},
					]);
					setCurrentRoomIndex(newIndex);
				}
			}
			notify.success("Room saved");
		} catch (err) {
			notify.error(getErrorMessage(err));
		} finally {
			setIsSavingRoom(false);
		}
	};
 
	const handleAddAnotherRoom = () => {
		resetRoomForm();
		setRoomMedia([]);
		setCurrentRoomIndex(rooms.length);
	};
 
	const handleEditRoom = (index: number) => {
		setCurrentRoomIndex(index);
	};
 
	const handleRemoveRoom = async (index: number) => {
		const room = rooms[index];
		Iif (!room?.roomId) return;
		try {
			await proApi.deleteRoom(proId, room.roomId);
			setRooms((prev) => prev.filter((_, i) => i !== index));
			// The form was showing the room that just went away.
			Eif (index === currentRoomIndex) {
				resetRoomForm();
				setRoomMedia([]);
				setCurrentRoomIndex(Math.max(rooms.length - 2, 0));
			}
		} catch (err) {
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleDone = () => {
		Iif (!createdProjectId) return;
		finishedRef.current = true;
		onComplete(createdProjectId);
	};
 
	if (!isOpen) return null;
 
	// ─── Shared pieces ──────────────────────────────────────────────────
 
	const stepper = (
		<div className="flex items-center gap-2">
			{/* The one index-red mark on this surface: a 3px bar, never a fill. */}
			<span
				aria-hidden="true"
				className="h-3 w-[3px] shrink-0 bg-secondary-600"
			/>
			{STEPS.map((step, index) => (
				<span key={step.id} className="flex items-center gap-2">
					{index > 0 && (
						<span
							aria-hidden="true"
							className="h-px w-6 shrink-0 bg-border-strong"
						/>
					)}
					<span
						aria-current={currentStep === step.id ? "step" : undefined}
						className={cn(
							"flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider",
							currentStep === step.id
								? "text-foreground-default"
								: "text-foreground-muted",
						)}
					>
						<span
							aria-hidden="true"
							className={cn(
								"size-1.5 rounded-full",
								currentStep >= step.id
									? "bg-foreground-default"
									: "bg-border-strong",
							)}
						/>
						{step.label}
					</span>
				</span>
			))}
			<span className="ml-auto text-xs font-semibold uppercase tracking-wider tabular-nums text-foreground-muted">
				Step {currentStep} of {STEPS.length}
			</span>
		</div>
	);
 
	const stepContent =
		currentStep === 1 ? (
			<BasicInfoSection
				title={title}
				description={description}
				onTitleChange={(v) => {
					setTitle(v);
					if (titleErrorMessage && validateProjectTitle(v) === null) {
						setTitleErrorMessage(null);
					}
				}}
				onDescriptionChange={setDescription}
				titleError={titleErrorMessage}
			/>
		) : (
			<div className="space-y-5">
				<RoomPhotosStep
					roomType={roomType}
					roomName={roomName}
					roomMedia={roomMedia}
					isDragOver={isDragOver}
					isUploading={isUploading}
					roomTypes={roomTypes}
					fileInputRef={fileInputRef}
					onRoomTypeChange={setRoomType}
					onRoomNameChange={setRoomName}
					onFileSelect={handleFileSelect}
					onDragOver={handleDragOver}
					onDragLeave={handleDragLeave}
					onDrop={handleDrop}
					onSetCover={handleSetCover}
					onSaveRoom={handleSaveRoom}
					canSaveRoom={Boolean(roomType) && roomMedia.length > 0 && !isSubmitting}
				/>
				<RoomsInProjectRows
					rooms={roomRows}
					getRoomTypeName={getRoomTypeName}
					currentIndex={rooms[currentRoomIndex]?.roomId ? currentRoomIndex : undefined}
					onEditRoom={handleEditRoom}
					onRemoveRoom={handleRemoveRoom}
				/>
			</div>
		);
 
	const footerContent =
		currentStep === 1 ? (
			<div className="flex items-center gap-3">
				<Button type="button" variant="outline" onClick={handleClose}>
					Cancel
				</Button>
				<div className="flex-1" />
				<Button
					type="button"
					onClick={handleContinue}
					isLoading={isSubmitting}
					disabled={!title.trim() || isSubmitting}
				>
					Continue
				</Button>
			</div>
		) : (
			<div className="flex flex-wrap items-center gap-3">
				<Button
					type="button"
					variant="ghost"
					onClick={() => setCurrentStep(1)}
					disabled={isSubmitting}
				>
					<ArrowLeft aria-hidden="true" />
					Basics
				</Button>
				<div className="flex-1" />
				<Button
					type="button"
					variant="outline"
					onClick={handleAddAnotherRoom}
					disabled={isSubmitting}
				>
					+ Another room
				</Button>
				<Button
					type="button"
					onClick={handleDone}
					disabled={rooms.length === 0 || isSubmitting}
				>
					{/* States what it is finishing. */}
					Done — {roomRows.length}{" "}
					{roomRows.length === 1 ? "room" : "rooms"},{" "}
					{totalPhotos} {totalPhotos === 1 ? "photo" : "photos"}
				</Button>
			</div>
		);
 
	const heading =
		currentStep === 1 || !title.trim() ? "Add project" : `Add project · ${title}`;
 
	// ─── Mobile: full page (multi-step, so never a drawer) ──────────────
	if (isMobile) {
		return (
			<div className="fixed inset-0 z-[60] flex flex-col bg-background-base animate-page-in">
				<div className="flex h-14 shrink-0 items-center gap-3 border-b border-border-default bg-background-elevated px-4">
					<button
						type="button"
						onClick={handleClose}
						className="-ml-2 rounded-md p-2 text-foreground-muted hover:text-foreground-default"
						aria-label="Go back"
					>
						<ArrowLeft className="h-5 w-5" />
					</button>
					<h2 className="truncate font-heading text-lg font-bold text-foreground-default">
						{heading}
					</h2>
				</div>
				<div className="shrink-0 border-b border-border-default bg-background-base px-4 py-2">
					{stepper}
				</div>
				<div className="flex-1 overflow-y-auto p-4">{stepContent}</div>
				<div className="shrink-0 border-t border-border-default bg-background-elevated px-4 py-4">
					{footerContent}
				</div>
			</div>
		);
	}
 
	// ─── Desktop: dialog ────────────────────────────────────────────────
	return (
		<div
			className="fixed inset-0 z-50 flex flex-col items-center justify-center p-4"
			tabIndex={-1}
		>
			<button
				type="button"
				aria-label="Close modal"
				className="fixed inset-0 cursor-default bg-black/50"
				onClick={handleClose}
				tabIndex={-1}
			/>
 
			<div
				ref={dialogRef}
				role="dialog"
				aria-modal="true"
				aria-labelledby="project-wizard-dialog-title"
				onKeyDown={handleFocusTrap}
				className="relative mx-auto flex max-h-[90vh] w-full max-w-3xl flex-col rounded-lg bg-background-elevated shadow-xl"
			>
				<div className="shrink-0 rounded-t-lg border-b border-border-strong px-6 py-3">
					<div className="flex items-center justify-between gap-4">
						<h2
							id="project-wizard-dialog-title"
							className="truncate text-xs font-semibold uppercase tracking-wider text-foreground-muted"
						>
							{heading}
						</h2>
						<button
							type="button"
							onClick={handleClose}
							aria-label="Close"
							className="rounded-sm p-1 text-foreground-subtle hover:text-foreground-default"
						>
							<X className="h-4 w-4" />
						</button>
					</div>
					<div className="mt-2">{stepper}</div>
				</div>
 
				<div className="flex-1 overflow-y-auto p-6">{stepContent}</div>
 
				<div className="shrink-0 rounded-b-lg border-t border-border-default px-6 py-4">
					{footerContent}
				</div>
			</div>
		</div>
	);
}