// Lalaluxe booking — booking/screens/summary.jsx
// Page: "summary" — review the receipt before scheduling. The pinned botbar owns the
// "Pick a time" CTA (next() routes summary → calendar).
function SummaryStep({ cfg, s, set, sq, edit }) {
	const items = priceItems(s);
	const t = total(s);
	const duration = totalDuration(s);
	// pay at visit: nothing is charged at booking, which gates the due copy below
	const bypass = !!(sq && sq.bypass);
	const dueNowDeposit = Math.min(CFG.deposit, t);
	const steps = editSteps(s, items);
	const notes = s.contact?.notes || "";
	const inspo = s.shareImages?.length || 0;
	// the notes and inspo are written on the look screen, so only a set that has one can edit them here
	const notesStep = s.visit !== "subscription" && s.who !== "toes" && s.service !== "repair" ? "design" : null;
	return (
		<div className="screen">
			<ScreenHead cfg={cfg} screen={s.visit === "subscription" ? "summaryPlan" : "summary"}>
				Review Your <em>{s.visit === "subscription" ? "Plan" : "Set"}</em>
			</ScreenHead>

			<div className="body">
				<div className="receipt">
					<div className="rcpt-head">
						<span className="rcpt-title">
							{bookingTitle(s)}
							{s.visit !== "subscription" && <EditPencil label="Change nails or toes" onClick={() => edit("who")} />}
						</span>
						{duration > 0 && (
							<span className="rcpt-chip">
								<Ico name="clock" />
								About {humanDuration(duration)}
							</span>
						)}
					</div>
					{items.length === 0 ? (
						<div className="rcpt-list">
							<div className="rcpt-row">
								<span className="l">Nothing Selected</span>
							</div>
						</div>
					) : (
						<dl className="rcpt-list rcpt-items">
							{items.map((it, i) => (
								<div className={"rcpt-row" + (it.coupon ? " rcpt-coupon" : "")} key={i}>
									<dt className="l">{it.label}</dt>
									<dd className="r">{it.amt === 0 ? "Included" : money(it.amt)}</dd>
									{steps[i] && <dd className="ed"><EditPencil label={"Change " + it.label} onClick={() => edit(steps[i])} /></dd>}
									{it.coupon && set && <dd className="ed"><button type="button" className="rcpt-edit" aria-label={"Remove code " + s.coupon.code} title="Remove code" onClick={() => set({ coupon: null })}><Ico name="x" /></button></dd>}
								</div>
							))}
							{(notes || inspo > 0) && (
								<div className="rcpt-row rcpt-notes">
									<dt className="l">
										<span className="nt-lbl">Your Notes</span>
										{notes && <span className="nt-text">{notes}</span>}
										{inspo > 0 && <span className="nt-text">{inspo} inspo {inspo === 1 ? "photo attached" : "photos attached"}</span>}
									</dt>
									{notesStep && <dd className="ed"><EditPencil label="Change your notes" onClick={() => edit(notesStep)} /></dd>}
								</div>
							)}
						</dl>
					)}
					{items.length > 0 && set && !s.coupon && <CouponEntry set={set} />}
					<div className="rcpt-tear" aria-hidden="true" />
					<div className="rcpt-total">
						<span className="lbl">
							{s.visit === "subscription" ? "Plan Total" : "Total"}
						</span>
						<span className="amt">{money(t)}</span>
					</div>
					{/* what is paid today and what is left for the visit; a code that covers it all leaves nothing at either */}
					<ol className="pay-steps" aria-label="When you pay">
						<li>
							<span className="ps-when">Today</span>
							<span className="ps-what">
								{bypass
									? "Nothing to Pay"
									: s.visit === "subscription"
										? `Full Plan Payment · ${PLAN_VISITS} Visits`
										: s.payFull === true && t > dueNowDeposit ? "Full Appointment Payment" : "Deposit to Hold Your Time"}
							</span>
							<span className="ps-amt">{money(bypass ? 0 : dueNow(s))}</span>
						</li>
						<li>
							<span className="ps-when">{s.visit === "subscription" ? "First Visit" : "At Your Visit"}</span>
							<span className="ps-what">
								{s.visit === "subscription" || bypass || t - dueNow(s) === 0 ? "Nothing More to Pay" : "Balance"}
							</span>
							<span className="ps-amt">{money(bypass ? 0 : t - dueNow(s))}</span>
						</li>
					</ol>
					{unpricedVisit(s) && (
						<div className="rcpt-note" role="status">{UNPRICED_VISIT}</div>
					)}
					{s.visit === "subscription" && (
						<div className="rcpt-note">
							Book your first visit next. Use the same email to book the rest of your plan.
						</div>
					)}
				</div>
			</div>
		</div>
	);
}

