---
import SiteFooter from "../components/royal-pop/SiteFooter.astro";
import { colorways, defaultColorway } from "../data/royalPop";
import BaseLayout from "../layouts/BaseLayout.astro";
import styles from "./checkout.module.scss";

const pricePerKit = 49.99;
const retailPerKit = 89.99;
const apiBaseUrl = process.env.API_BASE_URL || (import.meta.env.PROD ? "" : "http://localhost:8081");
---

<BaseLayout
	title="Royal Pop Thank You"
	description="Your Royal Pop preorder request has been received."
	noindex={true}
>
	<main class={styles.checkoutPage} data-thank-you-page>
		<header class={styles.topbar}>
			<div class={styles.topbarInner}>
				<a href="/checkout" class={styles.backLink} data-back-link>Back to review &amp; pay</a>

				<div class={styles.progress} aria-label="Purchase steps">
					<span>1. Configure</span>
					<span>2. Details</span>
					<span class={styles.progressActive}>3. Review &amp; Pay</span>
				</div>

				<p class={styles.helpText}>Request received</p>
			</div>
		</header>

		<section class={styles.hero}>
			<div class={styles.heroInner}>
				<div>
					<p class={styles.eyebrow}>Thank you</p>
					<h1 class={styles.heroTitle} data-thank-you-title>Your Royal Pop preorder request is in.</h1>
					<p class={styles.heroBody} data-thank-you-body>Your preorder summary and reference number are below so you can review the order exactly as submitted.</p>
				</div>

				<div class={styles.heroMeta}>
					<div>
						<strong data-thank-you-meta-label="confirmation">Confirmation ready</strong>
						<span data-thank-you-meta-copy="confirmation">Your selected kit and request details are collected here in one place.</span>
					</div>
					<div>
						<strong data-thank-you-meta-label="next">What comes next</strong>
						<span data-thank-you-meta-copy="next">We’ll use this saved order record for payment confirmation, fulfilment updates, and future support.</span>
					</div>
					<div>
						<strong data-thank-you-meta-label="reference">Reference ready</strong>
						<span data-thank-you-meta-copy="reference">Keep this page handy if you need to double-check your selected build.</span>
					</div>
				</div>
			</div>
		</section>

		<section class={styles.checkoutSection}>
			<div class={styles.checkoutGrid}>
				<aside class={styles.summaryRail}>
					<div class={styles.summarySticky}>
						<div class={styles.previewCard}>
							<p class={styles.sectionKicker}>Confirmed configuration</p>
							<div class={styles.previewFrame}>
								<img
									data-summary-image
									src={defaultColorway.previewImage}
									alt={`${defaultColorway.name} Royal Pop configuration preview`}
								/>
							</div>

							<div class={styles.previewCopy}>
								<p class={styles.previewTitle} data-summary-name>{defaultColorway.name}</p>
								<p class={styles.previewSubtitle} data-summary-subtitle>{defaultColorway.subtitle}</p>
								<p class={styles.previewSpec} data-summary-style>{defaultColorway.styleText}</p>
								<p class={styles.previewSpec} data-summary-crown>{defaultColorway.crownSpec}</p>
							</div>
						</div>

						<div class={styles.orderCard}>
							<div class={styles.orderHeader}>
								<div>
									<p class={styles.sectionKicker}>Request summary</p>
									<h2>Royal Pop cart</h2>
								</div>
								<p class={styles.priceNow} data-summary-total>£49.99</p>
							</div>

							<div class={styles.orderRows} data-cart-items>
								<div class={styles.orderRow}>
									<span>Reference</span>
									<strong data-order-reference>RP-BSI-SPMC-01</strong>
								</div>
								<div class={styles.orderRow}>
									<span>Quantity</span>
									<strong data-summary-quantity>1 kit</strong>
								</div>
								<div class={styles.orderRow}>
									<span>Early Bird total</span>
								<strong data-summary-total-inline>£49.99</strong>
								</div>
							</div>

						</div>

						<div class={styles.assuranceCard}>
							<h3>What happens next</h3>
						<ul>
						<li>Your request summary stays attached to this reference.</li>
						<li>Zero-stock configurations remain open as preorder requests while the next batch is prepared.</li>
						<li>Install guidance and fit support can follow after confirmation.</li>
						</ul>
						</div>
					</div>
				</aside>

				<div class={styles.formColumn}>
					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.stepCount}>Confirmation</p>
							<h2>Thank you for your preorder request.</h2>
							<p>Your request has been received. Use this page as your final summary for the preorder you just sent through.</p>
						</div>

					<div class={styles.statusCard}>
						<p class={styles.statusPill} data-status-pill>Confirmation</p>
						<h3 class={styles.statusTitle} data-status-title>Royal Pop request received</h3>
						<p class={styles.statusBody} data-status-body>We’ve saved your selected build and quantity so you can review the order exactly as submitted.</p>
						<div class={styles.inlineMeta}>
							<div>
								<span>Reference</span>
									<strong data-order-reference>RP-BSI-SPMC-01</strong>
							</div>
							<div>
								<span>Status</span>
								<strong data-order-status>Request received</strong>
							</div>
						</div>
						</div>
					</section>

				</div>
			</div>
		</section>

		<SiteFooter />

		<script is:inline src="/scripts/royal-pop-cart.js"></script>
		<script define:vars={{ colorways, pricePerKit, retailPerKit, apiBaseUrl, orderRowClass: styles.orderRow, cartLineClass: styles.cartLine, cartLineMetaClass: styles.cartLineMeta }}>
			const { clearCart, getEffectiveCart, groupCartItems } = window.RoyalPopCart || {};
			const normalizedApiBaseUrl = String(apiBaseUrl || "").replace(/\/$/, "");
			const formatGBP = (value) => `£${Number(value || 0).toFixed(2)}`;

			const initThankYouPage = () => {
				const root = document.querySelector("[data-thank-you-page]");
				if (!root || root.dataset.initialized === "true") return;

				root.dataset.initialized = "true";
				if (!clearCart || !getEffectiveCart || !groupCartItems) return;
				let currentPricePerKit = Number(pricePerKit || 0);
				let currentRetailPerKit = Number(retailPerKit || 0);

				const colorwayMap = new Map(colorways.map((colorway) => [colorway.id, colorway]));
				const summaryImage = root.querySelector("[data-summary-image]");
				const summaryName = root.querySelector("[data-summary-name]");
				const summarySubtitle = root.querySelector("[data-summary-subtitle]");
				const summaryStyle = root.querySelector("[data-summary-style]");
				const summaryCrown = root.querySelector("[data-summary-crown]");
				const summaryQuantity = root.querySelector("[data-summary-quantity]");
				const summaryTotal = root.querySelector("[data-summary-total]");
				const summaryTotalInline = root.querySelector("[data-summary-total-inline]");
				const referenceNodes = Array.from(root.querySelectorAll("[data-order-reference]"));
				const orderStatusNode = root.querySelector("[data-order-status]");
				const cartItemsNode = root.querySelector("[data-cart-items]");
				const backLink = root.querySelector("[data-back-link]");
				const thankYouTitle = root.querySelector("[data-thank-you-title]");
				const thankYouBody = root.querySelector("[data-thank-you-body]");
				const statusPill = root.querySelector("[data-status-pill]");
				const statusTitle = root.querySelector("[data-status-title]");
				const statusBody = root.querySelector("[data-status-body]");
				const metaLabels = {
					confirmation: root.querySelector('[data-thank-you-meta-label="confirmation"]'),
					next: root.querySelector('[data-thank-you-meta-label="next"]'),
					reference: root.querySelector('[data-thank-you-meta-label="reference"]'),
				};
				const metaCopies = {
					confirmation: root.querySelector('[data-thank-you-meta-copy="confirmation"]'),
					next: root.querySelector('[data-thank-you-meta-copy="next"]'),
					reference: root.querySelector('[data-thank-you-meta-copy="reference"]'),
				};

				const loadPricing = async () => {
					try {
						const response = await fetch(`${normalizedApiBaseUrl}/v1/storefront/pricing`);
						const payload = await response.json().catch(() => null);
						if (!response.ok) {
							throw new Error(payload?.error?.message || "Pricing is temporarily unavailable.");
						}

						const pricing = payload?.data || {};
						const nextUnit = Number(pricing.unitAmount || 0) / 100;
						const nextRetail = Number(pricing.retailAmount || 0) / 100;

						if (nextUnit > 0) currentPricePerKit = nextUnit;
						if (nextRetail > 0) currentRetailPerKit = nextRetail;
					} catch (_error) {
						// Keep baked fallback pricing when the public pricing endpoint is unavailable.
					}
				};

				const applyStatusContent = (orderStatus, message) => {
					if (orderStatus === "paid") {
						if (thankYouTitle) thankYouTitle.textContent = "Your Royal Pop preorder is confirmed.";
						if (thankYouBody) thankYouBody.textContent = "Your payment has been verified and your confirmed order summary is shown below.";
						if (statusPill) statusPill.textContent = "Payment confirmed";
						if (statusTitle) statusTitle.textContent = "Royal Pop preorder confirmed";
						if (statusBody) statusBody.textContent = message || "Stripe confirmed your payment and the backend order record has been updated.";
						if (metaLabels.confirmation) metaLabels.confirmation.textContent = "Payment verified";
						if (metaCopies.confirmation) metaCopies.confirmation.textContent = "Your backend order record and payment status now match.";
						if (metaLabels.next) metaLabels.next.textContent = "What happens next";
						if (metaCopies.next) metaCopies.next.textContent = "We can now use this verified order record for fulfilment, updates, and support.";
						if (metaLabels.reference) metaLabels.reference.textContent = "Order reference";
						if (metaCopies.reference) metaCopies.reference.textContent = "Keep this confirmed backend order reference handy for future support.";
						return;
					}

					if (orderStatus === "processing") {
						if (statusPill) statusPill.textContent = "Processing";
						if (statusTitle) statusTitle.textContent = "Your payment is still processing";
						if (statusBody) statusBody.textContent = message || "Stripe is still processing your payment. Refresh this page shortly for the latest update.";
						return;
					}

					if (orderStatus === "failed" || orderStatus === "canceled") {
						if (statusPill) statusPill.textContent = "Needs attention";
						if (statusTitle) statusTitle.textContent = "Your payment was not completed";
						if (statusBody) statusBody.textContent = message || "Stripe did not complete the payment. Return to checkout to try again.";
						return;
					}

					if (statusPill) statusPill.textContent = "Confirmation";
					if (statusTitle) statusTitle.textContent = "Royal Pop request received";
					if (statusBody) statusBody.textContent = message || "Your order record has been saved and is waiting for final Stripe confirmation.";
				};

				const renderFromBackendOrder = (payload) => {
					const order = payload?.order;
					if (!order) return false;

					const orderItems = Array.isArray(order.items) ? order.items : [];
					const mappedItems = orderItems.map((item) => ({
						...item,
						quantity: Number(item.quantity || 0),
						unitAmount: Number(item.unitAmount || 0),
						colorway: colorwayMap.get(item.colorwayId) || defaultColorway,
					}));
					const primaryItem = mappedItems[0] || { colorway: defaultColorway, quantity: 1, unitAmount: Math.round(currentPricePerKit * 100) };
					const totalQuantity = mappedItems.reduce((sum, item) => sum + item.quantity, 0) || 1;
					const total = Number(order.amount || 0) / 100;

					if (summaryImage) {
						summaryImage.setAttribute("src", primaryItem.colorway.previewImage);
						summaryImage.setAttribute("alt", `${primaryItem.colorway.name} Royal Pop configuration preview`);
					}
					if (summaryName) summaryName.textContent = mappedItems.map((item) => item.colorway.name).join(" + ") || primaryItem.colorway.name;
					if (summarySubtitle) summarySubtitle.textContent = `${totalQuantity} ${totalQuantity === 1 ? "kit" : "kits"} confirmed`;
					if (summaryStyle) summaryStyle.textContent = mappedItems.length > 1 ? "Mixed configurations" : primaryItem.colorway.styleText;
					if (summaryCrown) summaryCrown.textContent = mappedItems.length > 1 ? "Multiple selections confirmed under one order." : primaryItem.colorway.crownSpec;
					if (summaryQuantity) summaryQuantity.textContent = `${totalQuantity} ${totalQuantity === 1 ? "kit" : "kits"}`;
					if (summaryTotal) summaryTotal.textContent = formatGBP(total);
					if (summaryTotalInline) summaryTotalInline.textContent = formatGBP(total);
					if (orderStatusNode) orderStatusNode.textContent = order.status || payload.orderStatus || "Received";

					const reference = order.id || payload.orderId || "—";
					referenceNodes.forEach((node) => {
						node.textContent = reference;
					});

					if (cartItemsNode) {
						cartItemsNode.innerHTML = `
							<div class="${orderRowClass}">
								<span>Reference</span>
								<strong>${reference}</strong>
							</div>
							${mappedItems.map((item) => `
								<div class="${orderRowClass}">
									<div class="${cartLineClass}">
										<span>${item.colorway.name}</span>
										<small class="${cartLineMetaClass}">${item.colorway.styleText} · ${item.quantity} ${item.quantity === 1 ? "kit" : "kits"}</small>
									</div>
									<strong>${formatGBP((item.unitAmount * item.quantity) / 100)}</strong>
								</div>`).join("")}
							<div class="${orderRowClass}">
								<span>Confirmed total</span>
								<strong>${formatGBP(total)}</strong>
							</div>`;
					}

					applyStatusContent(order.status || payload.orderStatus, payload.message || order.webhookMessage);
					clearCart();
					return true;
				};

				const renderFromCartFallback = () => {
					const cartItems = getEffectiveCart();
					const groupedItems = groupCartItems(cartItems)
						.map((item) => ({ ...item, colorway: colorwayMap.get(item.colorwayId) || defaultColorway }))
						.filter(Boolean);
					const primaryItem = groupedItems[0] || { quantity: 1, colorway: defaultColorway };
					const totalQuantity = groupedItems.reduce((sum, item) => sum + Number(item.quantity || 0), 0) || primaryItem.quantity || 1;
					const total = currentPricePerKit * totalQuantity;
					const colorCode = groupedItems.map((item) => item.colorway.name.slice(0, 2).toUpperCase()).join("").slice(0, 4) || primaryItem.colorway.name.slice(0, 2).toUpperCase();
					const quantityCode = String(totalQuantity).padStart(2, "0");
					const reference = `RP-${quantityCode}-${colorCode}`;

					if (summaryImage) {
						summaryImage.setAttribute("src", primaryItem.colorway.previewImage);
						summaryImage.setAttribute("alt", `${primaryItem.colorway.name} Royal Pop configuration preview`);
					}
					if (summaryName) summaryName.textContent = groupedItems.map((item) => item.colorway.name).join(" + ") || primaryItem.colorway.name;
					if (summarySubtitle) summarySubtitle.textContent = `${totalQuantity} ${totalQuantity === 1 ? "kit" : "kits"} confirmed`;
					if (summaryStyle) summaryStyle.textContent = groupedItems.length > 1 ? "Mixed configurations" : primaryItem.colorway.styleText;
					if (summaryCrown) summaryCrown.textContent = groupedItems.length > 1 ? "Two selected kits saved under one request." : primaryItem.colorway.crownSpec;
					if (summaryQuantity) summaryQuantity.textContent = `${totalQuantity} ${totalQuantity === 1 ? "kit" : "kits"}`;
					if (summaryTotal) summaryTotal.textContent = formatGBP(total);
					if (summaryTotalInline) summaryTotalInline.textContent = formatGBP(total);
					referenceNodes.forEach((node) => {
						node.textContent = reference;
					});
					if (cartItemsNode) {
						cartItemsNode.innerHTML = `
							<div class="${orderRowClass}">
								<span>Reference</span>
								<strong>${reference}</strong>
							</div>
							${groupedItems.map((item) => `
								<div class="${orderRowClass}">
									<div class="${cartLineClass}">
										<span>${item.colorway.name}</span>
										<small class="${cartLineMetaClass}">${item.colorway.styleText} · ${item.quantity} ${item.quantity === 1 ? "kit" : "kits"}</small>
									</div>
								<strong>${formatGBP(item.quantity * currentPricePerKit)}</strong>
								</div>`).join("")}
							<div class="${orderRowClass}">
								<span>Early Bird total</span>
								<strong>${formatGBP(total)}</strong>
							</div>`;
					}
				};

				const loadVerifiedOrder = async () => {
					const paymentIntentID = new URLSearchParams(window.location.search).get("payment_intent");
					if (!paymentIntentID) {
						renderFromCartFallback();
						return;
					}

					try {
						const response = await fetch(`${normalizedApiBaseUrl}/v1/checkout/payment-intent/${encodeURIComponent(paymentIntentID)}`);
						const payload = await response.json().catch(() => ({}));
						if (!response.ok || !payload?.data || !renderFromBackendOrder(payload.data)) {
							throw new Error(payload?.error?.message || "We could not load your confirmed order details.");
						}
					} catch (error) {
						renderFromCartFallback();
						applyStatusContent("pending", error instanceof Error ? error.message : "We could not load your confirmed order details.");
					}
				};

				if (backLink) backLink.setAttribute("href", "/checkout");

				loadPricing().finally(loadVerifiedOrder);
			};

			initThankYouPage();
			document.addEventListener("astro:page-load", initThankYouPage);
		</script>
	</main>
</BaseLayout>
