const { useState, useMemo, useCallback, useEffect, useRef } = React;

let CFG = null;
// how long one try at the site config may take before it counts as failed (loadCfg)
const CFG_TIMEOUT_MS = 8000;

/* ============== App ============== */
function App() {
	const [s, setS] = useState(initialState);
	const [cfg, setCfg] = useState(null);
	const [cfgError, setCfgError] = useState("");
	// The payment mode lives OUTSIDE `s` so "start over" (setS(freshState())) never wipes it, and
	// so its async arrival re-renders. { configured }: whether online booking is open; `loading`
	// until /api/config answers, so checkout does not say booking is off before it knows.
	const [sq, setSq] = useState({ configured: false, loading: true });
	const [paying, setPaying] = useState(false); // checkout link in flight (the policies screen's busy state)
	const [payError, setPayError] = useState(""); // said on the screen that raised it; blocks advancing
	const [policyNudge, setPolicyNudge] = useState(0); // taps on the policies' blocked button; marks the unticked cards
	useEffect(() => { setPolicyNudge(0); }, [s.step]);
	// an error is read on the screen it was raised for: moving to another screen leaves it behind
	useEffect(() => { setPayError(""); }, [s.step]);

	const mounted = useRef(true);
	const redemptionRequest = useRef(null);
	const paymentRequest = useRef(null);
	const cancellationRequest = useRef(null);
	const restoreRedemption = useRef(pendingRedemption(s));
	const checkoutRecoveryRequest = useRef(null);
	const restoreCheckout = useRef(pendingCheckoutRecovery(s));
	// Load site config with retry-and-backoff so a single cold-start / Neon-autosuspend
	// blip self-heals instead of stranding the user on an error. Reused by click-to-retry.
	const loadCfg = useCallback(async () => {
		if (mounted.current) setCfgError("");
		const delays = [400, 900, 1800, 3500]; // backoff between attempts; one final try after the last
		for (let attempt = 0; ; attempt++) {
			// a request that hangs counts as a failed attempt, so the boot screen always ends in the
			// studio or in "Tap to try again", never in "Loading the studio…" for good
			const controller = new AbortController();
			const timeout = setTimeout(() => controller.abort(), CFG_TIMEOUT_MS);
			try {
				const r = await fetch("/api/site-config", { cache: "no-store", signal: controller.signal });
				if (!r.ok) throw new Error("site config request failed");
				const d = await r.json();
				if (!d || !d.config) throw new Error("site config missing");
				if (mounted.current) {
					CFG = d.config;
					setBrand(d.config.brand || DEFAULT_BRAND);
					setCfg(d.config);
					setCfgError("");
				}
				return;
			} catch (e) {
				if (!mounted.current) return;
				if (attempt >= delays.length) {
					setCfgError("The booking page couldn’t be loaded. Try again.");
					return;
				}
				await new Promise((res) => setTimeout(res, delays[attempt]));
			} finally {
				clearTimeout(timeout);
			}
		}
	}, []);

	useEffect(() => {
		mounted.current = true;
		loadCfg();
		fetch("/api/config")
			.then((r) => r.json())
			.then((d) => {
				if (mounted.current) setSq(d && d.square ? d.square : { configured: false });
			})
			// offline or unanswered: checkout stays closed, and now says so
			.catch(() => { if (mounted.current) setSq({ configured: false }); });
		return () => {
			mounted.current = false;
			redemptionRequest.current?.abort();
			paymentRequest.current?.abort();
			cancellationRequest.current?.abort();
			checkoutRecoveryRequest.current?.abort();
		};
	}, [loadCfg]);

	const flow = useMemo(() => computeFlow(s), [s.visit, s.priceCheck, s.who, s.subMode, s.service, cfg]);
	const busyRef = useRef(false);
	const navigationReady = useRef(false);
	useEffect(() => {
		if (new URLSearchParams(location.search).has("step")) return;
		try { saveBookingDraft(s, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
	}, [s]);
	useEffect(() => {
		const entry = { lalaluxe: true, step: s.step, trail: s.history, editReturn: s.editReturn || null, depth: 0 };
		if (!navigationReady.current) {
			window.history.replaceState(entry, "");
			navigationReady.current = true;
		} else if (window.history.state?.step !== s.step) {
			entry.depth = (window.history.state?.depth || 0) + 1;
			window.history.pushState(entry, "");
		}
		const wrap = document.querySelector(".screen-wrap");
		if (wrap) wrap.scrollTop = 0;
		const heading = wrap?.querySelector("h1, h2");
		if (heading) { heading.tabIndex = -1; heading.focus({ preventScroll: true }); }
	}, [s.step, cfg]);
	useEffect(() => {
		const pop = (event) => {
			const nav = event.state;
			if (!nav?.lalaluxe) return;
			setS((prev) => {
				if (busyRef.current || pendingRecovery(prev) || prev.step === "subdone" || prev.square?.checkoutUrl) {
					window.history.replaceState({ lalaluxe: true, step: prev.step, trail: prev.history, editReturn: prev.editReturn || null, depth: 0 }, "");
					return prev;
				}
				const nextPrev = nav.step === "plan" && prev.visit === "subscription" && prev.subMode === "existing"
					? { ...prev, subMode: "new" }
					: prev;
				const valid = ["intro", ...computeFlow(nextPrev)];
				const editReturn = nav.editReturn && valid.includes(nav.editReturn) && nav.step !== nav.editReturn ? nav.editReturn : null;
				const editableSteps = ["who", "base", "length", "design", "tbase"];
				if (!valid.includes(nav.step) && !(editReturn && editableSteps.includes(nav.step))) return prev;
				return {
					...nextPrev,
					step: nav.step,
					editReturn,
					history: (nav.trail || []).filter((step) => valid.includes(step) || (editReturn && editableSteps.includes(step))),
				};
			});
		};
		window.addEventListener("popstate", pop);
		return () => window.removeEventListener("popstate", pop);
	}, []);
	useEffect(() => {
		const resume = () => {
			if (redemptionRequest.current || checkoutRecoveryRequest.current || paymentRequest.current || cancellationRequest.current) return;
			busyRef.current = false;
			setPaying(false);
			setS((prev) => prev.square?.checkoutUrl ? { ...prev, step: "checkout" } : prev);
		};
		window.addEventListener("pageshow", resume);
		return () => window.removeEventListener("pageshow", resume);
	}, []);

	const go = useCallback((nextStep) => {
		if (busyRef.current) return;
		setS((prev) => {
			if (nextStep === prev.step || pendingRecovery(prev)) return prev;
			return { ...prev, step: nextStep, history: [...prev.history, nextStep] };
		});
	}, []);

	const back = useCallback(() => {
		if (busyRef.current || pendingRecovery(s)) return;
		if (window.history.state?.lalaluxe && window.history.state.depth > 0) {
			window.history.back();
			return;
		}
		setS((prev) => {
			const h = [...prev.history];
			if (h.length <= 1) return prev;
			h.pop();
			const prevStep = h[h.length - 1];
			return {
				...prev,
				...(prevStep === "plan" && prev.visit === "subscription" && prev.subMode === "existing" ? { subMode: "new" } : {}),
				...(prevStep === prev.editReturn ? { editReturn: null } : {}),
				step: prevStep,
				history: h,
			};
		});
	}, [s]);

	const set = useCallback(
		(patch) => setS((prev) => patchBooking(prev, patch)),
		[],
	);

	const toggleArr = useCallback((field, val) => {
		setS((prev) => {
			const arr = prev[field];
			const i = arr.indexOf(val);
			const next =
				i > -1 ? [...arr.slice(0, i), ...arr.slice(i + 1)] : [...arr, val];
			return patchBooking(prev, { [field]: next });
		});
	}, []);

	const recoverCheckout = useCallback(async () => {
		if (busyRef.current || !pendingCheckoutRecovery(s)) return;
		if (!validCustomerToken(s.customerToken)) { setPayError(PRIVATE_LINK_REQUIRED); return; }
		busyRef.current = true;
		setPaying(true); setPayError("");
		const controller = new AbortController();
		checkoutRecoveryRequest.current = controller;
		const timeout = setTimeout(() => controller.abort(), 20000);
		try {
			const response = await fetch(`/api/checkout/status?confirmation=${encodeURIComponent(s.confirmation)}`, { signal: controller.signal, headers: { Authorization: `Bearer ${s.customerToken}` } });
			const result = await response.json();
			if (!mounted.current) return;
			if (!response.ok || !result?.ok) throw new Error(result?.error || "Your booking couldn’t be checked. Try again.");
			if (result.bookingState === "rejected") {
				const path = computeFlow(s), index = path.indexOf("calendar");
				const rejected = { ...s, step: "calendar", history: ["intro", ...path.slice(0, index + 1)],
					confirmation: null, customerToken: null, square: null, time: null, availabilityReady: false, agreed: [], agreedAt: {},
					restoredNotice: "Your checkout closed. Choose an available time." };
				try { saveBookingDraft(rejected, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
				setS(rejected);
				return;
			}
			if (!["pending", "confirmed"].includes(result.bookingState) || typeof result.url !== "string" || !result.url)
				throw new Error("Your booking status is not available yet. Try again to check it.");
			const recovered = { ...s, step: "checkout", square: { ...result.square, checkoutUrl: result.url }, agreed: [], agreedAt: {}, restoredNotice: "Your checkout is restored." };
			try { saveBookingDraft(recovered, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
			setS(recovered);
			if (result.bookingState === "confirmed") window.location.assign(result.url);
		} catch (error) {
			if (mounted.current) setPayError(error.name === "AbortError"
				? "Your booking couldn’t be checked. Try again."
				: error.message || "Your booking couldn’t be checked. Try again.");
		} finally {
			clearTimeout(timeout);
			checkoutRecoveryRequest.current = null;
			busyRef.current = false;
			if (mounted.current) setPaying(false);
		}
	}, [s]);
	useEffect(() => {
		if (!restoreCheckout.current) return;
		restoreCheckout.current = false;
		recoverCheckout();
	}, [recoverCheckout]);

	// Every policy ticked -> create a Square-hosted payment link and leave card entry to Square.
	const completePayment = useCallback(async () => {
		if (busyRef.current) return;
		if (pendingCheckoutRecovery(s)) return recoverCheckout();
		if (s.square?.checkoutUrl) { window.location.assign(s.square.checkoutUrl); return; }
		if (!agreedToAll(s)) return;
		if (s.confirmation && !validCustomerToken(s.customerToken)) { setPayError(PRIVATE_LINK_REQUIRED); return; }
		const confirmation = s.confirmation || newConfirmation();
		const customerToken = s.customerToken || newCustomerToken();
		busyRef.current = true;
		const pending = { ...s, confirmation, customerToken };
		setS(pending);
		try { saveBookingDraft(pending, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
		// Only server-supplied error strings reach the customer; raw fetch/parse exceptions
		// ("Failed to fetch", SyntaxError) fall back to this customer-grade sentence.
		const genericMsg = "The payment page couldn’t be opened. Try again.";
		setPayError("");
		setPaying(true);
		const controller = new AbortController();
		paymentRequest.current = controller;
		const timeout = setTimeout(() => controller.abort(), 30000);
		try {
			if (controller.signal.aborted) throw new DOMException("Aborted", "AbortError");
			const booking = appointmentReportData(s);
			const form = new FormData();
			form.append("confirmation", confirmation);
			form.append("customerToken", customerToken);
			form.append("booking", JSON.stringify(booking));
			const policyTimes = {};
			if (typeof policyCards === "function" && s.agreedAt && typeof s.agreedAt === "object") {
				policyCards(s).forEach((card) => {
					if (s.agreedAt[card.key]) policyTimes[card.title || card.key] = s.agreedAt[card.key];
				});
			}
			form.append(
				"acknowledgement",
				JSON.stringify({
					text: acknowledgementText(s),
					version: ACK_VERSION,
					accepted: true,
					...(Object.keys(policyTimes).length ? { agreedAt: policyTimes } : {}),
				}),
			);
			try {
				const clientContext = {
					timezone: typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone || null : null,
					language: typeof navigator !== "undefined" ? navigator.language || null : null,
					screenW: typeof window !== "undefined" ? window.screen?.width || null : null,
					screenH: typeof window !== "undefined" ? window.screen?.height || null : null,
					viewportW: typeof window !== "undefined" ? window.innerWidth || null : null,
					viewportH: typeof window !== "undefined" ? window.innerHeight || null : null,
					touchPoints: typeof navigator !== "undefined" && typeof navigator.maxTouchPoints === "number" ? navigator.maxTouchPoints : null,
				};
				if (Object.values(clientContext).some((v) => v != null)) form.append("clientContext", JSON.stringify(clientContext));
			} catch (_) { /* Context is optional. */ }

			(s.shareImages || []).forEach((file) => {
				form.append("shareImages", file, file.name || "inspo-image.jpg");
			});
			const resp = await fetch("/api/checkout/payment-link", {
				method: "POST",
				signal: controller.signal,
				body: form,
			});
			const d = await resp.json();
			if (!mounted.current) return;
			if (!resp.ok || !d.ok) {
				// the code ended or ran out since it was entered: it comes off, and the booking stands
				if (d?.coupon === "invalid") {
					busyRef.current = false;
					setPaying(false);
					// nothing was reserved, so this attempt's keys are dropped with the code
					const cleared = { ...pending, coupon: null, confirmation: null, customerToken: null, square: null, agreed: [] };
					try { saveBookingDraft(cleared, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
					setS(cleared);
					setPayError(d.error + " The code was removed. Review your new total before continuing.");
					return;
				}
				// her time adds a fee it did not when she picked it (a squeeze-in by now), or no longer adds
				// one: the time stands with what it adds now, nothing was reserved, and she checks her total
				if (d?.timeFees && typeof d.timeFees === "object") {
					busyRef.current = false;
					setPaying(false);
					const cleared = { ...pending, squeezeIn: d.timeFees.squeezeIn === true, afterHours: d.timeFees.afterHours === true,
						holiday: d.timeFees.holiday === true, confirmation: null, customerToken: null, square: null, agreed: [] };
					try { saveBookingDraft(cleared, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
					setS(cleared);
					setPayError(d.error || genericMsg);
					return;
				}
				// the terms she read are not the ones the server sells this booking under: nothing was
				// reserved, so this attempt's keys are dropped, the studio's settings are read again,
				// and she stays on the policies to read them and tick each one again
				if (d?.policy === "changed") {
					busyRef.current = false;
					setPaying(false);
					const cleared = { ...pending, confirmation: null, customerToken: null, square: null, agreed: [] };
					try { saveBookingDraft(cleared, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
					setS(cleared);
					setPayError(d.error || genericMsg);
					loadCfg();
					return;
				}
				// refused before anything was claimed (a service not priced or timed yet, online booking
				// off): her time stands, this attempt's keys are dropped so the next try starts clean
				// rather than checking on this one, and checkout says why
				if (d?.attempt === "unused") {
					busyRef.current = false;
					setPaying(false);
					const cleared = { ...pending, confirmation: null, customerToken: null, square: null, agreed: [] };
					try { saveBookingDraft(cleared, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
					setS(cleared);
					setPayError(d.error || genericMsg);
					return;
				}
				// the attempt is spent and her time let go (most often because someone else just took
				// it): she picks another on the calendar, which says why, and checkout starts clean
				if (d?.bookingState === "rejected") {
					busyRef.current = false;
					setPaying(false);
					const flow = computeFlow(pending);
					const rejected = { ...pending, confirmation: null, customerToken: null, square: null, time: null, availabilityReady: false, agreed: [], agreedAt: {},
						timeNote: (d && d.error) || genericMsg, step: "calendar", history: ["intro", ...flow.slice(0, flow.indexOf("calendar") + 1)] };
					try { saveBookingDraft(rejected, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
					setS(rejected);
					return;
				}
				const err = new Error((d && d.error) || genericMsg);
				err.fromServer = true;
				throw err;
			}
			const ready = { ...pending, square: { ...d.square, checkoutUrl: d.url } };
			try { saveBookingDraft(ready, sessionStorage); } catch (_) { /* Payment can continue without storage. */ }
			setS(ready);
			window.location.assign(d.url);
		} catch (e) {
			busyRef.current = false;
			if (mounted.current) {
				setPaying(false);
				setPayError(e.fromServer ? e.message : genericMsg);
			}
		} finally {
			clearTimeout(timeout);
			paymentRequest.current = null;
		}
	}, [s, recoverCheckout, loadCfg]);

	// navigate forward from current step
	const next = useCallback(() => {
		const cur = s.step;
		if (s.editReturn && ["who", "base", "length", "design", "tbase"].includes(cur)) {
			const dest = nextReturnEditStep(s);
			if (dest === s.editReturn) {
				setS((prev) => {
					const backTo = prev.editReturn;
					const nextState = { ...prev, editReturn: null };
					const path = computeFlow(nextState), index = path.indexOf(backTo);
					return {
						...nextState,
						step: backTo,
						history: index >= 0 ? ["intro", ...path.slice(0, index + 1)] : [...prev.history, backTo],
					};
				});
				return;
			}
			if (dest) return go(dest);
		}
		if (cur === "intro") return go("visit");
		if (cur === "visit") {
			if (s.visit === "subscription")
				return go(s.subMode === "existing" ? "subcode" : "plan");
			if (s.priceCheck) return go("pricecheck");
			return go("who");
		}
		if (cur === "pricecheck") return go("calendar");
		if (cur === "subcode") return go("calendar");
		if (cur === "plan") return go("subaddons");
		if (cur === "subaddons") return go("summary");
		if (cur === "who") {
			if (s.who === "toes") return go("tbase");
			return go("base");
		}
		if (cur === "base") {
			// repair is nail health, not a look — it skips length AND the look screen (a category of its
			// own since 2026-06-10)
			if (s.service === "repair") return go(s.who === "both" ? "tbase" : "summary");
			const tiers = CFG.base[s.service];
			if (tiers && tiers.flat == null) return go("length"); // tiered base pricing → pick a length
			return go("design");
		}
		if (cur === "length") return go("design");
		if (cur === "design") {
			if (s.who === "both") return go("tbase");
			return go("summary");
		}
		if (cur === "tbase") return go("summary");
		if (cur === "summary") return go("calendar");
		if (cur === "calendar") {
			// Existing-subscription redemption is prepaid: skip checkout/consent and book the
			// visit directly against the code (handled in App via redeemVisit).
			if (s.visit === "subscription" && s.subMode === "existing") return;
			return go("checkout");
		}
		if (cur === "checkout") {
			if (pendingCheckoutRecovery(s)) return recoverCheckout();
			if (s.square?.checkoutUrl) return window.location.assign(s.square.checkoutUrl);
			// the policies come next; the redirect to payment starts once she has ticked every one
			return go("policies");
		}
		if (cur === "policies") return completePayment();
	}, [s, go, set, recoverCheckout, completePayment]);

	// Existing-subscription prepaid visit: book directly against the code. No charge,
	// no policies to tick (the plan was paid in full at purchase). Reuses paying/payError UI.
	const redeemVisit = useCallback(async () => {
		if (busyRef.current || (!pendingRedemption(s) && !s.availabilityReady) || !s.subCode || !s.date || !s.time) return;
		if (s.confirmation && !validCustomerToken(s.customerToken)) { setPayError(PRIVATE_LINK_REQUIRED); return; }
		const confirmation = s.confirmation || newConfirmation();
		const customerToken = s.customerToken || newCustomerToken();
		busyRef.current = true;
		const pending = { ...s, confirmation, customerToken, availabilityReady: false };
		setS(pending);
		try { saveBookingDraft(pending, sessionStorage); } catch (_) { /* Recovery is optional when storage is blocked. */ }
		setPayError("");
		setPaying(true);
		const controller = new AbortController();
		redemptionRequest.current = controller;
		const timeout = setTimeout(() => controller.abort(), 20000);
		try {
			const resp = await fetch("/api/subscriptions/redeem", {
				method: "POST",
				signal: controller.signal,
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({ code: s.subCode, date: s.date, time: s.time, confirmation, customerToken }),
			});
			const d = await resp.json();
			if (!mounted.current) return;
			if (!resp.ok || !d?.ok) {
				// her time was let go: the calendar says why until she picks another
				if (d?.bookingState === "rejected") {
					const rejected = { ...pending, confirmation: null, customerToken: null, time: null, availabilityReady: false,
						timeNote: d.error || "That time is no longer available. Choose another time." };
					setS(rejected);
					try { saveBookingDraft(rejected, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
					return;
				}
				throw new Error(d?.error || "Your booking status couldn’t be confirmed. Try again to check it.");
			}
			if (d.confirmation !== confirmation || !Number.isFinite(d.remaining))
				throw new Error("Your booking status couldn’t be confirmed. Try again to check it.");
			const complete = {
				...pending,
				confirmation: d.confirmation,
				subResult: { confirmation: d.confirmation, remaining: d.remaining },
				step: "subdone",
				history: ["intro", ...SUB_REDEEM_STEPS],
			};
			try { saveBookingDraft(complete, sessionStorage); } catch (_) { /* Storage may be blocked. */ }
			setS(complete);
		} catch (e) {
			if (mounted.current) setPayError(e.name === "AbortError"
				? "Your booking couldn’t be checked. Try again to check its status."
				: e.message || "Your booking status couldn’t be confirmed. Try again to check it.");
		} finally {
			clearTimeout(timeout);
			redemptionRequest.current = null;
			busyRef.current = false;
			if (mounted.current) setPaying(false);
		}
	}, [s]);
	useEffect(() => {
		if (!restoreRedemption.current) return;
		restoreRedemption.current = false;
		redeemVisit();
	}, [redeemVisit]);

	const reset = useCallback(() => {
		if (!busyRef.current) setS((prev) => pendingRecovery(prev) ? prev : freshState());
	}, []);
	const edit = useCallback(async (step) => {
		if (busyRef.current || pendingRedemption(s)) return;
		let canceled = false;
		if (s.square?.checkoutUrl || pendingCheckoutRecovery(s)) {
			if (!validCustomerToken(s.customerToken)) { setPayError(PRIVATE_LINK_REQUIRED); return; }
			const controller = new AbortController();
			cancellationRequest.current = controller;
			const timeout = setTimeout(() => controller.abort(), 15000);
			busyRef.current = true;
			setPaying(true); setPayError("");
			try {
				const response = await fetch("/api/checkout/cancel", {
					signal: controller.signal,
					method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${s.customerToken}` },
					body: JSON.stringify({ confirmation: s.confirmation }),
				});
				const result = await response.json();
				if (!mounted.current) return;
				if (!response.ok || !result.ok) throw new Error(result.error || "Checkout couldn’t be canceled. Try again.");
				if (result.url && !result.canceled) { window.location.assign(result.url); return; }
				if (!result.canceled) throw new Error("Checkout is still open. Try again.");
				canceled = true;
			} catch (error) {
				if (mounted.current) setPayError(controller.signal.aborted
					? "Checkout cancellation couldn’t be confirmed. Your checkout details are kept. Try again to check before editing."
					: error.message || "Checkout couldn’t be canceled. Try again.");
				return;
			} finally {
				clearTimeout(timeout);
				cancellationRequest.current = null;
				busyRef.current = false;
				if (mounted.current) setPaying(false);
			}
		}
		setS((prev) => {
			const returning =
				(prev.step === "pricecheck" || prev.step === "summary") &&
				["who", "base", "length", "design", "tbase"].includes(step);
			if (returning) {
				return {
					...prev,
					step,
					editReturn: prev.step,
					history: [...prev.history, step],
					...(canceled ? { square: null, confirmation: null, customerToken: null, time: null, availabilityReady: false, agreed: [] } : {}),
				};
			}
			const keepPriceCheck = prev.priceCheck === true && ["pricecheck", "calendar", "checkout", "policies"].includes(step);
			const nextState = { ...prev, priceCheck: keepPriceCheck, editReturn: null };
			const path = computeFlow(nextState), index = path.indexOf(step);
			return { ...nextState, step, history: ["intro", ...path.slice(0, index + 1)],
				...(canceled ? { square: null, confirmation: null, customerToken: null, time: null, availabilityReady: false, agreed: [] } : {}),
			};
		});
	}, [s]);

	// step indicator dots — one segment per screen of the active flow
	const rawStepIndex = flow.indexOf(s.step);
	const stepIndex = rawStepIndex >= 0 ? rawStepIndex : s.editReturn ? flow.indexOf(s.editReturn) : -1;
	// Which way the customer is travelling, so screens arrive from that side. Held in a ref
	// keyed to the step: re-renders within a screen must not flip a running animation.
	const travel = useRef({ step: s.step, index: stepIndex, dir: "forward" });
	if (travel.current.step !== s.step)
		travel.current = { step: s.step, index: stepIndex, dir: stepIndex < travel.current.index ? "back" : "forward" };

	// masthead label for each screen
	const STEP_NAMES = {
		visit: "Your Visit", pricecheck: "Price Check", who: "Your Set", base: "Your Base", length: "Your Length", design: "Your Look",
		tbase: "Your Toes", plan: "Your Plan", subaddons: "Plan Nail Art",
		summary: "Review", calendar: "Date & Time", checkout: "Your Details", policies: "Policies", subcode: "Your Plan", subdone: "Booked",
	};
	const stepNo = String(Math.max(0, stepIndex) + 1).padStart(2, "0");
	useEffect(() => {
		document.title = STEP_NAMES[s.step] ? `${STEP_NAMES[s.step]} · ${STORE.name}` : `${STORE.name} | Custom Luxe Nail Sets`;
	}, [s.step]);

	const onHome = s.step === "intro";
	// home is the night room in both themes: on a phone the browser's bars and the page behind it go dark with it
	useEffect(() => {
		if (window.__setRoom) window.__setRoom(onHome && window.matchMedia("(max-width: 600px)").matches);
	}, [onHome]);
	// subcode renders its own action (lookup gates advancing); subdone is a terminal success.
	// The visit tiles advance on their own, so that screen has no action until one is chosen.
	const showBotBar = s.step !== "subcode" && s.step !== "subdone" && !(s.step === "visit" && !s.visit);
	const backLocked = paying || s.uploadBusy || !!s.square?.checkoutUrl || pendingRecovery(s);
	const showTray = !onHome && !TAIL.includes(s.step) && s.step !== "pricecheck" && s.subMode !== "existing";

	if (!cfg) {
		return (
			<div className="boot">
				<Logo />
				{cfgError ? (
					<p role="alert">
						<button onClick={() => loadCfg()}>{cfgError}</button>
					</p>
				) : (
					<>
						<span className="boot-bar" aria-hidden="true" />
						<p role="status">Loading the studio…</p>
					</>
				)}
			</div>
		);
	}

	return (
		<>
			<PaintDefs />
			<WallArt />
			<header className="topbar">
				{s.history.length > 1 && s.step !== "subdone" ? (
					<button className="icon-btn nav-back" onClick={back} disabled={backLocked} aria-label="Back">
						<Ico name="back" />
					</button>
				) : (
					<span />
				)}
				<Logo />
				<span className="topbar-right">
					<ThemeToggle />
				</span>
				{!onHome && (
					<span
						className="steps"
						role="img"
						aria-label={stepIndex < 0 ? "Booking progress" : `Step ${stepIndex + 1} of ${flow.length}`}
					>
						{flow.map((name, i) => (
							<i key={name} className={"pip" + (i < stepIndex ? " done" : i === stepIndex ? " cur" : "")} />
						))}
					</span>
				)}
				{!onHome && (
					<StartOver
						label={<><b>{stepNo}</b>{STEP_NAMES[s.step]}</>}
						count={`${stepNo} / ${String(flow.length).padStart(2, "0")}`}
						locked={backLocked || s.step === "subdone"}
						onReset={reset}
					/>
				)}
			</header>

			<main className="screen-wrap" id="booking-main" data-dir={travel.current.dir}>
				{s.restoredNotice && (
					<div className="booking-notice" role="status">
						<p>{s.restoredNotice}</p>
						<button className="cal-retry" onClick={() => set({ restoredNotice: "" })}>Dismiss</button>
					</div>
				)}
				{renderScreen(s, cfg, set, toggleArr, go, reset, payMode(s, sq), edit, paying, payError, policyNudge)}
			</main>

			{showBotBar && (
				<div className="botbar">
					{showTray && <PicksTray s={s} cfg={cfg} />}
					{s.step === "calendar" && s.subMode === "existing" && payError && (
						<div className="sub-error" role="alert">{payError}</div>
					)}
					{onHome ? (
						<button className="cta startBtn" onClick={next}>
							Book Your Set
							<Ico name="arrow" />
						</button>
					) : s.step === "calendar" &&
					s.visit === "subscription" &&
					s.subMode === "existing" ? (
						<button
							className="cta"
							disabled={paying || (!pendingRedemption(s) && !(s.date && s.time && s.availabilityReady))}
							onClick={redeemVisit}
						>
							{paying
								? "Checking Booking…"
								: pendingRedemption(s)
									? "Retry Confirmation"
									: s.date && s.time
										? "Confirm Visit"
										: !s.date
											? "Pick a Day"
											: "Pick a Time"}
						</button>
					) : (
						<ContinueButton s={s} sq={payMode(s, sq)} onNext={next} onBlocked={s.step === "policies" ? () => setPolicyNudge((n) => n + 1) : undefined} busy={paying} recovering={pendingCheckoutRecovery(s)} />
					)}
				</div>
			)}

		</>
	);
}

function renderScreen(s, cfg, set, toggleArr, go, reset, sq, edit, paying, payError, policyNudge) {
	switch (s.step) {
		case "intro":
			return <Intro cfg={cfg} />;
		case "visit":
			return (
				<VisitStep
					cfg={cfg}
					s={s}
					sq={sq}
					onPick={(v) => {
						// Appointment auto-advances. Subscription stays on this screen to choose
						// NEW vs. existing (a prepaid plan already in hand) before advancing.
						if (v === "subscription") {
							set({ visit: v, subMode: null, priceCheck: false, editReturn: null });
							return;
						}
						set({ visit: v, subMode: null, priceCheck: false, editReturn: null });
						go("who");
					}}
					onSubMode={(mode) => {
						set({ visit: "subscription", subMode: mode, priceCheck: false, editReturn: null });
						go(mode === "existing" ? "subcode" : "plan");
					}}
					onPriceCheck={() => {
						set({ visit: "appointment", subMode: null, priceCheck: true, editReturn: null });
						go("pricecheck");
					}}
				/>
			);
		case "pricecheck":
			return <PriceCheckStep cfg={cfg} s={s} set={set} sq={sq} edit={edit} />;
		case "who":
			return <WhoStep cfg={cfg} s={s} set={set} />;
		case "base":
			return <BaseStep cfg={cfg} s={s} set={set} toggleArr={toggleArr} />;
		case "length":
			return <LengthStep cfg={cfg} s={s} set={set} />;
		case "design":
			return <DesignStep cfg={cfg} s={s} set={set} />;
		case "tbase":
			return <TBaseStep cfg={cfg} s={s} set={set} />;
		case "plan":
			return (
				<PlanStep
					cfg={cfg}
					s={s}
					set={set}
					sq={sq}
					onExisting={() => {
						set({ visit: "subscription", subMode: "existing", priceCheck: false });
						go("subcode");
					}}
				/>
			);
		case "subaddons":
			return <SubAddonsStep cfg={cfg} s={s} set={set} toggleArr={toggleArr} />;
		case "summary":
			return <SummaryStep cfg={cfg} s={s} set={set} sq={sq} edit={edit} />;
		case "calendar":
			return <CalendarStep cfg={cfg} s={s} set={set} recovering={pendingRedemption(s)} dur={s.subMode === "existing" ? s.subLookup?.duration || totalDuration(s) : totalDuration(s)} />;
		case "checkout":
			return <CheckoutStep cfg={cfg} s={s} set={set} sq={sq} edit={edit} busy={paying} error={payError} recovering={pendingCheckoutRecovery(s)} />;
		case "policies":
			return <PoliciesStep cfg={cfg} s={s} set={set} busy={paying} error={payError} nudge={policyNudge} />;
		case "subcode":
			return <SubCodeStep cfg={cfg} s={s} set={set} go={go} />;
		case "subdone":
			return <SubDoneStep cfg={cfg} s={s} reset={reset} />;
		default:
			return null;
	}
}

const manageConfirmation = new URLSearchParams(location.search).get("manage");
ReactDOM.createRoot(document.getElementById("app")).render(manageConfirmation !== null
	? <CustomerBooking confirmation={manageConfirmation} token={new URLSearchParams(location.hash.slice(1)).get("token") || ""} />
	: <App />);
