All files / src/scripts unified-contact-form.ts

93.77% Statements 226/241
70.27% Branches 104/148
100% Functions 25/25
95.34% Lines 205/215

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                                        17x                         5x     5x 5x 5x 5x         213x     213x 193x 213x 191x           45x     47x         47x       47x 47x 47x   47x     47x     47x 47x 47x 47x     47x 47x     47x     47x     47x       47x       47x   47x 223x     47x 188x     188x   188x 188x 188x         47x 1x 1x 1x           47x     235x     42x 19x               19x 19x 19x 19x 19x 19x       509x 193x 193x 193x 193x 193x 193x 193x       125x       47x   48x 48x 2x 2x 2x 2x     46x         47x 3x   3x 3x 3x 3x     3x 3x 2x 2x 2x           47x 44x         64x 64x   47x 47x               47x     47x 5x 5x       5x 5x 1x   4x                               47x     47x 4x 4x 4x 4x       47x 4x 3x 3x   1x 1x 1x 1x                   47x 47x 5x   5x         5x         5x 5x 5x       47x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x       9x 9x 9x     9x             47x 47x 25x 25x     24x             24x 24x   24x 24x 24x   24x 24x     25x 25x   25x         25x   18x 18x     25x 25x 25x 24x 24x 24x 24x 1x   24x 1x   24x 10x 10x     14x     14x     14x   25x 25x 25x 14x   14x   25x                           25x 14x         14x 14x           12x                     12x 2x     2x       2x         2x     10x   9x   9x 9x         9x                       9x     1x     1x 1x     2x 2x   2x   14x 14x 14x 14x                   123x     47x 47x       45x 45x  
/**
 * Unified Contact Form - Client-side behavior for both placement variants
 * (sidebar, inline).
 *
 * Reads widget configuration from data attributes on .unified-contact-widget
 * containers and wires up CTA triggers, form validation, submission, duplicate
 * detection, success/reset flows, the WhatsApp prefill and analytics tracking.
 */
 
import { LEAD_CONSENT_VERSION } from "@interioring/utils/constants/consent";
import { getCachedHomeownerUser } from "../components/homeowner/auth-check";
import { pushDataLayerEvent } from "../lib/gtm";
import {
	extractPhoneDigits,
	validateCustomerName,
	validateIndianPhoneNumber,
} from "../lib/validation";
import { firstTouch } from "./attribution";
 
function getTracker(): DRTracker | undefined {
	return window.DRTracker;
}
 
/**
 * The WhatsApp message to Interioring, built when the chat is opened so it
 * carries whatever the homeowner has already typed into the form. The first
 * line matches the SSR href in ContactFormFields.astro.
 */
export function whatsappPrefill(
	proName: string,
	pageUrl: string,
	typed: { name?: string; need?: string } = {},
): string {
	const lines = [
		`Hi Interioring, I'd like to talk to ${proName} about my home interiors.`,
	];
	if (typed.name) lines.push(`My name: ${typed.name}`);
	if (typed.need) lines.push(`Looking for: ${typed.need}`);
	lines.push(pageUrl);
	return lines.join("\n");
}
 
/** Add or remove one id in an element's aria-describedby list. */
function toggleDescribedBy(el: Element, id: string, on: boolean): void {
	const ids = new Set(
		(el.getAttribute("aria-describedby") ?? "").split(" ").filter(Boolean),
	);
	if (on) ids.add(id);
	else ids.delete(id);
	if (ids.size) el.setAttribute("aria-describedby", [...ids].join(" "));
	else el.removeAttribute("aria-describedby");
}
 
// Ids must stay unique: a page can render this form twice (the project page
// has a mobile and a desktop copy), so ids are numbered per widget, not per
// placement.
let widgetCount = 0;
 