// "Have a code?": the client's coupon, checked by the server before it goes on the bill
function CouponEntry({ set }) {
	const [open, setOpen] = useState(false);
	const [code, setCode] = useState("");
	const [busy, setBusy] = useState(false);
	const [error, setError] = useState("");
	const field = useRef(null);
	useEffect(() => { if (open && field.current) field.current.focus(); }, [open]);
	const apply = async (e) => {
		e.preventDefault();
		const wanted = code.trim();
		if (!wanted) { setError("Enter your code."); return; }
		setBusy(true); setError("");
		try {
			const r = await fetch("/api/coupons/check", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: wanted }) });
			const d = await r.json().catch(() => null);
			if (!r.ok || !d?.ok || !d.coupon) throw new Error(d?.error || "The code couldn’t be checked. Try again.");
			set({ coupon: d.coupon });
		} catch (err) {
			setError(err.message || "The code couldn’t be checked. Try again.");
			setBusy(false);
		}
	};
	if (!open)
		return (
			<div className="rcpt-code">
				<button type="button" className="rcpt-code-open" onClick={() => setOpen(true)}>
					<span>Have a Code?</span>
					<span className="rcpt-code-add"><Ico name="plus" />Add</span>
				</button>
			</div>
		);
	return (
		<form className="rcpt-code is-open" onSubmit={apply} noValidate>
			<label className="lab" htmlFor="rcpt-code-input">Code</label>
			<div className="rcpt-code-row">
				<input id="rcpt-code-input" ref={field} type="text" value={code} placeholder="Enter your code" autoComplete="off" autoCapitalize="characters" spellCheck={false} maxLength={24}
					aria-invalid={error ? true : undefined} aria-describedby={error ? "rcpt-code-err" : undefined}
					onChange={(e) => { setCode(e.target.value.toUpperCase()); setError(""); }} />
				<button type="submit" className="rcpt-code-apply" disabled={busy}>{busy ? "Checking…" : "Apply"}</button>
			</div>
			{error && <span className="field-err" id="rcpt-code-err" role="alert">{error}</span>}
		</form>
	);
}

// the pencil beside a line: opens the screen where that choice was made
function EditPencil({ label, onClick }) {
	return (
		<button type="button" className="rcpt-edit" aria-label={label} title={label} onClick={onClick}>
			<Ico name="edit" />
		</button>
	);
}

// which screen each receipt line was chosen on, index for index with priceItems(s)
function editSteps(s, items) {
	// a code is taken off with its own button, not chosen on a screen
	return editStepsOf(s, items).map((step, i) => (items[i] && items[i].coupon ? null : step));
}
function editStepsOf(s, items) {
	if (s.visit === "subscription")
		// the plan fee (planFee in booking/engine/pricing.js) is the studio's, the last line, and not chosen anywhere
		return items.map((it, i) => (i === 0 && s.plan ? "plan" : it.label === "Plan Fee" ? null : "subaddons"));
	const nails = s.who === "nails" || s.who === "both" ? priceItems({ ...s, who: "nails" }).length : 0;
	const byNail = (nailLines(s) || []).map(nailLabel).concat((shapeLines(s) || []).map(shapeLineLabel));
	const art = byNail.length ? null : artTier(s);
	const artLabel = art ? tierLabel(art.id, "Tier") : null;
	const lengthLabel = s.length ? "Length: " + CFG.labels.length[s.length] : null;
	const shapeLabel = typeof s.shape === "string" && (CFG.labels.shape || {})[s.shape] ? "Shape: " + CFG.labels.shape[s.shape] : null;
	// toe lines, toe art included, are all chosen on the toes screen
	return items.map((it, i) => {
		if (i >= nails) return "tbase";
		if (it.label === artLabel || byNail.includes(it.label) || it.label === shapeLabel) return "design";
		return it.label === lengthLabel ? "length" : "base";
	});
}
