// Lalaluxe booking — booking/screens/calendar.jsx
// Page: "calendar" — month grid + time slots, backed by live /api/availability.
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
// (humanDuration lives in booking/engine/format.js with the other formatters; used here at render time.)
function CalendarStep({ cfg, s, set, dur, recovering = false, availabilityUrl, availabilityToken, held }) {
	const studioTimeZone = cfg.schedule?.timeZone || "America/Chicago";
	const timeZoneLabel = zoneName(studioTimeZone);
	const today = useMemo(() => {
		const parts = new Intl.DateTimeFormat("en-US", {
			timeZone: studioTimeZone, year: "numeric", month: "2-digit", day: "2-digit",
		}).formatToParts(new Date());
		const part = (type) => Number(parts.find((p) => p.type === type).value);
		return new Date(part("year"), part("month") - 1, part("day"));
	}, [studioTimeZone]);
	const initialMonth = useMemo(() => {
		if (s.date) {
			const d = parseYmd(s.date);
			if (d >= today) return { y: d.getFullYear(), m: d.getMonth() };
		}
		return { y: today.getFullYear(), m: today.getMonth() };
	}, [today, s.date]);
	const [view, setView] = useState(initialMonth);
	// How far ahead she can book (the studio opens the calendar month by month): the last day she can
	// book (`until`) and the day the month after it opens (`opens`), as the server last said; null while
	// the studio leaves it off. Kept across months, so the next-month arrow knows before a month loads.
	const [ahead, setAhead] = useState(null);

	const year = view.y;
	const m = view.m;
	const first = new Date(year, m, 1);
	const startDow = first.getDay();
	const daysInMonth = new Date(year, m + 1, 0).getDate();
	const cells = [];
	for (let i = 0; i < startDow; i++) cells.push(null);
	for (let d = 1; d <= daysInMonth; d++) cells.push(d);
	while (cells.length % 7 !== 0) cells.push(null);

	const atMonthStart =
		view.y === today.getFullYear() && view.m === today.getMonth();

	const goPrev = () => {
		if (atMonthStart) return;
		set({ date: null, time: null, availabilityReady: false });
		setView((v) =>
			v.m === 0 ? { y: v.y - 1, m: 11 } : { y: v.y, m: v.m - 1 },
		);
	};
	const goNext = () => {
		if (nextShut) return;
		set({ date: null, time: null, availabilityReady: false });
		setView((v) =>
			v.m === 11 ? { y: v.y + 1, m: 0 } : { y: v.y, m: v.m + 1 },
		);
	};

	// Live availability for the visible month [first .. last], cached per fetched range and
	// refetched on month change. `avail.days` = { "YYYY-MM-DD": ["10:00",…] } of OPEN slots.
	const fromKey = ymd(year, m, 1);
	const toKey = ymd(year, m, daysInMonth);
	// this month is the last she can book (or past it), so the next one is not open yet
	const nextShut = !!ahead && toKey >= ahead.until;
	const notOpenYet = !!ahead && fromKey > ahead.until;
	const [avail, setAvail] = useState({
		days: null,
		loading: true,
		error: false,
	});
	// A time that adds a fee, as the open times list it: a squeeze-in (it starts within the studio's
	// squeeze-in hours of now), after hours or a holiday. A plan's visit is never booked into one online,
	// so a plan is not offered them; a new visit is, marked with what it adds.
	const onPlan = s.visit === "subscription";
	const listed = (map, key, t) => !!map && Array.isArray(map[key]) && map[key].includes(t);
	const feeTimeOf = (map, key, t) => ({
		squeezeIn: listed(map?.squeezeIn, key, t),
		afterHours: listed(map?.afterHours, key, t),
		holiday: listed(map?.holiday, key, t),
	});
	const anyFee = (f) => f.squeezeIn || f.afterHours || f.holiday;
	const [nonce, setNonce] = useState(0); // "Try again" bumps this to refetch after an error
	const [selectionNote, setSelectionNote] = useState("");
	useEffect(() => {
		if (recovering) return;
		let live = true;
		const controller = new AbortController();
		const timeout = setTimeout(() => controller.abort(), 15000);
		set({ availabilityReady: false });
		setSelectionNote("");
		setAvail({ days: null, loading: true, error: false });
		fetch(availabilityUrl ? `${availabilityUrl}?from=${fromKey}&to=${toKey}` : `/api/availability?from=${fromKey}&to=${toKey}&dur=${dur || 0}`, {
			...(availabilityToken ? { headers: { Authorization: `Bearer ${availabilityToken}` } } : {}),
			signal: controller.signal,
		})
			.then(async (r) => {
				if (!r.ok) throw new Error("Availability could not be loaded.");
				const d = await r.json();
				if (!d?.ok || !d.days || Array.isArray(d.days) || typeof d.days !== "object" ||
					Object.values(d.days).some((slots) => !Array.isArray(slots)))
					throw new Error("Availability could not be loaded.");
				return d;
			})
			.then((d) => {
				if (!live) return;
				setAvail({ days: d.days, squeezeIn: d.squeezeIn || {}, afterHours: d.afterHours || {}, holiday: d.holiday || {}, loading: false, error: false });
				setAhead(typeof d.until === "string" && typeof d.opens === "string" ? { until: d.until, opens: d.opens } : null);
				const dateValid = s.date && s.date >= fromKey && s.date <= toKey && parseYmd(s.date) >= today && !(typeof d.until === "string" && s.date > d.until);
				const fees = feeTimeOf(d, s.date, s.time);
				const timeValid = dateValid && (d.days[s.date] || []).includes(s.time) && !(onPlan && anyFee(fees));
				if (s.time && !timeValid)
					setSelectionNote("That time is no longer available. Choose another time.");
				// the time she keeps carries what it adds now (a time can become a squeeze-in while she books)
				set({
					availabilityReady: true,
					...(!dateValid ? { date: null, time: null } : !timeValid ? { time: null } : onPlan ? {} : fees),
				});
			})
			.catch(() => {
				if (!live) return;
				setAvail({ days: null, loading: false, error: true });
				set({ availabilityReady: false, time: null });
			})
			.finally(() => clearTimeout(timeout));
		return () => {
			live = false;
			clearTimeout(timeout);
			controller.abort();
		};
	}, [fromKey, toKey, dur, nonce, set, recovering, availabilityUrl, availabilityToken]);

	// Availability is supplied by the studio schedule in every payment mode.
	const openFor = useCallback(
		(key) => {
			if (avail.loading || avail.error) return [];
			// a day past the month the studio has opened is not hers to book yet
			if (ahead && key > ahead.until) return [];
			const times = (avail.days && avail.days[key]) || [];
			if (!onPlan) return times;
			return times.filter((t) => !anyFee(feeTimeOf(avail, key, t)));
		},
		[avail.loading, avail.days, avail.error, avail.squeezeIn, avail.afterHours, avail.holiday, onPlan, ahead],
	);
	// the days with a time she can take, as openFor offers them
	const openDays = Object.fromEntries(Object.keys(avail.days || {}).map((key) => [key, openFor(key)]));
	const hasOpenDays = Object.entries(openDays).some(
		([key, times]) => parseYmd(key) >= today && times.length > 0,
	);
	// what a time adds to her total, and the words for it: null for a time with no fee
	const feeOfRule = (rule) => (rule && rule.on === true ? Math.max(0, Number(rule.fee) || 0) : 0);
	const timeFee = (key, t) => {
		if (onPlan || !key || !t) return null;
		const f = feeTimeOf(avail, key, t);
		const amt = (f.squeezeIn ? feeOfRule(cfg.schedule?.squeeze) : 0) + (f.afterHours ? feeOfRule(cfg.schedule?.afterHours) : 0) +
			(f.holiday ? feeOfRule(cfg.schedule?.holiday) : 0);
		if (!(amt > 0)) return null;
		return { ...f, amt, name: [f.squeezeIn && "Squeeze-In", f.afterHours && "After Hours", f.holiday && "Holiday"].filter(Boolean).join(" · ") };
	};

	// The selected date is cleared on month navigation, along with its time.
	const pickedInView =
		!!s.date &&
		(() => {
			const d = parseYmd(s.date);
			return d.getFullYear() === year && d.getMonth() === m;
		})();
	const slots = pickedInView ? openFor(s.date) : [];

	return (
		recovering ? (
			<div className="screen">
				<ScreenHead sub="Checking your booking before another time can be chosen.">
					Your <em>Visit.</em>
				</ScreenHead>
				<div className="body">
					<div className="receipt">
						<div className="rcpt-head"><span className="rcpt-title">Booking Status</span></div>
						<dl className="rcpt-list">
							<div className="rcpt-row"><dt className="l">When</dt><dd className="r">{prettyDateShort(s.date)} · {fmtTime(s.time)}</dd></div>
							<div className="rcpt-row"><dt className="l">Confirmation</dt><dd className="r mono">{s.confirmation}</dd></div>
						</dl>
						<div className="rcpt-note">Retry confirmation below. This won’t use another plan visit.</div>
					</div>
				</div>
			</div>
		) : (
		<div className="screen">
			<ScreenHead
				cfg={cfg} screen="calendar"
				sub={s.visit === "subscription"
					? s.subMode === "existing"
						? "Choose a day for your next plan visit."
						: "Choose a day for your first visit. Use the same email to book the rest of your plan."
					: Number.isFinite(dur) && dur > 0
						? `Choose an open day. Allow about ${humanDuration(dur)}.`
						: "Choose an open day."}
			>
				When Are You <em>Free?</em>
			</ScreenHead>

			<div className="body cal-body">
				{/* why the time she had was let go (the server refused that booking), until she picks another */}
				{s.timeNote && <div className="booking-notice" role="alert"><p>{s.timeNote}</p></div>}
				{atMonthStart && !avail.loading && !avail.error && hasOpenDays && (
					<div className="soonest">
						<div className="slot-group-label">Soonest Openings</div>
						<div className="soonest-row">
							{soonestOpenings(openDays, today, 3).map(([key, t]) => {
								const sel = s.date === key && s.time === t;
								const fee = timeFee(key, t);
								return (
									<FeeTime
										key={key}
										className="soon"
										sel={sel}
										fee={fee}
										cfg={cfg}
										date={key}
										time={t}
										label={`${prettyDateShort(key)}, ${fmtTime(t)}`}
										onPick={() => {
											setSelectionNote("");
											set({ date: key, time: t, squeezeIn: !!fee?.squeezeIn, afterHours: !!fee?.afterHours, holiday: !!fee?.holiday });
										}}
									>
										<b>{prettyDateShort(key)}</b>
										<span>{fmtTime(t)}</span>
									</FeeTime>
								);
							})}
						</div>
					</div>
				)}
				<div className="cal-card">
					<div className="cal-head">
						<div className="cal-month">
							{MONTHS_LONG[m]} <em>{year}</em>
						</div>
						<div className="cal-nav">
							<button
								onClick={goPrev}
								disabled={atMonthStart}
								aria-label="Previous month"
							>
								<Ico name="back" />
							</button>
							<button className="next" onClick={goNext} disabled={nextShut} aria-label="Next month">
								<Ico name="next" />
							</button>
						</div>
					</div>

					<div className="cal-dow-row">
						{DOW_SHORT.map((d, i) => (
							<div key={i} className="cal-dow">
								{d}
							</div>
						))}
					</div>

					<div className="cal-grid">
						{cells.map((d, i) => {
							if (d === null)
								return <div key={i} className="cal-cell empty"></div>;
							const dt = new Date(year, m, d);
							const past = dt < today;
							const isToday = sameDay(dt, today);
							const key = ymd(year, m, d);
							// Open/closed is DRIVEN BY availability: a day is open iff it has ≥1 slot. While the
							// month loads, days render dimmed "wait" (not closed, and no flicker into the
							// fallback) until data lands.
							const closed =
								!past && !avail.loading && openFor(key).length === 0;
							const sel = s.date === key;
							const cls = ["cal-cell"];
							if (past) cls.push("past");
							else if (avail.loading) cls.push("wait");
							else if (closed) cls.push("closed");
							else cls.push("avail");
							if (isToday) cls.push("today");
							if (sel) cls.push("sel");
							const disabled = past || avail.loading || closed;
							return (
								<button
									key={i}
									className={cls.join(" ")}
									disabled={disabled}
									aria-label={`${MONTHS_LONG[m]} ${d}, ${year}`}
									aria-pressed={sel}
									onClick={() => {
										if (disabled) return;
										setSelectionNote("");
										set({ date: key, time: null });
										// Short/mid viewports can render the slot list below the fold;
										// "nearest" makes this a no-op when it is already visible.
										requestAnimationFrame(() =>
											document
												.querySelector(".slot-section")
												?.scrollIntoView({ block: "nearest", behavior: "smooth" }),
										);
									}}
								>
									<span>{d}</span>
								</button>
							);
						})}
					</div>

					<div className="cal-legend">
						<span className="l-item">
							<span className="swatch"></span> Open
						</span>
						<span className="l-item">
							<span className="swatch today"></span> Today
						</span>
						{pickedInView && (
							<span className="l-item">
								<span className="swatch sel"></span> Picked
							</span>
						)}
					</div>
					{/* the studio opens the calendar month by month: when the next month opens */}
					{nextShut && <OpensNote ahead={ahead} />}
				</div>

				<div className="slot-section">
					{pickedInView && (
						<div className="slabel" role="status">
							<span>Available Times</span>
							<span className="picked">{prettyDateShort(s.date)}</span>
						</div>
					)}
					{selectionNote && <div className="empty-slots" role="status">{selectionNote}</div>}
					{avail.loading ? (
						<div className="empty-slots" role="status">
							{pickedInView ? "Loading times…" : "Loading open days…"}
						</div>
					) : avail.error ? (
						<div className="empty-slots" role="status">
							Times couldn’t be loaded. Try again.
							<button
								className="cal-retry"
								onClick={() => {
									set({ availabilityReady: false });
									setNonce((n) => n + 1);
								}}
							>
								Try Again
							</button>
						</div>
					) : null}
					{!avail.loading && !avail.error &&
						(!pickedInView ? (
							!hasOpenDays && !notOpenYet && (
								<div className="empty-slots" role="status">
									{nextShut ? "No appointments are available this month." : "No appointments are available this month. Try the next month."}
								</div>
							)
						) : slots.length === 0 ? (
							<div className="empty-slots" role="status">
								No times available. Choose another day.
							</div>
						) : (
							<>
								{/* what the coloured times add: amber a squeeze-in, purple after hours, teal a holiday */}
								<FeeKey cfg={cfg} fees={slots.map((t) => timeFee(s.date, t))} />
								{slotGroups(slots).map(([part, times]) => (
									<div className="slot-group" key={part}>
										<div className="slot-group-label">{part}</div>
										<div className={"slots" + (times.some((t) => timeFee(s.date, t)) ? " slots--fee" : "")}>
											{times.map((t) => {
												const sel = s.time === t;
												const fee = timeFee(s.date, t);
												return (
													<FeeTime
														key={t}
														className="slot"
														sel={sel}
														fee={fee}
														cfg={cfg}
														date={s.date}
														time={t}
														label={fmtTime(t)}
														onPick={() => {
															setSelectionNote("");
															set({ time: t, squeezeIn: !!fee?.squeezeIn, afterHours: !!fee?.afterHours, holiday: !!fee?.holiday });
														}}
													>
														{fmtTime(t)}
														{/* when moving a visit, the time she already holds is named */}
														{held && held.date === s.date && held.time === t
															? <small>Current Time</small>
															: dur > 0 && <small>to {fmtTime(slotEnd(t, dur))}</small>}
													</FeeTime>
												);
											})}
										</div>
									</div>
								))}
							</>
						))}
					{/* a plan's visit is not booked into a time that adds a fee, so those are left out, and she is told */}
					{onPlan && pickedInView && !avail.loading && !avail.error && ((avail.days && avail.days[s.date]) || []).length > slots.length && (
						<p className="custom-hint">To book a plan visit at a time with an extra fee, contact the studio.</p>
					)}
					{pickedInView && s.time && (
						<div className="when-pill" role="status">
							<Ico name="calendar" />
							<div>
								<b>{prettyDate(s.date)} · {fmtTime(s.time)}</b>
								{dur > 0 && <span>, about {humanDuration(dur)}</span>}
								{timeFee(s.date, s.time) && (
									<span className="when-fee">{timeFee(s.date, s.time).name} · {money(timeFee(s.date, s.time).amt)} is added to your total.</span>
								)}
							</div>
						</div>
					)}
					<p className="custom-hint">Times are shown in {timeZoneLabel}.</p>
				</div>
			</div>
		</div>
		)
	);
}

