// Lalaluxe booking — booking/screens/checkout.jsx
// Page: "checkout" — contact details, and how much to pay today, before the redirect to Square. (Look description + inspo
// upload moved to the look screen; this page is contact-only now.)
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
function CheckoutStep({ cfg, s, set, sq, edit, busy, error, recovering = false }) {
	const t = total(s);
	const dur = totalDuration(s);
	const off = priceItems(s).find((it) => it.coupon);
	// what the time adds (a squeeze-in, after hours, a holiday), each on a line of its own
	const timeFees = priceItems(s).filter((it) => it.fee);
	const upd = (field, key, val) =>
		set({ [field]: { ...s[field], [key]: val } });
	const c = s.contact;
	const squareOn = !!(sq && sq.configured);
	const afterpay = cfg.afterpay !== false && sq?.afterpay === true;
	const pendingCheckout = !!s.square?.checkoutUrl;
	// An appointment can be held with the deposit or paid in full, where the pay-later options
	// are. There is nothing to choose under pay at visit, on a plan (always in full), or when the
	// deposit already covers the total.
	const deposit = Math.min(cfg.deposit, t);
	const canChoose = !!sq && !sq.bypass && s.visit !== "subscription" && t > deposit;
	const changeBy = changeCutoffLabel(s.date, s.time, cfg.schedule?.timeZone);
	const hasLook = computeFlow(s).includes("design");
	const reviewStep = s.priceCheck ? "pricecheck" : "summary";
	// Per-field validation hints appear only after a field is touched (blurred), using the
	// SAME predicates that gate "Review & continue" (contactChecks — engine/checks.js).
	const [touched, setTouched] = useState({});
	const ck = contactChecks(c);
	const touch = (k) => setTouched((p) => ({ ...p, [k]: true }));
	const err = (k, msg) =>
		touched[k] && !ck[k] ? (
			<span className="field-err" id={"co-" + k + "-err"}>
				{msg}
			</span>
		) : null;
	const errProps = (k) =>
		touched[k] && !ck[k]
			? { "aria-invalid": true, "aria-describedby": "co-" + k + "-err" }
			: {};

	return (
		<div className="screen">
			<ScreenHead
				cfg={cfg} screen="checkout"
				sub={
					/* a code that covers the whole visit leaves nothing to pay, today or later, and the copy says so */
					sq && sq.bypass
						? s.visit === "subscription"
							? "Your code covers the plan. Add your details to confirm your booking."
							: "Add your details to confirm your booking."
						: s.visit === "subscription"
							? `Pay ${money(t)} today for all ${PLAN_VISITS} visits.`
							: "Add your details to continue."
				}
			>
				Lock It <em>In.</em>
			</ScreenHead>

			<div className="body co-scroll">
				<div className="co-summary">
					<div className="l">
						<div className="when-line">
							{[s.date && prettyDateShort(s.date), s.time && fmtTime(s.time)].filter(Boolean).join(" · ") || "No Time Picked Yet"}
						</div>
						<div className="when-sub">
							{bookingTitle(s)}{Number.isFinite(dur) && dur > 0 && <> · about {humanDuration(dur)}</>}
						</div>
					</div>
					{/* the client's code, so what she saves is on the screen where she pays */}
					{off && (
						<div className="co-code">
							<span>Code {s.coupon.code} · {s.coupon.kind === "percent" ? s.coupon.value + "%" : money(s.coupon.value)} off</span>
							<span>{money(off.amt)}</span>
						</div>
					)}
					{timeFees.map((fee) => (
						<div className="co-code co-fee" key={fee.label}>
							<span>{fee.label}</span>
							<span>+{money(fee.amt)}</span>
						</div>
					))}
					<div className="r">
						<span className="total-lbl">
							{s.visit === "subscription" ? "Plan Total" : "Total"}{" "}
							{money(t)}
						</span>
						<span className="co-due">
							{/* a code that covers the whole visit: nothing is due, now or at the visit */}
							{sq && sq.bypass ? (
								<span className="due-lbl">Nothing to Pay</span>
							) : (
								<>
									<span className="due-lbl">Due Now</span>
									<span className="due-amt">{money(dueNow(s))}</span>
								</>
							)}
						</span>
					</div>
				</div>

				{canChoose && (
					<div className="block">
						<h3 className="co-section">Pay Today</h3>
						<div className="finish-grid" role="group" aria-label="Pay today">
							<button type="button" className={"fin " + (!s.payFull ? "sel" : "")} aria-pressed={!s.payFull} disabled={pendingCheckout || recovering || busy} onClick={() => set({ payFull: false })}>
								<span className="fname">Deposit</span>
								<span className="fprice">{money(deposit)} now · {money(t - deposit)} at your visit</span>
							</button>
							<button type="button" className={"fin " + (s.payFull ? "sel" : "")} aria-pressed={!!s.payFull} disabled={pendingCheckout || recovering || busy} onClick={() => set({ payFull: true })}>
								<span className="fname">Pay in Full</span>
								<span className="fprice">{money(t)} now · nothing at your visit</span>
							</button>
						</div>
						{(s.payFull || afterpay) && <p className="custom-hint">
							{s.payFull
								? afterpay
									? "Pay by card or, when available, in 4 payments with Afterpay at Square checkout."
									: "Pay by card at Square checkout."
								: "Pay-later options may be available when you choose Pay in Full."}
						</p>}
					</div>
				)}
				{recovering ? <div className="booking-notice">
					<p>Your booking details are saved. Check the booking status below before trying again.</p>
					<button className="cal-retry" onClick={() => edit(reviewStep)} disabled={busy}>{busy ? "Checking Booking…" : "Cancel Request & Edit"}</button>
				</div> : pendingCheckout ? <div className="booking-notice">
					<p>Resume checkout below, or cancel it to edit your booking.</p>
					<button className="cal-retry" onClick={() => edit(reviewStep)} disabled={busy}>{busy ? "Checking Checkout…" : "Cancel Checkout & Edit"}</button>
				</div> : <nav className="review-actions" aria-label="Review appointment">
					<button className="cal-retry" onClick={() => edit("calendar")}>Change Time</button>
					<button className="cal-retry" onClick={() => edit(reviewStep)}>{s.priceCheck ? "Review Quote" : "Review Set"}</button>
				</nav>}
				{error && <Alert>{error}</Alert>}
				<fieldset className="checkout-fields" disabled={pendingCheckout || recovering || busy}>
				<h3 className="co-section">Your Info</h3>
				<div className="field">
					<label className="lab" htmlFor="co-name">
						Name
					</label>
					<input
						id="co-name"
						type="text"
						placeholder="Your full name"
						autoComplete="name"
						aria-required={true}
						value={c.name}
						onChange={(e) => upd("contact", "name", e.target.value)}
						onBlur={() => touch("name")}
						{...errProps("name")}
					/>
					{err("name", "Enter your name")}
				</div>
				<div className="field-row">
					<div className="field">
						<label className="lab" htmlFor="co-email">
							Email
						</label>
						<input
							id="co-email"
							type="email"
							placeholder="you@email.com"
							autoComplete="email"
							autoCapitalize="none"
							spellCheck={false}
							aria-required={true}
							value={c.email}
							onChange={(e) => upd("contact", "email", e.target.value)}
							onBlur={() => touch("email")}
							{...errProps("email")}
						/>
						{err("email", "Enter a valid email address")}
					</div>
					<div className="field">
						<label className="lab" htmlFor="co-phone">
							Phone
						</label>
						<input
							id="co-phone"
							type="tel"
							inputMode="tel"
							placeholder="(901) 555-0123"
							autoComplete="tel-national"
							aria-required={true}
							value={c.phone}
							onChange={(e) =>
								upd("contact", "phone", formatPhone(e.target.value))
							}
							onBlur={() => touch("phone")}
							{...errProps("phone")}
						/>
						{err("phone", "Enter a 10-digit phone number")}
					</div>
				</div>

				{hasLook ? (
					/* the look was described on its own screen — show it, don't ask twice */
					<div className="block">
						<h3 className="co-section">Your Look</h3>
						<p className="look-recap">{c.notes || "No description yet."}</p>
						<p className="custom-hint">
							{s.shareImages.length > 0
								? `${s.shareImages.length} inspo ${s.shareImages.length === 1 ? "photo" : "photos"} attached. `
								: "No inspo photos yet. "}
							<button type="button" className="inline-link" onClick={() => edit("design")}>Edit Your Look</button>
						</p>
					</div>
				) : (
					<>
						<h3 className="co-section">Anything Else? <small>Optional</small></h3>
						<div className="field">
							<label className="lab" htmlFor="co-notes">Appointment Notes</label>
							<textarea id="co-notes" className="look-note" rows="3" value={c.notes} onChange={(e) => upd("contact", "notes", e.target.value)} placeholder="Special requests, or anything else for your visit" />
						</div>
						<InspoUpload s={s} set={set} />
					</>
				)}
				</fieldset>
				{!squareOn && !sq?.loading && <div className="sub-error" role="alert">Online booking is unavailable right now. Your details are saved in this tab.</div>}
				<ul className="assure">
					<li>
						<Ico name="lock" />
						<span>
							{sq && sq.bypass
								? "Your code covers the " + (s.visit === "subscription" ? "plan" : "appointment") + ". Nothing will be charged."
								: !squareOn && !sq?.loading
									? "Online payments are unavailable. Try again later."
									: "Payment opens on Square’s payment page. Card details are not collected by this booking form."}
						</span>
					</li>
					<li>
						<Ico name="pin" />
						<span>The studio address is on your private confirmation.</span>
					</li>
					{changeBy && (
						<li>
							<Ico name="calendar" />
							<span>Online changes and cancellations close {changeBy}, 24 hours before your visit.</span>
						</li>
					)}
				</ul>
			</div>
		</div>
	);
}
