// Lalaluxe booking — booking/ui/chrome.jsx (load before app.jsx — see docs/architecture.md, "The no-build multi-file Babel contract")
// The chrome more than one screen wears: the screen header, the dock's one action, alerts, Start over and
// the theme toggle in the masthead, and the spring that eases drawn values.
// Its neighbours in ui/: icons.jsx (Ico, tile art), choices.jsx (the tray and the pickers), inspo-upload.jsx,
// and paint-ten.js (Build your own, plain JS); the contact and change-cutoff checks are engine/checks.js.

/* ---------- Motion: a critically damped spring for values React draws (nail length, totals) —
   it eases to rest and never overshoots ---------- */
function useSpringValue(target, stiffness = 190, damping = 28) {
	const [value, setValue] = useState(target);
	const sim = useRef({ x: target, v: 0, raf: 0 });
	useEffect(() => {
		const s = sim.current;
		const still =
			typeof window.matchMedia === "function" &&
			window.matchMedia("(prefers-reduced-motion: reduce)").matches;
		if (still) {
			s.x = target;
			s.v = 0;
			setValue(target);
			return;
		}
		let last = performance.now();
		const tick = (now) => {
			const dt = Math.min(0.034, (now - last) / 1000);
			last = now;
			s.v += (-stiffness * (s.x - target) - damping * s.v) * dt;
			s.x += s.v * dt;
			if (Math.abs(s.v) < 0.05 && Math.abs(s.x - target) < 0.05) {
				s.x = target;
				s.v = 0;
				setValue(target);
				return;
			}
			setValue(s.x);
			s.raf = requestAnimationFrame(tick);
		};
		s.raf = requestAnimationFrame(tick);
		return () => cancelAnimationFrame(s.raf);
	}, [target]);
	return value;
}

// What this booking is, in the customer's words — titles the review and details screens.
function bookingTitle(s) {
	if (s.visit === "subscription") return "3-Visit Plan";
	if (s.who === "toes") return "Toes";
	// the child price exists for gel polish only, so that is the only booking labelled for kids
	const nails = (s.isKid && s.service === "gel" ? "Kids " : "") + (CFG.labels.service[s.service] || "Custom Set");
	return s.who === "both" ? nails + " + Toes" : nails;
}

// An error the customer must not miss: announced, and brought into view when it appears.
function Alert({ children }) {
	const ref = useRef(null);
	useEffect(() => {
		if (ref.current) ref.current.scrollIntoView({ block: "center", behavior: "smooth" });
	}, [children]);
	return <div className="sub-error" role="alert" ref={ref}>{children}</div>;
}

/* ---------- Screen header ---------- */
// A screen's title is the studio's (Look → Titles, content.titles[screen]): plain words, then the
// italic words over the brush, then the line under it. `sub` is passed only where that line is worked
// out from the booking (a price, a date); `after` rides at the end of the title.
function ScreenHead({ cfg, screen, children, sub, after }) {
	const t = screen ? cfg?.content?.titles?.[screen] : null;
	const title = t ? <>{t.lead}{t.lead && t.accent ? " " : ""}{t.accent && <em>{t.accent}</em>}</> : children;
	const line = sub !== undefined ? sub : t ? t.sub : undefined;
	return (
		<header className="screen-head">
			<h1 className="h-question">{title}{after}</h1>
			{line && <p className="h-sub">{line}</p>}
		</header>
	);
}

