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

92.09% Statements 198/215
66.43% Branches 97/146
94.11% Functions 16/17
93.84% Lines 183/195

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                        11x     28x 28x 28x 28x 28x   28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x     28x 28x 28x   28x 28x   28x     28x   17x 36x 17x 17x 17x                   42x 87x 42x 42x 42x         18x 72x 72x         28x 112x 112x 112x 112x 112x 112x         28x   29x 29x 2x 2x 2x   2x     27x         28x 6x 6x   3x 3x 3x     3x 3x   6x 6x     6x 6x 2x 2x 2x           28x 22x         2x 2x 2x     28x 28x       42x 42x   28x 28x     28x 4x 3x 3x   1x 1x 1x 1x           28x 1x   28x         28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x       28x 17x     17x                 17x 17x     17x 17x   17x 17x 17x   17x 17x 17x     17x 17x   17x 17x 17x 17x   17x 17x 17x 17x 17x         17x   9x 9x 9x 9x     17x 17x 17x 5x 5x   17x 17x 6x 6x   17x 5x 5x   17x 1x 1x   17x 9x 9x     8x   17x                 17x 8x         8x 8x           6x           6x   5x   5x 5x   5x 1x 1x     1x         5x 5x 5x       5x   1x     1x 1x 1x     2x 2x 2x 2x   8x 8x 8x 8x        
/**
 * Unified Contact Form - Client-side behavior for all placement variants
 * (sidebar, inline, sticky-mobile).
 *
 * Reads widget configuration from data attributes on .unified-contact-widget
 * containers and wires up CTA triggers, form validation, submission, duplicate
 * detection, success/reset flows, and analytics tracking.
 */
 
import { validateCustomerName, validateIndianPhoneNumber, extractPhoneDigits } from '../lib/validation';
 
function getTracker(): DRTracker | undefined {
	return window.DRTracker;
}
 
