// Lalaluxe booking — booking/screens/subcode.jsx
// Page: "subcode" (continue a plan: the email it was booked with → a one-time code emailed to
// it → the plans under that email). "subdone" (the visit booked) is subdone.jsx.
// These power the EXISTING-plan redemption flow: email → code → plan → calendar → redeem.
// No payment/consent (prepaid). There is no plan code to keep: the server hands the page the
// plan's key once the email is proved. One screen per file. Load before app.jsx.
function SubCodeStep({ cfg, s, set, go }) {
	const [busy, setBusy] = useState("");
	const [error, setError] = useState("");
	const [sent, setSent] = useState(false);
	const [code, setCode] = useState("");
	const request = useRef(null);
	useEffect(() => () => request.current?.abort(), []);
	const lookup = s.subLookup;
	const plans = s.subPlans;
	const email = s.subEmail || "";

	const call = async (kind, path, body) => {
		if (request.current) return null;
		const controller = new AbortController();
		request.current = controller;
		setBusy(kind);
		setError("");
		try {
			const resp = await fetch(path, {
				method: "POST",
				signal: controller.signal,
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(body),
			});
			const d = await resp.json().catch(() => ({}));
			if (controller.signal.aborted) return null;
			if (!resp.ok || !d.ok) {
				setError((d && d.error) || "The request failed. Try again.");
				return null;
			}
			return d;
		} catch (e) {
			if (!controller.signal.aborted) setError("The studio couldn’t be reached. Try again.");
			return null;
		} finally {
			if (!controller.signal.aborted) {
				request.current = null;
				setBusy("");
			}
		}
	};

	const cleared = { subCode: "", subLookup: null, plan: null, planTier: null, subaddons: [], date: null, time: null, availabilityReady: false };
	const pick = (p) => set({ subCode: p.code, subLookup: p, plan: p.plan, planTier: p.tier || null, subaddons: p.subaddons || [], date: null, time: null, availabilityReady: false });
	const usable = (p) => p.ready && p.remaining > 0;

	const sendCode = async () => {
		if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
			setError("Enter the email you booked your plan with.");
			return;
		}
		const d = await call("send", "/api/plans/send-code", { email: email.trim() });
		if (!d) return;
		set({ subEmail: d.email, subPlans: null, ...cleared });
		setCode("");
		setSent(true);
	};

	const checkCode = async (value = code) => {
		if (!/^\d{6}$/.test(value)) {
			setError("Enter the 6-digit code from your email.");
			return;
		}
		const d = await call("check", "/api/plans/verify", { email, code: value });
		if (!d) return;
		const list = d.plans || [];
		const open = list.filter(usable);
		set({ subPlans: list, ...cleared });
		if (open.length === 1) pick(open[0]);
		setSent(false);
	};

	const restart = () => {
		set({ subEmail: "", subPlans: null, ...cleared });
		setCode("");
		setSent(false);
		setError("");
	};

	const stage = plans ? "plans" : sent ? "code" : "email";
	const canBook = !busy && lookup && lookup.remaining > 0;

	return (
		<div className="screen">
			<ScreenHead cfg={cfg} screen="subcode">
				Your <em>Plan.</em>
			</ScreenHead>

			<div className="body">
				{stage === "email" && (
					<>
						<div className="field">
							<label className="lab" htmlFor="sub-email">
								Email
							</label>
							<input
								id="sub-email"
								type="email"
								inputMode="email"
								autoComplete="email"
								autoCapitalize="none"
								spellCheck={false}
								placeholder="you@example.com"
								disabled={!!busy}
								value={email}
								onChange={(e) => {
									setError("");
									set({ subEmail: e.target.value });
								}}
								onKeyDown={(e) => {
									if (e.key === "Enter") {
										e.preventDefault();
										sendCode();
									}
								}}
							/>
						</div>
						{error && <div className="sub-error" role="alert">{error}</div>}
						<button className="cta" onClick={sendCode} aria-disabled={!!busy || !email.trim()}>
							{busy ? "Sending…" : email.trim() ? "Email Me a Code" : "Enter Your Email"} <Ico name="arrow" />
						</button>
					</>
				)}

				{stage === "code" && (
					<>
						<p className="sub-sent">
							If a plan is linked to <b>{email}</b>, a 6-digit code will arrive shortly. The code expires in 10 minutes.
						</p>
						<div className="field code-field">
							<label className="lab" htmlFor="sub-code">
								Code
							</label>
							<input
								id="sub-code"
								type="text"
								inputMode="numeric"
								autoComplete="one-time-code"
								pattern="[0-9]*"
								maxLength={6}
								placeholder="000000"
								disabled={!!busy}
								value={code}
								onChange={(e) => {
									const v = e.target.value.replace(/\D/g, "").slice(0, 6);
									setError("");
									setCode(v);
									if (v.length === 6) checkCode(v);
								}}
								onKeyDown={(e) => {
									if (e.key === "Enter") {
										e.preventDefault();
										checkCode();
									}
								}}
							/>
						</div>
						{error && <div className="sub-error" role="alert">{error}</div>}
						<button className="cta" onClick={() => checkCode()} aria-disabled={!!busy || code.length !== 6}>
							{busy === "check" ? "Checking…" : code.length === 6 ? "Continue" : "Enter the 6-Digit Code"} <Ico name="arrow" />
						</button>
						<div className="sub-links">
							<button type="button" className="sub-link" onClick={sendCode} disabled={!!busy}>
								{busy === "send" ? "Sending…" : "Send a New Code"}
							</button>
							<button type="button" className="sub-link" onClick={restart} disabled={!!busy}>
								Use Another Email
							</button>
						</div>
						<p className="custom-hint">No code? Check spam and confirm you used the email from your plan purchase.</p>
					</>
				)}

				{stage === "plans" && (
					<>
						{plans.length === 0 ? (
							<div className="sub-error" role="alert">
								No plan was found for {email}. Try your purchase email or contact the studio.
							</div>
						) : (
							<div className="plan-picks" role={plans.length > 1 ? "radiogroup" : undefined} aria-label={plans.length > 1 ? "Your plans" : undefined}>
								{plans.length > 1 && <p className="lab">Choose a Plan</p>}
								{plans.map((p) => (
									<SubPlanCard
										key={p.code}
										cfg={cfg}
										p={p}
										many={plans.length > 1}
										selected={lookup?.code === p.code}
										onPick={() => usable(p) && pick(p)}
									/>
								))}
							</div>
						)}
						{error && <div className="sub-error" role="alert">{error}</div>}
						{plans.length > 0 && (
							<button
								className="cta"
								aria-disabled={!canBook}
								onClick={() => canBook && go("calendar")}
							>
								{canBook ? "Pick a Time" : plans.some(usable) ? "Choose a Plan" : "No Visits Available to Book"} <Ico name="arrow" />
							</button>
						)}
						<div className="sub-links">
							<button type="button" className="sub-link" onClick={restart}>
								Use Another Email
							</button>
						</div>
					</>
				)}
			</div>
		</div>
	);
}