/* ---------- Dock: running tray + the one primary action ---------- */
function ContinueButton({ s, sq, onNext, onBlocked, busy, recovering = false }) {
	// figure out if continue is enabled; `need` says what is missing when it is not
	let ok = true;
	let label = "Continue";
	let need = "";
	// Subscription forks into new-vs-existing on this same screen; Continue must wait for that
	// pick or it routes (via next()) to the NEW-plan flow, silently sending an existing
	// subscriber past their "enter your code" redemption path.
	if (s.step === "visit" && (!s.visit || (s.visit === "subscription" && !s.subMode))) {
		ok = false;
		need = "Choose How to Book";
	}
	if (s.step === "pricecheck") {
		const pc = s.priceCheckResult;
		const hasQuote = Boolean((pc && pc.matched) || (!pc && s.priceCheckMatched));
		const ready = Boolean(hasQuote && (s.who === "toes" ? s.tbase : s.service));
		label = "Pick a Time";
		if (!hasQuote) {
			ok = false;
			need = pc && !pc.matched ? "Try Another Photo" : "Upload an Inspo Photo";
		} else if (!ready || unpricedVisit(s)) {
			ok = false;
			need = unpricedVisit(s) ? "Not Bookable Online Yet" : "Check Your Selections";
		}
	}
	if (s.step === "who" && !s.who) {
		ok = false;
		need = "Choose What You’re Booking";
	}
	// a service the studio has since taken off the menu is no choice at all
	if (s.step === "base" && (!s.service || !serviceOffered(s.service, s.service === "gel" && s.isKid === true))) {
		ok = false;
		need = "Choose a Service";
	}
	if (s.step === "length" && !s.length) {
		ok = false;
		need = "Choose a Length";
	}
	// every set is in a tier, so the look screen needs one piece of nail art — a solid color counts
	if (s.step === "design" && !s.art.length) {
		ok = false;
		need = "Choose Your Nail Art";
	}
	// built nail by nail, every nail wears something — a solid color counts
	const bare = s.step === "design" && Array.isArray(s.perNail) ? s.perNail.filter((a) => !a).length : 0;
	if (bare && s.art.length) {
		ok = false;
		need = bare === 1 ? "Choose Art for 1 More Nail" : `Choose Art for ${bare} More Nails`;
	}
	if (s.step === "tbase" && !Array.isArray(s.perToe) && (!s.tbase || !s.tart.length)) {
		ok = false;
		need = !s.tbase ? "Choose a Toe Service" : "Choose Your Toe Art";
	}
	// built toe by toe, every toe has a base, its own or the set's, and wears something
	if (s.step === "tbase" && Array.isArray(s.perToe)) {
		const unbased = s.perToe.filter((_, i) => !((s.perToeBase || [])[i] || s.tbase)).length;
		const bareToes = s.perToe.filter((a) => !a).length;
		const toes = (n) => (n === 1 ? "1 More Toe" : `${n} More Toes`);
		if (unbased || bareToes) {
			ok = false;
			need = unbased ? `Choose Acrylic or Gel for ${toes(unbased)}` : `Choose Art for ${toes(bareToes)}`;
		}
	}
	if (s.step === "plan" && !s.plan) {
		ok = false;
		need = "Choose a Plan";
	}
	// When editing one choice from the quote or review screen, say exactly where the tap goes next.
	if (ok && s.editReturn && ["who", "base", "length", "design", "tbase"].includes(s.step)) {
		const dest = nextReturnEditStep(s);
		if (dest === "pricecheck") label = "Update Quote";
		else if (dest === "summary") label = "Update Set";
		else if (dest === "base") label = "Choose Service";
		else if (dest === "length") label = "Choose Length";
		else if (dest === "design") label = "Choose Look";
		else if (dest === "tbase") label = "Choose Toes";
	}
	if (s.step === "summary") {
		label = "Pick a Time";
		// nothing to pay and no code that covers it: the studio has not priced this visit yet
		if (unpricedVisit(s)) {
			ok = false;
			need = "Not Bookable Online Yet";
		}
	}
	if (s.step === "calendar") {
		ok = !!(s.date && s.time && s.availabilityReady);
		label = "Add Your Details";
		need = !s.date ? "Pick a Day" : !s.time ? "Pick a Time" : "";
	}
	if (s.step === "checkout") {
		const ck = contactChecks(s.contact);
		ok = ck.name && ck.email && ck.phone && !!(s.date && s.time) && !!sq?.configured;
		// the policies come next; their button is the one that books and pays, so this one says less
		label = s.square?.checkoutUrl ? "Resume Checkout" : "Review Policies";
		const c = s.contact || {};
		need = !(ck.name && ck.email && ck.phone)
			? c.name && c.email && c.phone ? "Check Your Details" : "Add Your Details to Continue"
			: "";
		if (recovering) { ok = true; label = "Check Booking Status"; }
	}
	// the one button that books: blocked until every policy is ticked, then it pays (or confirms a
	// visit a code covers in full). Blocked, it keeps its words (the owner's call); a tap on it marks
	// the cards still unticked instead (onBlocked, PoliciesStep)
	if (s.step === "policies") {
		const bypass = !!(sq && sq.bypass);
		const left = policyCards(s).filter((card) => !(s.agreed || []).includes(card.key)).length;
		ok = left === 0 && !!(s.date && s.time) && !!sq?.configured;
		label = s.square?.checkoutUrl ? "Resume Checkout" : bypass ? "Confirm Booking" : "Continue to Checkout";
		if (busy) label = bypass ? "Booking…" : "Opening Checkout…";
	}

	// Blocked is not disabled: the button stays focusable and announces what is still needed.
	const off = s.uploadBusy || busy;
	return (
		<button className="cta" disabled={off} aria-disabled={!ok || undefined} onClick={ok ? onNext : onBlocked}>
			{!ok && need && !busy ? need : label}
			{ok && !off && <Ico name="arrow" />}
		</button>
	);
}

