// Lalaluxe booking — booking/screens/pricecheck.jsx
// Page: "pricecheck" — upload an inspo photo, inspect the Clef System One primitives and instant
// menu estimate, confirm base service / prep options, then accept to pick a time or make changes.
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
function PriceCheckStep({ cfg, s, set, sq, edit }) {
	const [busy, setBusy] = useState(false);
	const [error, setError] = useState("");
	const [previewUrl, setPreviewUrl] = useState("");
	const photo = (s.shareImages || [])[0] || null;
	const result = s.priceCheckResult || null;

	useEffect(() => {
		if (!photo) {
			setPreviewUrl("");
			return;
		}
		const url = URL.createObjectURL(photo);
		setPreviewUrl(url);
		return () => URL.revokeObjectURL(url);
	}, [photo]);

	const shapeLine = /^Shape: [^\n]*\n?/;
	const generatedLines = /^(?:Shape|Nails|Shapes|Toes|Toe base): [^\n]*\n?/gm;
	const buildNotes = (shapeKey, existing) => {
		const rest = String(existing || "").replace(generatedLines, "").trimStart();
		const label = shapeKey && cfg.labels?.shape?.[shapeKey];
		return label ? `Shape: ${String(label).trim()}\n${rest}` : rest;
	};

	const analyzeFile = async (e) => {
		const picked = e.target.files?.[0];
		e.target.value = "";
		if (!picked) return;
		setBusy(true);
		setError("");
		set({ uploadBusy: true });
		try {
			const prepared = await preparePriceCheckImage(picked);
			const form = new FormData();
			form.append("image", prepared, prepared.name || "inspo.jpg");
			const resp = await fetch("/api/price-check", { method: "POST", body: form });
			const data = await resp.json().catch(() => null);
			if (!resp.ok || !data?.ok) {
				throw new Error(data?.error || "The photo couldn’t be analyzed. Try again.");
			}
			const sel = data.matched && data.selection ? data.selection : null;
			if (sel) {
				set({
					visit: "appointment",
					priceCheck: true,
					priceCheckMatched: true,
					priceCheckResult: data,
					editReturn: null,
					shareImages: [prepared],
					who: sel.who,
					isKid: false,
					setType: sel.setType,
					service: sel.service,
					length: sel.length,
					shape: sel.shape,
					art: sel.art || [],
					perNail: null,
					perShape: null,
					addons: sel.addons || [],
					tbase: sel.tbase || null,
					tart: sel.tart || [],
					perToe: null,
					perToeBase: null,
					contact: { ...s.contact, notes: buildNotes(sel.shape, s.contact?.notes) },
				});
			} else {
				set({
					priceCheck: true,
					priceCheckMatched: false,
					priceCheckResult: data,
					editReturn: null,
					shareImages: [prepared],
				});
			}
		} catch (err) {
			setError(err.message || "The photo couldn’t be analyzed. Try again.");
		} finally {
			setBusy(false);
			set({ uploadBusy: false });
		}
	};

	const includesNails = s.who === "nails" || s.who === "both";
	const includesToes = s.who === "toes" || s.who === "both";
	const quickServices = useMemo(() => {
		const list = orderedKeys(cfg.content?.order?.service, cfg.base || {}).filter((id) => id !== "repair" && serviceOffered(id, false));
		if (serviceOffered("overlay", false) && !list.includes("overlay")) list.push("overlay");
		if (serviceOffered("gel", false) && !list.includes("gel")) list.push("gel");
		return list;
	}, [cfg]);
	const toeBaseList = useMemo(
		() => orderedKeys(["acrylic", "gel", "bigtoe"], cfg.toesBase || {}).filter((id) => cfg.toesBase?.[id] != null),
		[cfg],
	);

	const pickBaseService = (id) => {
		const tiers = cfg.base?.[id];
		const needsLen = !!(tiers && tiers.flat == null);
		const validLens = needsLen ? orderedKeys(cfg.content?.order?.length, tiers) : [];
		const fallbackLen = result?.selection?.length && validLens.includes(result.selection.length) ? result.selection.length : validLens[0] || null;
		const nextLen = needsLen ? (validLens.includes(s.length) ? s.length : fallbackLen) : null;
		const allowedPrep = PREP_FOR[id] || [];
		set({
			service: id,
			setType: id === "gel" ? "gel" : "acrylic",
			length: nextLen,
			addons: (s.addons || []).filter((a) => allowedPrep.includes(a)),
			...(id !== "gel" ? { isKid: false } : {}),
		});
	};

	const addonsList = (PREP_FOR[s.service] || []).filter((id) => cfg.addon?.[id] != null);
	const toggleAddon = (id) => {
		const cur = s.addons || [];
		const next = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id];
		set({ addons: next });
	};

	const hasQuote = Boolean((result?.matched || (!result && s.priceCheckMatched)) && !busy);
	const items = hasQuote ? priceItems(s) : [];
	const steps = hasQuote ? editSteps(s, items) : [];
	const t = hasQuote ? total(s) : 0;
	const dur = hasQuote ? totalDuration(s) : 0;
	const bypass = !!(sq && sq.bypass);

	const shapeName = typeof s.shape === "string" && cfg.labels?.shape?.[s.shape] ? String(cfg.labels.shape[s.shape]).trim() : "";
	const paidShapeShown = items.some((it) => it.label === "Shape: " + (cfg.labels?.shape?.[s.shape] || ""));
	const showFreeShape = Boolean(
		hasQuote && includesNails && s.service !== "repair" && !Array.isArray(s.perShape) && shapeName && !paidShapeShown,
	);
	const currentArtTier = hasQuote && includesNails && s.service !== "repair" && !Array.isArray(s.perNail) ? artTier(s)?.id : null;
	const showDetectedArt = Boolean(
		result?.matched && result.detectedArt?.length > 0 && result.tier?.id && currentArtTier === result.tier.id,
	);
	const userNotes = String(s.contact?.notes || "").replace(shapeLine, "").trim();
	const editedFromPhoto = Boolean(
		result?.selection &&
			(s.who !== result.selection.who ||
				s.service !== result.selection.service ||
				s.length !== result.selection.length ||
				s.shape !== result.selection.shape ||
				s.tbase !== result.selection.tbase ||
				(s.addons || []).length > 0 ||
				Array.isArray(s.perNail) ||
				(result.tier?.id && currentArtTier && currentArtTier !== result.tier.id)),
	);

	const photoBar = previewUrl ? (
		<div className="pc-photo-bar">
			<img className="pc-thumb" src={previewUrl} alt="Uploaded inspiration photo" />
			<div className="pc-photo-meta">
				<b>
					{busy
						? "Analyzing Photo…"
						: hasQuote
							? editedFromPhoto
								? "Photo Attached · Edited"
								: "Photo Attached"
							: result
								? "Try a Clearer Photo"
								: "Inspiration Photo"}
				</b>
				<label className={"pc-replace" + (busy ? " busy" : "")}>
					<input
						type="file"
						accept="image/*"
						onChange={analyzeFile}
						disabled={busy}
					/>
					<span>{busy ? "Checking…" : "Try Another Photo"}</span>
				</label>
			</div>
		</div>
	) : hasQuote ? (
		<div className="pc-photo-bar pc-photo-bar--empty">
			<span className="upload-ico"><Ico name="image" /></span>
			<div className="pc-photo-meta">
				<b>Re-attach Your Inspo Photo</b>
				<label className={"pc-replace" + (busy ? " busy" : "")}>
					<input
						type="file"
						accept="image/*"
						onChange={analyzeFile}
						disabled={busy}
					/>
					<span>{busy ? "Checking…" : "Choose Photo"}</span>
				</label>
			</div>
		</div>
	) : null;

	return (
		<div className="screen">
			<h1 className="sr-only">Photo Price Check</h1>

			<div className="body">
				{error && <Alert>{error}</Alert>}

				{!previewUrl && !hasQuote && (
					<label className={"upload-box pc-drop" + (busy ? " busy" : "")}>
						<input
							type="file"
							accept="image/*"
							onChange={analyzeFile}
							disabled={busy}
						/>
						<span className="upload-ico">
							<Ico name={busy ? "clock" : "image"} />
						</span>
						<span className="upload-main">{busy ? "Analyzing Photo…" : "Upload an Inspo Photo"}</span>
						<span className="upload-sub">JPG, PNG, or WebP · resized automatically</span>
					</label>
				)}

				{!hasQuote && photoBar}

				{result && !result.matched && !busy && (
					<Alert>{result.reason || "That photo couldn’t be matched. Try a clearer nail photo."}</Alert>
				)}

				{hasQuote && (
					<>
						<div className="receipt pc-receipt">
							<div className="pc-quote-hero">
								<div className="pc-quote-top">
									<span className="pc-quote-lbl">Estimated Total</span>
									{dur > 0 && (
										<span className="rcpt-chip">
											<Ico name="clock" />
											About {humanDuration(dur)}
										</span>
									)}
								</div>
								<div className="pc-quote-main">
									<span className="pc-quote-amt">{money(t)}</span>
									<span className="pc-quote-title">
										{bookingTitle(s)}
										<EditPencil label="Change nails or toes" onClick={() => edit("who")} />
									</span>
								</div>
							</div>
							<ol className="pay-steps pc-pay-steps" aria-label="When you pay">
								<li>
									<span className="ps-when">Today</span>
									<span className="ps-what">{bypass ? "Nothing to Pay" : "Deposit to Hold Your Time"}</span>
									<span className="ps-amt">{money(bypass ? 0 : dueNow(s))}</span>
								</li>
								<li>
									<span className="ps-when">At Your Visit</span>
									<span className="ps-what">{bypass || t - dueNow(s) === 0 ? "Nothing More to Pay" : "Balance"}</span>
									<span className="ps-amt">{money(bypass ? 0 : t - dueNow(s))}</span>
								</li>
							</ol>
							<div className="rcpt-tear" aria-hidden="true" />
							<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 && (
											<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>
								))}
								{showFreeShape && (
									<div className="rcpt-row">
										<dt className="l">Shape: {shapeName}</dt>
										<dd className="r">Included</dd>
										<dd className="ed"><EditPencil label="Change nail shape" onClick={() => edit("design")} /></dd>
									</div>
								)}
								{showDetectedArt && (
									<div className="rcpt-row rcpt-notes">
										<dt className="l">
											<span className="nt-lbl">Detected from Photo</span>
											<span className="nt-text">
												{result.detectedArt.map((a) => a.label).join(" · ")}
											</span>
										</dt>
										{includesNails && <dd className="ed"><EditPencil label="Change nail art" onClick={() => edit("design")} /></dd>}
									</div>
								)}
								{userNotes && (
									<div className="rcpt-row rcpt-notes">
										<dt className="l">
											<span className="nt-lbl">Your Notes</span>
											<span className="nt-text">{userNotes}</span>
										</dt>
										{includesNails && s.service !== "repair" && <dd className="ed"><EditPencil label="Change your notes" onClick={() => edit("design")} /></dd>}
									</div>
								)}
							</dl>
							{items.length > 0 && !s.coupon && <CouponEntry set={set} />}
							{unpricedVisit(s) ? (
								<div className="rcpt-note" role="status">{UNPRICED_VISIT}</div>
							) : (
								<div className="rcpt-note">
									Estimate from your photo. {previewUrl ? "Your photo attaches automatically; final" : "Final"} tier is confirmed at your visit.
								</div>
							)}
						</div>

						{includesNails && quickServices.length > 0 && (
							<section className="block">
								<h3 className="co-section">Base Service <small>Confirm for Your Nails</small></h3>
								<div className="pc-chips" role="radiogroup" aria-label="Base service">
									{quickServices.map((id) => (
										<button
											key={id}
											type="button"
											role="radio"
											aria-checked={s.service === id}
											className={"pc-chip" + (s.service === id ? " sel" : "")}
											onClick={() => pickBaseService(id)}
										>
											{cfg.labels?.service?.[id] || id}
										</button>
									))}
								</div>
								{addonsList.length > 0 && (
									<div className="pc-addons">
										{addonsList.map((id) => {
											const on = (s.addons || []).includes(id);
											return (
												<button
													key={id}
													type="button"
													aria-pressed={on}
													className={"pc-chip pc-chip--addon" + (on ? " sel" : "")}
													onClick={() => toggleAddon(id)}
												>
													<span>{on ? "✓ " : "+ "}{cfg.labels?.addon?.[id] || id}</span>
													<small>{money(cfg.addon[id])}</small>
												</button>
											);
										})}
									</div>
								)}
							</section>
						)}

						{includesToes && toeBaseList.length > 0 && (
							<section className="block">
								<h3 className="co-section">Toe Service <small>Confirm for Your Toes</small></h3>
								<div className="pc-chips" role="radiogroup" aria-label="Toe service">
									{toeBaseList.map((id) => (
										<button
											key={id}
											type="button"
											role="radio"
											aria-checked={s.tbase === id && !Array.isArray(s.perToeBase)}
											className={"pc-chip" + (s.tbase === id && !Array.isArray(s.perToeBase) ? " sel" : "")}
											onClick={() => set({ tbase: id, perToeBase: null })}
										>
											{cfg.labels?.toesBase?.[id] || id}
										</button>
									))}
								</div>
							</section>
						)}

						{photoBar}
					</>
				)}
			</div>
		</div>
	);
}