// Presentation helpers for the slot list. Declared after CalendarStep on purpose:
// test/ui/booking/availability.test.js slices the component's logic from the top of this file.
function slotGroups(slots) {
	const parts = [["Morning", []], ["Afternoon", []], ["Evening", []]];
	for (const t of slots) {
		const hour = Number(t.split(":")[0]);
		parts[hour < 12 ? 0 : hour < 17 ? 1 : 2][1].push(t);
	}
	return parts.filter(([, times]) => times.length);
}
// A fee time wears its colour (fee-squeeze amber, fee-after purple, fee-holiday teal) and what it adds,
// "+$20", in its corner.
function feeKinds(fee) {
	return fee ? [fee.squeezeIn && "squeeze", fee.afterHours && "after", fee.holiday && "holiday"].filter(Boolean) : [];
}
// A time the client can pick. One that adds a fee (a squeeze-in, after hours, a holiday) asks first
// (FeeAsk), and is theirs only once they say they understand the fee; a time already held is picked
// again as it is.
function FeeTime({ className, sel, fee, cfg, date, time, label, onPick, children }) {
	const [asking, setAsking] = useState(false);
	const opener = useRef(null);
	return (
		<>
			<button
				ref={opener}
				className={[className, ...feeKinds(fee).map((k) => "fee-" + k), sel && "sel"].filter(Boolean).join(" ")}
				aria-pressed={sel}
				aria-label={fee ? `${label}. ${fee.name}, adds ${money(fee.amt)}` : undefined}
				aria-haspopup={fee && !sel ? "dialog" : undefined}
				onClick={() => (fee && !sel ? setAsking(true) : onPick())}
			>
				{children}
				{fee && <span className="fee-tag" aria-hidden="true">+{money(fee.amt)}</span>}
			</button>
			{asking && (
				<FeeAsk
					cfg={cfg}
					fee={fee}
					date={date}
					time={time}
					opener={opener}
					onYes={() => {
						setAsking(false);
						onPick();
					}}
					onNo={() => setAsking(false)}
				/>
			)}
		</>
	);
}
// Before a time with a fee is hers: what it adds and why, and that she understands. A sheet portalled to
// the app's root (never inside .screen-wrap). Escape or a tap outside keeps her on the times, and focus
// goes back to the time she tapped.
function FeeAsk({ cfg, fee, date, time, opener, onYes, onNo }) {
	const yes = useRef(null);
	const card = useRef(null);
	useEffect(() => {
		yes.current?.focus();
		const back = opener.current;
		return () => {
			if (back && back.isConnected) back.focus();
		};
	}, []);
	const hours = Number(cfg.schedule?.squeeze?.hours) || 0;
	const feeOf = (rule) => money(Math.max(0, Number(rule?.fee) || 0));
	const keys = (e) => {
		if (e.key === "Escape") {
			e.preventDefault();
			onNo();
		} else if (e.key === "Tab") {
			// two buttons, and Tab stays on them
			const stops = [...card.current.querySelectorAll("button")];
			const at = stops.indexOf(document.activeElement);
			e.preventDefault();
			stops[(at + (e.shiftKey ? -1 : 1) + stops.length) % stops.length].focus();
		}
	};
	return ReactDOM.createPortal(
		<div className="fee-ask" onClick={(e) => e.target === e.currentTarget && onNo()}>
			<div
				ref={card}
				className={["fee-ask-card", ...feeKinds(fee).map((k) => "fee-" + k)].join(" ")}
				role="alertdialog"
				aria-modal="true"
				aria-labelledby="fee-ask-title"
				aria-describedby="fee-ask-why"
				onKeyDown={keys}
			>
				<p className="fee-ask-when">{fee.name} · {prettyDateShort(date)} · {fmtTime(time)}</p>
				<h2 className="fee-ask-title" id="fee-ask-title">This Time Costs <em>{money(fee.amt)} More.</em></h2>
				<div className="fee-ask-why" id="fee-ask-why">
					{fee.squeezeIn && (
						<p>This visit starts within {hours} {hours === 1 ? "hour" : "hours"}. A {feeOf(cfg.schedule?.squeeze)} squeeze-in fee applies.</p>
					)}
					{fee.afterHours && (
						<p>This visit is outside studio hours. A {feeOf(cfg.schedule?.afterHours)} after-hours fee applies.</p>
					)}
					{fee.holiday && (
						<p>This visit is on a holiday. A {feeOf(cfg.schedule?.holiday)} holiday fee applies.</p>
					)}
				</div>
				<button ref={yes} className="cta" onClick={onYes}>
					<span>I Understand · Add {money(fee.amt)}</span>
					<Ico name="next" />
				</button>
				<button className="fee-ask-no" onClick={onNo}>Choose Another Time</button>
			</div>
		</div>,
		document.getElementById("app") || document.body,
	);
}
// The key to the coloured times, above the list on a day that has any.
function FeeKey({ cfg, fees }) {
	const has = (kind) => fees.some((fee) => fee && fee[kind]);
	const feeOf = (rule) => money(Math.max(0, Number(rule?.fee) || 0));
	if (!has("squeezeIn") && !has("afterHours") && !has("holiday")) return null;
	return (
		<div className="fee-key">
			{has("squeezeIn") && <span className="fee-key-item fee-squeeze"><i aria-hidden="true"></i>Squeeze-In +{feeOf(cfg.schedule?.squeeze)}</span>}
			{has("afterHours") && <span className="fee-key-item fee-after"><i aria-hidden="true"></i>After Hours +{feeOf(cfg.schedule?.afterHours)}</span>}
			{has("holiday") && <span className="fee-key-item fee-holiday"><i aria-hidden="true"></i>Holiday +{feeOf(cfg.schedule?.holiday)}</span>}
		</div>
	);
}
// When the next month opens, under the calendar on the last month she can book: "January opens for
// booking on Tuesday, December 15." The month after `until` is the one that opens on `opens`.
function OpensNote({ ahead }) {
	const last = parseYmd(ahead.until);
	return (
		<p className="cal-opens" role="note">
			<Ico name="calendar" />
			<span><b>{MONTHS_LONG[(last.getMonth() + 1) % 12]}</b> opens for booking on {prettyDate(ahead.opens)}.</span>
		</p>
	);
}
// The first open time on each of the next few open days of the loaded month.
function soonestOpenings(days, today, count) {
	return Object.keys(days || {})
		.sort()
		.filter((key) => parseYmd(key) >= today && days[key].length > 0)
		.slice(0, count)
		.map((key) => [key, days[key][0]]);
}
function slotEnd(t, dur) {
	const [h, m] = t.split(":").map(Number);
	const end = h * 60 + m + dur;
	return String(Math.floor(end / 60) % 24).padStart(2, "0") + ":" + String(end % 60).padStart(2, "0");
}