document.querySelectorAll<HTMLElement>(".unified-contact-widget").forEach((widget) => {
	const proId = widget.dataset.proId ?? "";
	const proName = widget.dataset.proName ?? "";
	const proWhatsapp = widget.dataset.proWhatsapp ?? "";
	const placement = widget.dataset.placement ?? "sidebar";
 
	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 fallbackLink = widget.querySelector(".ucf-fallback-link") 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 submitActionInput = form?.querySelector("input[name=\"submitAction\"]") as HTMLInputElement | null;
	const requirementSelect = form?.querySelector("select[name=\"requirementType\"]") as HTMLSelectElement | null;
	const requirementDesc = form?.querySelector("textarea[name=\"requirementDescription\"]") as HTMLTextAreaElement | null;
 
	// Sticky-mobile specific elements
	const overlay = widget.querySelector(".ucf-overlay") as HTMLElement | null;
	const panel = widget.querySelector(".ucf-panel") as HTMLElement | null;
	const panelClose = widget.querySelector(".ucf-panel-close") as HTMLElement | null;
 
	const btnWhatsapp = widget.querySelector(".ucf-btn-whatsapp") as HTMLButtonElement | null;
	const btnCallback = widget.querySelector(".ucf-btn-callback") as HTMLButtonElement | null;
 
	Iif (!form || !errorDiv) return;
 
	// --- Field-level inline errors ---
	const fieldErrors = form.querySelectorAll<HTMLElement>(".ucf-field-error");
	function showFieldError(fieldName: string, message: string): void {
		for (const el of fieldErrors) {
			if (el.dataset.field === fieldName) {
				el.textContent = message;
				el.classList.remove("hidden");
				return;
			}
		}
		// Fallback to central error div if inline element is missing
		if (errorDiv) {
			errorDiv.textContent = message;
			errorDiv.classList.remove("hidden");
		}
	}
	function clearFieldError(fieldName: string): void {
		for (const el of fieldErrors) {
			if (el.dataset.field === fieldName) {
				el.textContent = "";
				el.classList.add("hidden");
				return;
			}
		}
	}
	function clearFieldErrors(): void {
		for (const el of fieldErrors) {
			el.textContent = "";
			el.classList.add("hidden");
		}
	}
 
	// --- 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);
			const uid = `ucf-${placement}-${fieldName}`;
			input.id = uid;
			label.setAttribute("for", uid);
		}
	});
 
	// --- 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\u2019ve already reached out to ${proName}. They should get back to you soon!`;
				duplicateWarning.classList.remove("hidden");
			}
		} else {
			isDuplicate = false;
		}
	}
 
	// --- CTA trigger (inline + sticky-mobile) ---
	if (ctaTrigger && placement !== "sidebar") {
		function handleCtaActivate(): void {
			if (placement === "sticky-mobile") {
				// Open slide-up panel
				overlay?.classList.remove("hidden");
				panel?.classList.remove("hidden");
				document.body.style.overflow = "hidden";
			} else {
				// 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();
	}
 
	// --- Sticky-mobile close ---
	function closePanel(): void {
		overlay?.classList.add("hidden");
		panel?.classList.add("hidden");
		document.body.style.overflow = "";
	}
 
	panelClose?.addEventListener("click", closePanel);
	overlay?.addEventListener("click", closePanel);
 
	// --- 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);
 
	// --- 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 = "";
			}
		}
	});
 
	// --- Button click handlers to set submitAction ---
	btnWhatsapp?.addEventListener("click", () => {
		Eif (submitActionInput) submitActionInput.value = "whatsapp";
	});
	btnCallback?.addEventListener("click", () => {
		if (submitActionInput) submitActionInput.value = "callback";
	});
 
	// --- Reset button ---
	resetBtn?.addEventListener("click", () => {
		successDiv?.classList.add("hidden");
		form?.classList.remove("hidden");
		form?.reset();
		errorDiv?.classList.add("hidden");
		Eif (errorDiv) errorDiv.textContent = "";
		clearFieldErrors();
		fallbackLink?.classList.add("hidden");
		otherDescContainer?.classList.add("hidden");
		Eif (requirementDesc) {
			requirementDesc.required = false;
			requirementDesc.value = "";
		}
		duplicateWarning?.classList.add("hidden");
		checkDuplicate();
	});
 
	// --- Form submission ---
	form.addEventListener("submit", async (e: SubmitEvent) => {
		e.preventDefault();
 
		// Block duplicate submissions
		Iif (isDuplicate) {
			if (successMessage) {
				successMessage.textContent = `You've already sent an inquiry to ${proName}. They'll get back to you soon!`;
			}
			form.classList.add("hidden");
			successDiv?.classList.remove("hidden");
			return;
		}
 
		const action = submitActionInput?.value ?? "callback";
		const isWhatsapp = action === "whatsapp";
 
		// Determine which button was clicked
		const activeBtn = isWhatsapp ? (btnWhatsapp ?? btnCallback) : (btnCallback ?? btnWhatsapp);
		Iif (!activeBtn) 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 ?? "";
 
		activeBtn.disabled = true;
		Eif (activeBtnLabel) activeBtnLabel.textContent = "Sending...";
		Eif (activeBtnIcon) activeBtnIcon.classList.add("hidden");
 
		// Disable the other button too
		const otherBtn = isWhatsapp ? btnCallback : btnWhatsapp;
		Eif (otherBtn) otherBtn.disabled = true;
 
		errorDiv.classList.add("hidden");
		errorDiv.textContent = "";
		clearFieldErrors();
		fallbackLink?.classList.add("hidden");
 
		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 and show inline errors
		let hasError = false;
		function restoreButtons(): void {
			Eif (activeBtn) activeBtn.disabled = false;
			Eif (activeBtnLabel) activeBtnLabel.textContent = originalLabel;
			Eif (activeBtnIcon) activeBtnIcon.classList.remove("hidden");
			Eif (otherBtn) otherBtn.disabled = false;
		}
 
		const normalizedName = name.replace(/\s+/g, " ");
		const nameError = validateCustomerName(normalizedName);
		if (nameError) {
			showFieldError("customerName", nameError);
			hasError = true;
		}
		const phoneError = validateIndianPhoneNumber(phone);
		if (phoneError) {
			showFieldError("customerPhone", phoneError);
			hasError = true;
		}
		if (!reqType) {
			showFieldError("requirementType", "Please select what you are looking for.");
			hasError = true;
		}
		if (reqType === "other" && !otherDesc) {
			showFieldError("requirementDescription", "Please describe your requirement.");
			hasError = true;
		}
		if (hasError) {
			restoreButtons();
			return;
		}
 
		const email = (formData.get("customerEmail") as string ?? "").trim();
 
		const data: Record<string, string | undefined> = {
			proId,
			customerName: normalizedName,
			customerPhone: phone,
			type: isWhatsapp ? "whatsapp" : "form_submit",
			requirementType: reqType,
			sourceType: "marketplace",
			sourcePage: window.location.pathname,
		};
		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;
				data?: { id?: string; whatsapp_redirect_url?: string };
				error?: string;
			};
 
			if (result.success) {
				// Store in localStorage for duplicate detection
				localStorage.setItem(`inquiry_${proId}`, String(Date.now()));
 
				const tracker = getTracker();
				tracker?.click("pro", proId, proId, isWhatsapp ? "whatsapp_form_submit" : "callback_form_submit");
 
				if (isWhatsapp && result.data?.whatsapp_redirect_url) {
					tracker?.click("pro", proId, proId, "whatsapp_redirect");
					Iif (window.innerWidth < 768) {
						window.location.href = result.data.whatsapp_redirect_url;
					} else {
						window.open(result.data.whatsapp_redirect_url, "_blank");
					}
				}
 
				// Show success state
				form.classList.add("hidden");
				Eif (successMessage) {
					successMessage.textContent = isWhatsapp
						? `Request sent to ${proName}!`
						: `We\u2019ve shared your details with ${proName}. They\u2019ll call you back shortly!`;
				}
				successDiv?.classList.remove("hidden");
			} else {
				const msg = typeof result.error === "string"
					? result.error
					: "Something went wrong. Please try again.";
				errorDiv.textContent = msg;
				errorDiv.classList.remove("hidden");
				Eif (proWhatsapp) fallbackLink?.classList.remove("hidden");
			}
		} catch (err) {
			console.error("[UnifiedContactForm] Submission failed:", err);
			errorDiv.textContent = "Something went wrong. You can try again or use the direct link below.";
			errorDiv.classList.remove("hidden");
			Iif (proWhatsapp) fallbackLink?.classList.remove("hidden");
		} finally {
			activeBtn.disabled = false;
			Eif (activeBtnLabel) activeBtnLabel.textContent = originalLabel;
			Eif (activeBtnIcon) activeBtnIcon.classList.remove("hidden");
			Eif (otherBtn) otherBtn.disabled = false;
		}
	});
});