---
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 finishOptions = [
	{ id: "silver", label: "Silver", note: "Classic brushed 316L steel" },
	{ id: "black-pvd", label: "Black PVD", note: "Stealth satin hardware" },
	{ id: "rose-gold", label: "Rose Gold", note: "Warm contrast finish" },
];

const pricePerKit = 49.99;
const retailPerKit = 89.99;
const defaultFinish = finishOptions[0];
const apiBaseUrl = process.env.API_BASE_URL || (import.meta.env.PROD ? "" : "http://localhost:8081");
const detailsStorageKey = "royal-pop-checkout-details";
const countryOptions = [
	"Australia",
	"Austria",
	"Belgium",
	"Brazil",
	"Bulgaria",
	"Canada",
	"China",
	"Croatia",
	"Cyprus",
	"Czech Republic",
	"Denmark",
	"Estonia",
	"Finland",
	"France",
	"Germany",
	"Greece",
	"Hong Kong SAR",
	"Hungary",
	"Iceland",
	"India",
	"Indonesia",
	"Ireland",
	"Israel",
	"Italy",
	"Japan",
	"Latvia",
	"Lithuania",
	"Luxembourg",
	"Malaysia",
	"Malta",
	"Mexico",
	"Netherlands",
	"New Zealand",
	"Norway",
	"Philippines",
	"Poland",
	"Portugal",
	"Qatar",
	"Romania",
	"Saudi Arabia",
	"Singapore",
	"Slovakia",
	"Slovenia",
	"South Africa",
	"South Korea",
	"Spain",
	"Sweden",
	"Switzerland",
	"Taiwan",
	"Thailand",
	"Turkey",
	"United Arab Emirates",
	"United Kingdom",
	"United States",
	"Vietnam",
];
---

<BaseLayout
	title="Royal Pop Preorder Details"
	description="Enter your contact and shipping details to continue your Royal Pop preorder."
	noindex={true}