// One plan under the email: what it covers, and how many visits are left on it.
function SubPlanCard({ cfg, p, many, selected, onPick }) {
	const name = cfg.labels?.plan?.[p.plan] || p.plan || "3-Visit Plan";
	const tier = cfg.labels?.tier?.[p.tier];
	const bought = p.boughtAt ? new Date(p.boughtAt).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }) : "";
	const status = !p.ready
		? "Available after payment is confirmed."
		: p.remaining <= 0
			? `All ${p.visitsAllowed} visits used.`
			: `${p.remaining} of ${p.visitsAllowed} visits left`;
	const body = (
		<>
			<span className="pp-top">
				<span className="pp-name">{name}</span>
				{tier && <span className="pp-tier">{tier} Nail Art</span>}
			</span>
			<PunchCard total={p.visitsAllowed || 3} left={Math.max(0, p.remaining)} />
			<span className="pp-foot">
				<span>{status}</span>
				{bought && <span>Bought {bought}</span>}
			</span>
		</>
	);
	if (!many) return <div className={"plan-pick" + (p.ready && p.remaining > 0 ? "" : " spent")}>{body}</div>;
	const open = p.ready && p.remaining > 0;
	return (
		<button
			type="button"
			role="radio"
			aria-checked={selected}
			aria-disabled={!open}
			className={"plan-pick" + (selected ? " sel" : "") + (open ? "" : " spent")}
			onClick={onPick}
		>
			{body}
		</button>
	);
}
