// Lalaluxe booking — booking/screens/base.jsx
// Page: "base" — base nail service PLUS arrival prep (soak-off removal). The service list
// renders from config (labels.service / content.order.service), so nail repair — its own
// category since 2026-06-10 (owner call; it used to hide as a prep add-on under fill-in/
// overlay/gel) — and any admin-created service appear here without code changes. Pricing
// kind is derived from the shape of cfg.base[id]: per-length → "From" the service's own price
// (cfg.servicePrice[id]; the length adds to it), { flat }
// → "$n"; overlay/gel keep their special flat keys.
// Prep is about the STATE you arrive in, not your look, and applicability
// is per-service so the offer never contradicts the service: you don't soak off a set you're
// filling, and a repair visit IS the arrival problem. Prep is all that lives in s.addons; the
// look itself is s.art.
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
const PREP_FOR = {
	fullset: ["removal"],
	overlay: ["removal"],
	gel: ["removal"],
};

function BaseStep({ cfg, s, set, toggleArr }) {
	// Arrival prep sits under the service list, below the fold on a phone. Picking a service brings
	// it into view, so removal is offered before she moves on; arriving at the screen with a
	// service already chosen leaves the page where it is.
	const prepBlock = useRef(null);
	const [picked, setPicked] = useState(0);
	useEffect(() => {
		if (!picked || !prepBlock.current) return;
		const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
		prepBlock.current.scrollIntoView({ block: "end", behavior: still ? "auto" : "smooth" });
	}, [picked]);

	const price = (id) => {
		const tiers = cfg.base[id];
		if (!tiers)
			// overlay/gel skip length → flat, not "from"
			return priceTag(id === "gel" ? cfg.gelAdult : cfg.overlay, "flat");
		return tiers.flat != null
			? priceTag(tiers.flat, "flat")
			: priceTag(cfg.servicePrice?.[id], "from"); // the length and the nail art add to it
	};
	// gel is the standalone fork below, not an acrylic-list row (orderedKeys would otherwise
	// re-append it since it still lives in labels.service for pricing/summary). A service the
	// studio has taken off the menu (any of them, gel and overlay included) is not offered.
	const row = (id) => ({
		id,
		name: cfg.labels.service[id],
		desc: cfg.content.serviceDesc[id],
		icon: cfg.content.serviceIcon?.[id],
		price: price(id),
	});
	const opts = orderedKeys(cfg.content.order?.service, cfg.labels.service)
		.filter((id) => id !== "gel" && serviceOffered(id))
		.map(row);
	// gel polish is offered while it is on the menu, and the child's price while it has one
	const gelOn = typeof cfg.labels.service?.gel === "string" && serviceOffered("gel");
	const kidsGel = gelOn && serviceOffered("gel", true);
	// with no acrylic service on the menu, gel is the list's one row; with no gel, there is no fork
	const gelOnly = gelOn && !opts.length;
	if (gelOnly) opts.push(row("gel"));
	const fork = gelOn && !gelOnly;

	const prep = (PREP_FOR[s.service] || []).filter((id) => cfg.addon[id] != null).map((id) => ({
		id,
		name: cfg.labels.addon[id],
		desc: cfg.content.addonDesc[id],
		price: priceTag(cfg.addon[id]),
	}));

	// Switching service drops prep picks that don't apply to the new service. Nail art
	// persists — except into repair, which skips the look screen entirely, so a stale pick
	// could never be reviewed or removed there.
	const pickService = (id) => {
		set({
			service: id,
			length: null,
			addons: s.addons.filter((a) => (PREP_FOR[id] || []).includes(a)),
			...(id === "repair" ? { art: [], shape: null } : {}),
			// the child's price is gel polish's alone, and only while the studio has one
			...(id !== "gel" || !kidsGel ? { isKid: false } : {}),
		});
		setPicked((n) => n + 1);
	};

	// Top-level fork: an acrylic-based service (full set/fill/overlay/repair, each with its own
	// base price + length) vs. gel polish — the standalone no-acrylic service that replaces the
	// whole base ($40 flat, skips length). Gel used to sit in the acrylic list; pulled out so the
	// "what kind of set?" question reads clearly. Default to acrylic so the common path is one tap.
	const mode = fork ? s.setType || (s.service === "gel" ? "gel" : "acrylic") : "acrylic";
	// the gel description, then what comes next, without a stray full stop when it has none
	const gelDesc = String(cfg.content.serviceDesc?.gel || "").trim().replace(/\.+$/, "");
	// the child price exists for gel polish only, so the flag leaves with gel
	const pickAcrylic = () =>
		set({ setType: "acrylic", isKid: false, ...(s.service === "gel" ? { service: null, length: null } : {}) });
	const pickGel = () => {
		set({ setType: "gel", service: "gel", length: null, ...(kidsGel ? {} : { isKid: false }) });
		setPicked((n) => n + 1);
	};

	return (
		<div className="screen">
			<ScreenHead cfg={cfg} screen="base">
				Choose Your <em>Service</em>
			</ScreenHead>
			<div className="body">
				{fork && (
					<div className="svc-fork" data-on={mode}>
						<button
							className={"svc-fork-btn " + (mode === "acrylic" ? "sel" : "")}
							aria-pressed={mode === "acrylic"}
							onClick={pickAcrylic}
						>
							<span className="sf-name">Acrylic Set</span>
							<span className="sf-sub">{opts.map((option) => option.name.trim()).join(" · ")}</span>
						</button>
						<button
							className={"svc-fork-btn " + (mode === "gel" ? "sel" : "")}
							aria-pressed={mode === "gel"}
							onClick={pickGel}
						>
							<span className="sf-name">{cfg.labels.service.gel}</span>
							<span className="sf-sub">
								{priceTag(s.isKid && kidsGel ? cfg.gelKid : cfg.gelAdult, "flat")} · No Acrylic
							</span>
						</button>
					</div>
				)}

				{mode === "acrylic" ? (
					<div className="opt-list">
						{opts.map((o) => (
							<button
								key={o.id}
								className={"opt opt-lg " + (s.service === o.id ? "sel" : "")}
								aria-pressed={s.service === o.id}
								onClick={() => pickService(o.id)}
							>
								<ServiceIcon kind={o.icon} />
								<div className="meta">
									<div className="name">{o.name}</div>
									<div className="desc">{o.desc}</div>
								</div>
								<div className="price">{o.price.startsWith("From ") ? <><small>From</small>{o.price.slice(5)}</> : o.price}</div>
							</button>
						))}
					</div>
				) : (
					<div className="gel-card sel">
						<ServiceIcon kind={cfg.content.serviceIcon?.gel} />
						<div>
							<b>{s.isKid && kidsGel ? "Kids Gel Polish" : cfg.labels.service.gel}</b>
							<span className="gel-note">{gelDesc ? gelDesc + ". " : ""}Choose your nail art next.</span>
						</div>
						<div className="price">{priceTag(s.isKid && kidsGel ? cfg.gelKid : cfg.gelAdult, "flat")}</div>
					</div>
				)}
				{kidsGel && s.service === "gel" && (
					<label className="check-row">
						<input type="checkbox" checked={s.isKid} onChange={() => set({ isKid: !s.isKid })} />
						<span className="cbox"><Ico name="check" /></span>
						<span className="check-copy">
							<b>For a Child</b>
							<small>{priceTag(cfg.gelKid, "flat")} for kids gel polish.</small>
						</span>
					</label>
				)}

				{prep.length > 0 && (
					<section className="block" ref={prepBlock}>
						<h3 className="co-section">Arriving with an Old Set?</h3>
						<div className="addon-list">
							{prep.map((o) => (
								<AddonRow
									key={o.id}
									item={o}
									on={s.addons.indexOf(o.id) > -1}
									onToggle={() => toggleArr("addons", o.id)}
								/>
							))}
						</div>
					</section>
				)}
			</div>
		</div>
	);
}