// "Start over" in the masthead's step row. Choices are kept in the browser so a reload or a
// trip to checkout loses nothing, which also means a customer needs a way to drop them: one tap
// asks, the second clears everything and returns home.
function StartOver({ label, count, locked, onReset }) {
	const [asking, setAsking] = useState(false);
	useEffect(() => { if (locked) setAsking(false); }, [locked]);
	if (asking) {
		return (
			<div className="step-meta step-ask" role="group" aria-label="Start over"
				onKeyDown={(e) => { if (e.key === "Escape") setAsking(false); }}>
				<span>Clear Your Choices?</span>
				<span className="step-ask-actions">
					<button type="button" className="step-link" autoFocus onClick={() => setAsking(false)}>Keep Choices</button>
					<button type="button" className="step-link step-link-strong" onClick={() => { setAsking(false); onReset(); }}>Start Over</button>
				</span>
			</div>
		);
	}
	return (
		<div className="step-meta">
			<span aria-hidden="true">{label}</span>
			<span className="step-meta-end">
				{!locked && (
					<button type="button" className="step-link" onClick={() => setAsking(true)}>Start Over</button>
				)}
				<span className="step-count" aria-hidden="true">{count}</span>
			</span>
		</div>
	);
}

// Light ⇆ dark theme toggle. State lives on <html data-theme>, owned by theme.js
// (loaded in <head> before paint); this just reflects/flips it and re-renders on the
// "themechange" event (so OS changes and multiple toggles stay in sync).
function ThemeToggle() {
	const [mode, setMode] = useState(
		typeof window !== "undefined" && window.__getTheme ? window.__getTheme() : "light",
	);
	useEffect(() => {
		const sync = () => setMode(window.__getTheme ? window.__getTheme() : "light");
		window.addEventListener("themechange", sync);
		return () => window.removeEventListener("themechange", sync);
	}, []);
	const dark = mode === "dark";
	return (
		<button
			type="button"
			className="icon-btn theme-toggle"
			onClick={() => window.__setTheme && window.__setTheme(dark ? "light" : "dark")}
			aria-label={dark ? "Switch to light mode" : "Switch to dark mode"}
			title={dark ? "Light Mode" : "Dark Mode"}
		>
			<Ico key={dark ? "sun" : "moon"} name={dark ? "sun" : "moon"} />
		</button>
	);
}