>
	<main class={styles.checkoutPage} data-details-page>
		<header class={styles.topbar}>
			<div class={styles.topbarInner}>
				<a href="/buy" class={styles.backLink} data-back-link>Back to configuration</a>

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

				<p class={styles.helpText}>Contact &amp; delivery details</p>
			</div>
		</header>

		<section class={styles.hero}>
			<div class={styles.heroInner}>
				<div>
					<p class={styles.eyebrow}>Details</p>
					<h1 class={styles.heroTitle}>Add your contact and delivery details.</h1>
					<p class={styles.heroBody}>Add the contact and delivery details for this preorder so everything is ready for the final review.</p>
				</div>

				<div class={styles.heroMeta}>
					<div>
						<strong>What happens here</strong>
						<span>Contact info, shipping address, and any useful notes before you move on.</span>
					</div>
					<div>
						<strong>What we’ll use</strong>
						<span>Your details help keep your preorder, delivery preferences, and follow-up support aligned.</span>
					</div>
					<div>
						<strong>Next step</strong>
						<span>Review configuration, payment method, and submission on the final Review &amp; Pay page.</span>
					</div>
				</div>
			</div>
		</section>

		<section class={styles.checkoutSection}>
			<div class={styles.checkoutGrid}>
				<aside class={styles.summaryRail}>
					<div class={styles.summarySticky}>
						<div class={styles.orderCard}>
							<div class={styles.orderHeader}>
								<div>
									<p class={styles.sectionKicker}>Order summary</p>
									<h2>Your cart</h2>
								</div>
								<p class={styles.priceNow} data-summary-total>£0.00</p>
							</div>

							<div class={styles.cartList} data-cart-items>
								<div class={styles.cartItemEmpty}>Your cart is empty.</div>
							</div>

							<div class={styles.orderRows}>
								<div class={styles.orderRow}>
									<span>Kits in cart</span>
									<strong data-summary-quantity>0 kits</strong>
								</div>
								<div class={styles.orderRow}>
									<span>Early Bird total</span>
									<strong data-summary-total-inline>£0.00</strong>
								</div>
							</div>

						</div>

						<div class={styles.assuranceCard}>
							<h3>What we need from you</h3>
							<ul>
								<li>Primary contact for preorder confirmation and shipping updates</li>
						<li>Delivery address for shipping and customs guidance</li>
						<li>Optional fit or access notes before final review</li>
							</ul>
						</div>
					</div>
				</aside>

				<form class={styles.formColumn} data-details-form>
					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.stepCount}>Step 2A</p>
							<h2>Contact information</h2>
							<p>Where should we send your confirmation, shipping timeline, and install support?</p>
						</div>

						<div class={styles.fieldGrid}>
							<label class={styles.field}>
								<span>Email address</span>
								<input type="email" name="email" autocomplete="email" inputmode="email" placeholder="name@example.com" required data-details-input />
							</label>
							<label class={styles.field}>
								<span>Phone number</span>
								<input type="tel" name="phone" autocomplete="tel" inputmode="tel" placeholder="+44 7XXX XXX XXX" minlength="7" required data-details-input />
							</label>
						</div>
					</section>

					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.stepCount}>Step 2B</p>
							<h2>Shipping address</h2>
							<p>Use your intended final delivery address so rollout logistics can be planned correctly.</p>
						</div>

						<div class={styles.fieldGrid}>
							<label class={styles.field}>
								<span>First name</span>
								<input type="text" name="firstName" autocomplete="shipping given-name" placeholder="First name" minlength="2" required data-details-input />
							</label>
							<label class={styles.field}>
								<span>Last name</span>
								<input type="text" name="lastName" autocomplete="shipping family-name" placeholder="Last name" minlength="2" required data-details-input />
							</label>
							<label class={styles.field + " " + styles.fieldFull}>
								<span>Street address</span>
								<input type="text" name="addressLine1" autocomplete="shipping address-line1" placeholder="Street address" minlength="5" required data-details-input />
							</label>
							<label class={styles.field + " " + styles.fieldFull}>
								<span>Apartment, suite, etc. <em>(optional)</em></span>
								<input type="text" name="addressLine2" autocomplete="shipping address-line2" placeholder="Apartment, suite, unit, building, etc." data-details-input />
							</label>
							<label class={styles.field}>
								<span>City</span>
								<input type="text" name="city" autocomplete="shipping address-level2" placeholder="City" minlength="2" required data-details-input />
							</label>
							<label class={styles.field}>
								<span>State / county / region</span>
								<input type="text" name="region" autocomplete="shipping address-level1" placeholder="State, county, or region" minlength="2" required data-details-input />
							</label>
							<label class={styles.field}>
								<span>Postal code</span>
								<input type="text" name="postalCode" autocomplete="shipping postal-code" inputmode="text" placeholder="Postal code" minlength="3" required data-details-input />
							</label>
							<label class={styles.field}>
								<span>Country</span>
								<select name="country" autocomplete="shipping country-name" required data-details-input>
									<option value="" selected disabled>Select your country</option>
									{countryOptions.map((country) => (
										<option value={country}>{country}</option>
									))}
								</select>
							</label>
						</div>
					</section>

					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.stepCount}>Step 2C</p>
							<h2>Delivery notes</h2>
							<p>Add anything helpful for shipping, fit questions, or handoff notes before you continue.</p>
						</div>

						<div class={styles.stack}>
							<div class={styles.optionCard}>
							<div>
								<strong>Dispatch preference</strong>
								<span>Tracked worldwide shipping, with pre-orders expected to ship in around 1 month.</span>
							</div>
								<p>Standard</p>
							</div>

							<label class={styles.field + " " + styles.fieldFull}>
								<span>Special notes</span>
								<textarea name="notes" rows="4" placeholder="Gate code, delivery notes, wrist-fit question, etc." data-details-input></textarea>
							</label>
						</div>
					</section>

					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.stepCount}>Next</p>
							<h2>Continue to review &amp; pay</h2>
							<p>From here you’ll review your configuration, choose payment, and send your preorder request.</p>
						</div>

						<div class={styles.actions}>
							<a href="/buy" class={styles.secondaryCta}>Edit configuration</a>
							<button type="submit" class={styles.primaryCta} data-go-review>Continue to review &amp; pay</button>
						</div>

						<p class={styles.footnote}>Please double-check your email and delivery address before continuing.</p>
					</section>
				</form>
			</div>
		</section>

		<SiteFooter />

		<script is:inline src="/scripts/royal-pop-cart.js"></script>
		<script define:vars={{ colorways, finishOptions, pricePerKit, retailPerKit, apiBaseUrl, detailsStorageKey, cartItemClass: styles.cartItem, cartItemImageWrapClass: styles.cartItemImageWrap, cartItemBodyClass: styles.cartItemBody, cartItemTitleClass: styles.cartItemTitle, cartItemSubtitleClass: styles.cartItemSubtitle, cartItemMetaClass: styles.cartItemMeta, cartItemFooterClass: styles.cartItemFooter, cartItemPriceClass: styles.cartItemPrice, cartItemRemoveClass: styles.cartItemRemove, cartItemEmptyClass: styles.cartItemEmpty }}>
			const { loadCart, removeCartItem } = window.RoyalPopCart || {};
			const normalizedApiBaseUrl = String(apiBaseUrl || "").replace(/\/$/, "");
			const formatGBP = (value) => `£${Number(value || 0).toFixed(2)}`;

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

				root.dataset.initialized = "true";
				if (!loadCart || !removeCartItem) return;

				const colorwayMap = new Map(colorways.map((colorway) => [colorway.id, colorway]));
				const finishMap = new Map(finishOptions.map((finish) => [finish.id, finish]));

				const summaryQuantity = root.querySelector("[data-summary-quantity]");
				const summaryTotal = root.querySelector("[data-summary-total]");
				const summaryTotalInline = root.querySelector("[data-summary-total-inline]");
				const cartItemsNode = root.querySelector("[data-cart-items]");
				const backLink = root.querySelector("[data-back-link]");
				const detailsForm = root.querySelector("[data-details-form]");
				const reviewLink = root.querySelector("[data-go-review]");
				const detailsFields = Array.from(root.querySelectorAll("[data-details-input]"));
				let currentPricePerKit = Number(pricePerKit || 0);
				let currentRetailPerKit = Number(retailPerKit || 0);

				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.
					} finally {
						renderCart();
					}
				};

				const redirectToBuy = () => {
					window.location.replace("/buy");
				};

				const loadStoredDetails = () => {
					try {
						return JSON.parse(window.sessionStorage.getItem(detailsStorageKey) || "null");
					} catch {
						return null;
					}
				};

				const saveDetails = () => {
					if (!detailsForm) return;

					const formData = new FormData(detailsForm);
					const payload = Object.fromEntries(formData.entries());
					window.sessionStorage.setItem(detailsStorageKey, JSON.stringify(payload));
				};

				const prefillDetails = () => {
					const stored = loadStoredDetails();
					if (!stored) return;

					detailsFields.forEach((field) => {
						const key = field.getAttribute("name");
						if (!key) return;
						const value = stored[key];
						if (typeof value !== "string") return;
						field.value = value;
					});
				};

				const renderCart = () => {
					const rawCart = loadCart();

					if (rawCart.length === 0) {
						redirectToBuy();
						return;
					}

					const cartItems = rawCart.map((item) => ({
						...item,
						quantity: Math.max(1, Number(item.quantity || 1)),
						colorway: colorwayMap.get(item.colorwayId) || defaultColorway,
						finish: finishMap.get(item.finishId) || defaultFinish,
					}));
					const totalQuantity = cartItems.reduce((sum, item) => sum + item.quantity, 0);
					const total = currentPricePerKit * totalQuantity;
					if (summaryQuantity) summaryQuantity.textContent = `${totalQuantity} ${totalQuantity === 1 ? "kit" : "kits"}`;
					if (summaryTotal) summaryTotal.textContent = formatGBP(total);
					if (summaryTotalInline) summaryTotalInline.textContent = formatGBP(total);

					if (reviewLink) {
						const disabled = totalQuantity === 0;
						reviewLink.setAttribute("aria-disabled", String(disabled));
						reviewLink.disabled = disabled;
					}

					if (!cartItemsNode) return;

					if (cartItems.length === 0) {
						cartItemsNode.innerHTML = `<div class="${cartItemEmptyClass}">Your cart is empty. Go back to configuration to add a kit.</div>`;
						return;
					}

					cartItemsNode.innerHTML = cartItems
						.map(
							(item) => `
								<article class="${cartItemClass}">
									<div class="${cartItemImageWrapClass}" style="background:${item.colorway.previewBackground}">
										<img src="${item.colorway.cardImage}" alt="${item.colorway.name} kit preview" />
									</div>
									<div class="${cartItemBodyClass}">
										<div>
											<strong class="${cartItemTitleClass}">${item.colorway.name}</strong>
											<p class="${cartItemSubtitleClass}">${item.colorway.subtitle}</p>
											<p class="${cartItemMetaClass}">${item.colorway.styleText}</p>
											<p class="${cartItemMetaClass}">${item.quantity} ${item.quantity === 1 ? "kit" : "kits"} · Matched configuration</p>
										</div>
										<div class="${cartItemFooterClass}">
										<strong class="${cartItemPriceClass}">${formatGBP(currentPricePerKit * item.quantity)}</strong>
											<button type="button" class="${cartItemRemoveClass}" data-remove-cart-item="${item.id}">Remove</button>
										</div>
									</div>
								</article>`,
						)
						.join("");
				};

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

				if (cartItemsNode) {
					cartItemsNode.addEventListener("click", (event) => {
						const button = event.target.closest("[data-remove-cart-item]");
						if (!button) return;

						const { removeCartItem: itemId } = button.dataset;
						if (!itemId) return;

						removeCartItem(itemId);
						renderCart();
					});
				}

				if (detailsForm) {
					detailsForm.addEventListener("submit", (event) => {
						event.preventDefault();

						if (!detailsForm.reportValidity()) {
							return;
						}

						saveDetails();
						window.location.assign("/checkout");
					});
				}

				prefillDetails();
				renderCart();
				loadPricing();
			};

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