function wireWidget(widget: HTMLElement): void {
	const uid = `ucf-${++widgetCount}`;
	// Prefer the container's data-pro-id; fall back to the form's hidden
	// proId input so the value survives even if the dataset attr is missing
	// (#794).
	const proId =
		widget.dataset.proId ||
		(widget.querySelector('input[name="proId"]') as HTMLInputElement | null)
			?.value ||
		"";
	const proName = widget.dataset.proName ?? "";
	const placement = widget.dataset.placement ?? "sidebar";
	const city = widget.dataset.city?.trim() ?? "";
 
	const ctaTrigger = widget.querySelector(
		".ucf-cta-trigger",
	) as HTMLElement | null;
	const formContainer = widget.querySelector(
		".ucf-form-container",
	) as HTMLElement | null;
	const form = widget.querySelector(".ucf-form") as HTMLFormElement | null;
	const successDiv = widget.querySelector(".ucf-success") as HTMLElement | null;
	const errorDiv = widget.querySelector(".ucf-error") as HTMLElement | null;
	const duplicateWarning = widget.querySelector(
		".ucf-duplicate-warning",
	) as HTMLElement | null;
	const resetBtn = widget.querySelector(".ucf-reset-btn") as HTMLElement | null;
	const successMessage = widget.querySelector(
		".ucf-success-message",
	) as HTMLElement | null;
	const otherDescContainer = widget.querySelector(
		".ucf-other-description",
	) as HTMLElement | null;
	const requirementSelect = form?.querySelector(
		'select[name="requirementType"]',
	) as HTMLSelectElement | null;
	const requirementDesc = form?.querySelector(
		'textarea[name="requirementDescription"]',
	) as HTMLTextAreaElement | null;
 
	const btnCallback = widget.querySelector(
		".ucf-btn-callback",
	) as HTMLButtonElement | null;
 
	Iif (!form || !errorDiv) return;
 
	const control = (name: string) =>
		form.querySelector<HTMLElement>(`[name="${name}"]`);
 
	// --- Accessibility: associate labels with inputs via for/id ---
	form.querySelectorAll<HTMLElement>("label").forEach((label) => {
		const input = label.parentElement?.querySelector(
			"input, select, textarea",
		) as HTMLElement | null;
		Eif (input && !input.id) {
			const fieldName =
				(input as HTMLInputElement).name || crypto.randomUUID().slice(0, 8);
			input.id = `${uid}-${fieldName}`;
			label.setAttribute("for", input.id);
		}
	});
 
	// Format hints (e.g. the phone's "10 digits…") describe their field.
	for (const hint of form.querySelectorAll<HTMLElement>(".ucf-field-hint")) {
		hint.id = `${uid}-${hint.dataset.field}-hint`;
		const field = control(hint.dataset.field ?? "");
		Eif (field) toggleDescribedBy(field, hint.id, true);
	}
 
	// --- Field-level inline errors ---
	// Each error is tied to its field (aria-invalid + aria-describedby) and
	// announced (role="alert" in the markup), as the sign-in modal does.
	const fieldErrors = [
		...form.querySelectorAll<HTMLElement>(".ucf-field-error"),
	];
	for (const el of fieldErrors) el.id = `${uid}-${el.dataset.field}-error`;
 
	function showFieldError(fieldName: string, message: string): void {
		const el = fieldErrors.find((e) => e.dataset.field === fieldName);
		Iif (!el) {
			// Fallback to central error div if inline element is missing
			if (errorDiv) {
				errorDiv.textContent = message;
				errorDiv.classList.remove("hidden");
			}
			return;
		}
		el.textContent = message;
		el.classList.remove("hidden");
		const field = control(fieldName);
		Eif (field) {
			field.setAttribute("aria-invalid", "true");
			toggleDescribedBy(field, el.id, true);
		}
	}
	function clearFieldError(fieldName: string): void {
		const el = fieldErrors.find((e) => e.dataset.field === fieldName);
		Iif (!el) return;
		el.textContent = "";
		el.classList.add("hidden");
		const field = control(fieldName);
		Eif (field) {
			field.removeAttribute("aria-invalid");
			toggleDescribedBy(field, el.id, false);
		}
	}
	function clearFieldErrors(): void {
		for (const el of fieldErrors) clearFieldError(el.dataset.field ?? "");
	}
 
	// --- Duplicate check ---
	let isDuplicate = false;
	function checkDuplicate(): void {
		const ts = localStorage.getItem(`inquiry_${proId}`);
		if (ts && Date.now() - parseInt(ts, 10) < 86400000) {
			isDuplicate = true;
			Eif (duplicateWarning) {
				duplicateWarning.textContent = `You’ve already reached out to ${proName} in the last 24 hours. They have your details.`;
				duplicateWarning.classList.remove("hidden");
			}
		} else {
			isDuplicate = false;
		}
	}
 
	// --- CTA trigger (inline) ---
	if (ctaTrigger && placement !== "sidebar") {
		function handleCtaActivate(): void {
			// Inline: hide CTA, show form
			ctaTrigger?.classList.add("hidden");
			formContainer?.classList.remove("hidden");
			getTracker()?.click("pro", proId, proId, "contact_cta_click");
			checkDuplicate();
		}
 
		ctaTrigger.addEventListener("click", handleCtaActivate);
		ctaTrigger.addEventListener("keydown", (e: KeyboardEvent) => {
			Eif (e.key === "Enter" || e.key === " ") {
				e.preventDefault();
				handleCtaActivate();
			}
		});
	}
 
	// Sidebar: check duplicate immediately since form is always visible
	if (placement === "sidebar") {
		checkDuplicate();
	}
 
	// --- Clear inline error on field interaction ---
	function handleFieldInteraction(e: Event): void {
		const fieldName = (e.target as HTMLElement as HTMLInputElement).name;
		Eif (fieldName) clearFieldError(fieldName);
	}
	form.addEventListener("input", handleFieldInteraction);
	form.addEventListener("change", handleFieldInteraction);
 
	// --- Live name validation on blur ---
	// Uses the canonical validateCustomerName so live feedback always matches
	// the submit-time verdict. (The previous inline `oninput` handler in
	// ContactFormFields.astro hand-rolled a regex that Astro's attribute
	// compilation mangled — see git history.) The clear-on-input listener
	// above wipes the error as the user types; this re-validates on blur.
	const nameInput = form.querySelector(
		'input[name="customerName"]',
	) as HTMLInputElement | null;
	nameInput?.addEventListener("blur", () => {
		const value = nameInput.value.trim().replace(/\s+/g, " ");
		Iif (!value) {
			clearFieldError("customerName");
			return;
		}
		const error = validateCustomerName(value);
		if (error) {
			showFieldError("customerName", error);
		} else {
			clearFieldError("customerName");
		}
	});
 
	// --- Normalize the phone field on blur ---
	// Inquiries accept any Indian-mobile format (with/without +91, spaces, or a
	// leading 0). ContactFormFields.astro used to carry an inline
	// `oninput="...replace(/\D/g,'')"` digit-strip, but Astro's attribute
	// compilation mangled the regex (\D -> D) so it stripped nothing; combined
	// with the old maxlength="10" a pasted "+91 …" was truncated to garbage and
	// the inquiry POST 500'd with no success shown. extractPhoneDigits (backed
	// by libphonenumber) collapses every accepted format to the 10-digit
	// national number, so blur leaves a clean value and submit always sends
	// digits. Unparseable input (mid-typed, too short) falls back to a plain
	// digit-strip — harmless, since submit re-normalizes and validation rejects
	// anything that isn't a valid mobile.
	const phoneInput = form.querySelector(
		'input[name="customerPhone"]',
	) as HTMLInputElement | null;
	phoneInput?.addEventListener("blur", () => {
		Iif (!phoneInput.value.trim()) return;
		const normalized = extractPhoneDigits(phoneInput.value);
		Eif (normalized && normalized !== phoneInput.value)
			phoneInput.value = normalized;
	});
 
	// --- Show/hide "Other" description field ---
	requirementSelect?.addEventListener("change", () => {
		if (requirementSelect.value === "other") {
			otherDescContainer?.classList.remove("hidden");
			Eif (requirementDesc) requirementDesc.required = true;
		} else {
			otherDescContainer?.classList.add("hidden");
			Eif (requirementDesc) {
				requirementDesc.required = false;
				requirementDesc.value = "";
			}
		}
	});
 
	// --- WhatsApp link (#1086) ---
	// A plain link to Interioring's number, so nothing is submitted. It still
	// counts as the designer's "WhatsApp Clicks" in the portal analytics. The
	// message is rebuilt on each tap (before the browser follows the link) so
	// it names the page and carries anything already typed into the form.
	const whatsappLink = widget.querySelector<HTMLAnchorElement>("a.ucf-whatsapp");
	whatsappLink?.addEventListener("click", () => {
		const reqType = requirementSelect?.value ?? "";
		const need =
			reqType === "other"
				? requirementDesc?.value.trim()
				: reqType
					? requirementSelect?.selectedOptions[0]?.textContent?.trim()
					: undefined;
		const message = whatsappPrefill(
			proName,
			window.location.origin + window.location.pathname,
			{ name: nameInput?.value.trim().replace(/\s+/g, " "), need },
		);
		const base = whatsappLink.href.split("?")[0];
		whatsappLink.href = `${base}?text=${encodeURIComponent(message)}`;
		getTracker()?.click("pro", proId, proId, "whatsapp_redirect");
	});
 
	// --- Reset button ---
	resetBtn?.addEventListener("click", () => {
		successDiv?.classList.add("hidden");
		form?.classList.remove("hidden");
		form?.reset();
		errorDiv?.classList.add("hidden");
		Eif (errorDiv) errorDiv.textContent = "";
		clearFieldErrors();
		otherDescContainer?.classList.add("hidden");
		Eif (requirementDesc) {
			requirementDesc.required = false;
			requirementDesc.value = "";
		}
		duplicateWarning?.classList.add("hidden");
		checkDuplicate();
		nameInput?.focus();
	});
 
	function showSuccess(message: string): void {
		form?.classList.add("hidden");
		Eif (successMessage) successMessage.textContent = message;
		successDiv?.classList.remove("hidden");
		// The form (and the focused button) just vanished: move focus to the
		// confirmation so it is read out instead of focus falling to <body>.
		successMessage?.focus();
	}
 
	// --- Form submission ---
	// The button is never `disabled`: disabling the focused button drops focus
	// to <body>. Validation runs first; while sending, aria-disabled plus the
	// `sending` flag block a second submit.
	let sending = false;
	form.addEventListener("submit", async (e: SubmitEvent) => {
		e.preventDefault();
		if (sending) return;
 
		// Block duplicate submissions
		Iif (isDuplicate) {
			showSuccess(
				`You’ve already sent an inquiry to ${proName} in the last 24 hours.`,
			);
			return;
		}
 
		const activeBtn = btnCallback;
		Iif (!activeBtn) return;
 
		errorDiv.classList.add("hidden");
		errorDiv.textContent = "";
		clearFieldErrors();
 
		const formData = new FormData(form);
		const phone = extractPhoneDigits(
			(formData.get("customerPhone") as string) ?? "",
		);
		const name = ((formData.get("customerName") as string) ?? "").trim();
		const reqType = (formData.get("requirementType") as string) ?? "";
		const otherDesc =
			reqType === "other"
				? ((formData.get("requirementDescription") as string) ?? "").trim()
				: undefined;
 
		// Validate all fields, in form order, and show inline errors.
		const invalid: string[] = [];
		function fail(field: string, message: string): void {
			showFieldError(field, message);
			invalid.push(field);
		}
 
		const normalizedName = name.replace(/\s+/g, " ");
		const nameError = validateCustomerName(normalizedName);
		if (nameError) fail("customerName", nameError);
		const phoneError = validateIndianPhoneNumber(phone);
		if (phoneError) fail("customerPhone", phoneError);
		if (!reqType) fail("requirementType", "Please select what you are looking for.");
		if (reqType === "other" && !otherDesc) {
			fail("requirementDescription", "Please describe your requirement.");
		}
		if (!formData.get("consent")) {
			fail("consent", "Please tick the box to agree to be contacted.");
		}
		if (invalid.length > 0) {
			control(invalid[0])?.focus();
			return;
		}
 
		const activeBtnLabel = activeBtn.querySelector(
			".ucf-btn-label",
		) as HTMLElement | null;
		const activeBtnIcon = activeBtn.querySelector(
			".ucf-btn-icon",
		) as HTMLElement | null;
		const originalLabel = activeBtnLabel?.textContent ?? "";
 
		sending = true;
		activeBtn.setAttribute("aria-disabled", "true");
		if (activeBtnLabel) activeBtnLabel.textContent = "Sending…";
		Eif (activeBtnIcon) activeBtnIcon.classList.add("hidden");
 
		const email = ((formData.get("customerEmail") as string) ?? "").trim();
 
		const data: Record<string, string | boolean | undefined> = {
			...firstTouch(),
			consent: true,
			consentVersion: LEAD_CONSENT_VERSION,
			entryType: "form",
			proId,
			customerName: normalizedName,
			customerPhone: phone,
			type: "form_submit",
			requirementType: reqType,
			sourceType: "marketplace",
			sourcePage: window.location.pathname,
			...(city ? { city } : {}),
		};
		Iif (email) data.customerEmail = email;
		Iif (otherDesc) {
			data.requirementDescription = otherDesc;
			data.requirement = otherDesc;
		}
 
		try {
			const response = await fetch("/api/inquiry", {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(data),
			});
 
			const result = (await response.json()) as {
				success: boolean;
				code?: string;
				data?: { id?: string };
				error?: string;
			};
 
			// Restrict Direct Contact: a 401 means this pro requires a logged-in
			// homeowner. Open the login/register modal and re-submit once the
			// homeowner authenticates (reusing the app-wide auth events). No
			// error is shown — logging in is the expected next step.
			if (response.status === 401 || result.code === "LOGIN_REQUIRED") {
				window.addEventListener(
					"ho:auth-success",
					() => {
						activeBtn.click();
					},
					{ once: true },
				);
				window.dispatchEvent(
					new CustomEvent("ho:open-auth-modal", {
						detail: { mode: "register" },
					}),
				);
				return;
			}
 
			if (result.success) {
				// Store in localStorage for duplicate detection
				localStorage.setItem(`inquiry_${proId}`, String(Date.now()));
 
				const tracker = getTracker();
				tracker?.click("pro", proId, proId, "callback_form_submit");
 
				// GA4 conversion (via GTM). Coexists with DRTracker above.
				// logged_in: optimistic (cached, no network) homeowner auth state
				// so GA4 can segment conversions by authenticated vs anonymous.
				pushDataLayerEvent("generate_lead", {
					lead_type: "callback",
					pro_id: proId,
					pro_name: proName,
					// Canonical page dimension shared across all conversion events
					// so GA can slice every conversion by page. See
					// apps/marketplace/CLAUDE.md §Analytics.
					page_path: window.location.pathname,
					logged_in: getCachedHomeownerUser() != null,
				});
 
				// No timing promise here: response time is not tracked.
				showSuccess(`Inquiry sent to ${proName}.`);
			} else {
				const msg =
					typeof result.error === "string"
						? result.error
						: "Something went wrong. Please try again.";
				errorDiv.textContent = msg;
				errorDiv.classList.remove("hidden");
			}
		} catch (err) {
			console.error("[UnifiedContactForm] Submission failed:", err);
			errorDiv.textContent =
				"Something went wrong. Please try again, or message us on WhatsApp.";
			errorDiv.classList.remove("hidden");
		} finally {
			sending = false;
			activeBtn.removeAttribute("aria-disabled");
			Eif (activeBtnLabel) activeBtnLabel.textContent = originalLabel;
			Eif (activeBtnIcon) activeBtnIcon.classList.remove("hidden");
		}
	});
}
 
// ClientRouter swaps pages without re-running bundled modules, so a profile
// reached by in-site navigation needs its widgets wired on astro:page-load.
// The flag stops a widget being wired twice (the first page-load fires after
// this module's own pass).
function wireWidgets(): void {
	for (const widget of document.querySelectorAll<HTMLElement>(
		".unified-contact-widget:not([data-ucf-wired])",
	)) {
		widget.dataset.ucfWired = "";
		wireWidget(widget);
	}
}
 
wireWidgets();
document.addEventListener("astro:page-load", wireWidgets);