// Lalaluxe booking — booking/screens/policies.jsx
// Page: "policies" — the last screen before payment. Each policy is a card she ticks: the app's
// Payment card (how the charge shows on her statement), then the studio's own, in the studio's order
// (content.policies, Booking → Policies). The dock's button books and pays only once every card is
// ticked (ContinueButton, agreedToAll); what is sent is the cards' words (acknowledgementText), which
// the server builds again and checks. A tap on the blocked button (nudge, counted in app.jsx) turns
// each unticked box red, shakes its card, and scrolls to the first and focuses its box, however far
// down the list it is.
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
function PoliciesStep({ cfg, s, set, busy, error, nudge = 0 }) {
	const cards = policyCards(s);
	const agreed = Array.isArray(s.agreed) ? s.agreed : [];
	const agreedAt = s.agreedAt && typeof s.agreedAt === "object" ? s.agreedAt : {};
	const changeBy = changeCutoffLabel(s.date, s.time, cfg.schedule?.timeZone);
	const tick = (key) => {
		const on = agreed.includes(key);
		const nextTimes = { ...agreedAt };
		if (on) delete nextTimes[key];
		else nextTimes[key] = new Date().toISOString();
		set({ agreed: on ? agreed.filter((k) => k !== key) : [...agreed, key], agreedAt: nextTimes });
	};
	const list = useRef(null);
	const left = cards.filter((card) => !agreed.includes(card.key)).length;
	// a tap on the blocked button: shake every unticked card, then bring the first into view and focus its box
	useEffect(() => {
		if (!nudge || !list.current) return;
		const open = [...list.current.querySelectorAll(".pol-card:not(.on)")];
		// the shake is an attribute React does not own, so it restarts on every tap without a re-render
		open.forEach((card) => { card.removeAttribute("data-nudge"); void card.offsetWidth; card.setAttribute("data-nudge", ""); });
		if (!open.length) return;
		const still = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
		open[0].scrollIntoView({ block: "center", behavior: still ? "auto" : "smooth" });
		open[0].querySelector("input")?.focus({ preventScroll: true });
	}, [nudge]);

	return (
		<div className="screen">
			<ScreenHead cfg={cfg} screen="policies">
				Before You <em>Pay.</em>
			</ScreenHead>

			<div className="body">
				<ul className="pol-list" ref={list}>
					{cards.map((card) => {
						const on = agreed.includes(card.key);
						return (
							<li key={card.key}>
								<label className={"pol-card" + (on ? " on" : nudge ? " warn" : "")} onAnimationEnd={(e) => e.currentTarget.removeAttribute("data-nudge")}>
									<input type="checkbox" checked={on} onChange={() => tick(card.key)} disabled={busy} aria-invalid={!on && nudge ? true : undefined} />
									<span className="cbox" aria-hidden="true"><Ico name="check" /></span>
									<span className="pol-copy">
										{card.title && <span className="pol-title">{card.title}</span>}
										{/* the words she agrees to, exactly as they are sent; the statement name never breaks across lines */}
										{card.body && <span className="pol-body">{card.body.replace(STORE.statement, STORE.statement.replace(/ /g, " "))}</span>}
									</span>
								</label>
							</li>
						);
					})}
				</ul>
				{/* said again on every blocked tap */}
				{nudge > 0 && left > 0 && <p key={nudge} className="sr-only" role="alert">Agree to each policy to continue.</p>}
				{error && <Alert>{error}</Alert>}
				{changeBy && (
					<ul className="assure">
						<li>
							<Ico name="calendar" />
							<span>Online changes close {changeBy}.</span>
						</li>
					</ul>
				)}
			</div>
		</div>
	);
}
