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

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

const styleOptions = [
	{
		id: "A",
		label: "Style A",
		title: "12 o'clock crown",
		description: "Pocket-watch inspired orientation with the crown centered at the top.",
	},
	{
		id: "B",
		label: "Style B",
		title: "3 o'clock crown",
		description: "Sport-watch ergonomics with direct access to the crown on the right side.",
	},
];

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 defaultFinish = finishOptions[0];
const pricePerKit = 49.99;
const retailPerKit = 89.99;
const siteUrl = "https://royal-pop-accessory.com";
const primaryImage = `${siteUrl}/images/png/pure-white.png`;

const structuredData = {
	"@context": "https://schema.org",
	"@type": "Product",
	name: "Royal Pop Accessory",
	description:
		"Royal Pop Accessory is a bold interchangeable watch strap accessory offered in standout colourways with multiple finish options and preorder configuration.",
	brand: {
		"@type": "Brand",
		name: "Royal Pop Accessory",
	},
	image: [primaryImage],
	url: `${siteUrl}/buy`,
	category: "Watch Accessories",
	material: "Bioceramic case, silicone strap, 316L steel hardware",
	additionalProperty: [
		{
			"@type": "PropertyValue",
			name: "Available colourways",
			value: `${colorways.length}`,
		},
		{
			"@type": "PropertyValue",
			name: "Available finishes",
			value: `${finishOptions.length}`,
		},
		{
			"@type": "PropertyValue",
			name: "Water resistance",
			value: "50m",
		},
	],
	offers: {
		"@type": "Offer",
		url: `${siteUrl}/buy`,
		priceCurrency: "GBP",
		price: pricePerKit.toFixed(2),
		availability: "https://schema.org/PreOrder",
		itemCondition: "https://schema.org/NewCondition",
	},
};
---

<BaseLayout
	title="Pre-Order Royal Pop Accessory"
	description="Configure your Royal Pop Accessory preorder, choose your preferred colourway and finish, and reserve your build before public release."
	structuredData={structuredData}
>
	<main class={styles.buyPage} data-buy-page>
		<header class={styles.topbar}>
			<div class={styles.topbarInner}>
				<a href="/" class={styles.backLink}>Royal Pop</a>

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

				<p class={styles.helpText}>Pre-order concierge available · Ships in around 1 month</p>
			</div>
		</header>

		<section class={styles.hero}>
			<div class={styles.heroInner}>
				<div>
					<p class={styles.eyebrow}>Royal Pop preorder</p>
					<h1 class={styles.heroTitle}>Choose your Royal Pop wrist conversion kit.</h1>
				</div>

				<div class={styles.heroMeta}>
					<div>
						<strong>Early Bird</strong>
						<span data-hero-price>£49.99 before public release</span>
					</div>
					<div>
						<strong>Colorways</strong>
						<span>8 matched Royal Pop references</span>
					</div>
					<div>
						<strong>Included</strong>
						<span>Bioceramic case · 50m water resistant · silicone strap</span>
					</div>
				</div>
			</div>
		</section>

		<section class={styles.configSection}>
			<div class={styles.configGrid}>
				<aside class={styles.summaryRail}>
					<div class={styles.summarySticky}>
						<div class={styles.previewCard}>
							<p class={styles.sectionKicker}>Your 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}>Order summary</p>
								<h2>Cart summary</h2>
							</div>
							<p class={styles.priceNow} data-summary-cart-total>£0.00</p>
						</div>

						<div class={styles.orderRows}>
							<div class={styles.orderRow}>
								<span>Unit price</span>
								<strong data-summary-unit-price>£49.99 per kit</strong>
							</div>
							<div class={styles.orderRow}>
								<span>Current build</span>
								<strong><span data-summary-colorway>{defaultColorway.name}</span></strong>
							</div>
							<div class={styles.orderRow}>
								<span>Selected quantity</span>
								<strong data-summary-quantity>1 kit</strong>
							</div>
							<div class={styles.orderRow}>
								<span>This selection</span>
								<strong data-summary-selection-total>£49.99</strong>
							</div>
							<div class={styles.orderRow}>
								<span>Cart total</span>
								<strong data-summary-cart-total>£0.00</strong>
							</div>
						</div>

					<div class={styles.cartStatusRow}>
						<div class={styles.cartStatusCopy}>
							<span data-cart-status>Cart empty · add your first configuration</span>
							<strong data-cart-count>0 kits</strong>
						</div>
						<button type="button" class={styles.cartUtilityButton} data-clear-cart disabled>Clear cart</button>
					</div>

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

					<div class={styles.summaryActions}>
						<button type="button" class={styles.primaryCta} data-add-to-cart>Add to cart</button>
						<button type="button" class={styles.secondaryCta} data-go-details>Buy now</button>
					</div>
					<p class={styles.orderFine} data-cart-feedback data-cart-feedback-state="info">Build your cart first, then continue to details.</p>
				</div>
			</div>
		</aside>

				<div class={styles.builderColumn}>
					<section class={styles.stepSection} data-step-section="1">
						<div class={styles.stepHeader}>
							<p class={styles.stepCount}>Step 1</p>
							<h2>Choose your crown layout.</h2>
							<p>Pick the wearing orientation first. Available colours update automatically.</p>
						</div>

						<div class={styles.choiceGrid}>
							{styleOptions.map((option) => (
								<button
									type="button"
									class={styles.choiceCard}
									data-style-option
									data-style-id={option.id}
									aria-pressed={String(option.id === defaultColorway.style)}
								>
									<p class={styles.choiceEyebrow}>{option.label}</p>
									<strong>{option.title}</strong>
									<span>{option.description}</span>
								</button>
							))}
						</div>
					</section>

					<section class={styles.stepSection} data-step-section="2">
						<div class={styles.stepHeader}>
							<p class={styles.stepCount}>Step 2</p>
							<h2>Pick a colourway.</h2>
						<p>Each kit is matched to a specific Royal Pop reference with live availability and preorder status shown below.</p>
						</div>

						<div class={styles.colorGrid}>
							{colorways.map((colorway) => (
								<button
									type="button"
									class={styles.colorCard}
									data-colorway-option
									data-colorway-id={colorway.id}
									data-style-id={colorway.style}
									data-colorway-name={colorway.name}
									data-colorway-subtitle={colorway.subtitle}
									data-colorway-style={colorway.styleText}
									data-colorway-crown={colorway.crownSpec}
									data-colorway-image={colorway.previewImage}
									data-colorway-card-image={colorway.cardImage}
									data-colorway-background={colorway.previewBackground}
									aria-pressed={String(colorway.id === defaultColorway.id)}
								>
									<div class={styles.colorImageWrap} style={`background:${colorway.previewBackground}`}>
										<img src={colorway.cardImage} alt={`${colorway.name} product card`} loading="lazy" />
									</div>
									<div class={styles.colorCopy}>
										<div class={styles.colorSwatchRow}>
											<span class={styles.colorSwatch} style={`background:${colorway.swatchColor}`}></span>
											<p>{colorway.name}</p>
										</div>
										<strong>{colorway.subtitle}</strong>
										<span>{colorway.styleText}</span>
										<p class={styles.availabilityLine}>
											<span
												class={styles.availabilityBadge}
												data-availability-badge
												data-style-id={colorway.style}
												data-colorway-id={colorway.id}
												data-finish-id={defaultFinish.id}
												data-state="default"
											>
												Checking availability…
											</span>
										</p>
									</div>
								</button>
							))}
						</div>
					</section>

					<section class={styles.stepSection} data-step-section="3">
						<div class={styles.stepHeader}>
							<p class={styles.stepCount}>Step 3</p>
							<h2>Confirm quantity.</h2>
						</div>

					<div class={styles.quantityRow}>
						<label class={styles.quantityField}>
							<span>Quantity</span>
							<input type="number" min="1" step="1" value="1" inputmode="numeric" data-quantity-input />
						</label>
					</div>

						<div class={styles.notesPanel}>
							<div>
								<strong>Shipping window</strong>
								<span>Pre-orders are expected to ship in around 1 month, dispatched in allocation order.</span>
							</div>
							<div>
								<strong>Returns</strong>
								<span>30-day returns after delivery, unused kits only.</span>
							</div>
							<div>
								<strong>Support</strong>
								<span>Dedicated install and fitting support after purchase.</span>
							</div>
						</div>

					<div class:list={[styles.summaryActions, styles.bottomCheckoutCta]}>
						<button type="button" class={styles.primaryCta} data-add-to-cart>Add to cart</button>
						<button type="button" class={styles.secondaryCta} data-checkout-cta data-go-details>Buy now</button>
					</div>
				</section>
			</div>
		</div>

			<div class={styles.supportRow}>
				<div class={styles.assuranceCard}>
					<h3>What ships in the box</h3>
						<ul>
							<li>Bioceramic Royal Pop conversion shell</li>
							<li>Matched silicone strap set</li>
							<li>Matched Royal Pop colourway configuration</li>
							<li>Fit guide and installation card</li>
						</ul>
				</div>
			</div>
		</section>

		<div class={styles.cartToast} data-cart-toast hidden>
			<strong data-cart-toast-title>Added to cart</strong>
			<span data-cart-toast-body>Your kit is ready in the cart.</span>
		</div>

		<SiteFooter />

		<script is:inline src="/scripts/royal-pop-cart.js"></script>
		<script define:vars={{
			apiBaseUrl,
			colorways,
			finishOptions,
			pricePerKit,
			retailPerKit,
			cartItemClass: styles.cartItem,
			cartItemImageWrapClass: styles.cartItemImageWrap,
			cartItemBodyClass: styles.cartItemBody,
			cartItemTopClass: styles.cartItemTop,
			cartItemTitleClass: styles.cartItemTitle,
			cartItemSubtitleClass: styles.cartItemSubtitle,
			cartItemMetaClass: styles.cartItemMeta,
			cartItemFooterClass: styles.cartItemFooter,
			cartItemPriceClass: styles.cartItemPrice,
			cartItemRemoveClass: styles.cartItemRemove,
			cartItemEmptyClass: styles.cartItemEmpty,
		}}>
			const normalizedApiBaseUrl = String(apiBaseUrl || "").replace(/\/$/, "");
			const {
				addSelectionToCart,
				clearCart,
				getCartCount,
				loadBuilderSelection,
				loadCart,
				removeCartItem,
				saveBuilderSelection,
			} = window.RoyalPopCart || {};

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

				root.dataset.initialized = "true";

				const styleButtons = Array.from(root.querySelectorAll("[data-style-option]"));
				const colorButtons = Array.from(root.querySelectorAll("[data-colorway-option]"));
				const availabilityBadges = Array.from(root.querySelectorAll("[data-availability-badge]"));
				const finishButtons = Array.from(root.querySelectorAll("[data-finish-option]"));
				const quantityInput = root.querySelector("[data-quantity-input]");
				const detailsButtons = Array.from(root.querySelectorAll("[data-go-details]"));
				const addToCartButtons = Array.from(root.querySelectorAll("[data-add-to-cart]"));
				const clearCartButtons = Array.from(root.querySelectorAll("[data-clear-cart]"));
				const cartStatusNodes = Array.from(root.querySelectorAll("[data-cart-status]"));
				const cartCountNodes = Array.from(root.querySelectorAll("[data-cart-count]"));
				const cartFeedbackNodes = Array.from(root.querySelectorAll("[data-cart-feedback]"));
				const cartItemsNode = root.querySelector("[data-cart-items]");
				const cartToast = root.querySelector("[data-cart-toast]");
				const cartToastTitle = root.querySelector("[data-cart-toast-title]");
				const cartToastBody = root.querySelector("[data-cart-toast-body]");

				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 heroPrice = root.querySelector("[data-hero-price]");
				const summaryColorway = root.querySelector("[data-summary-colorway]");
				const summaryQuantity = root.querySelector("[data-summary-quantity]");
				const summaryUnitPrice = root.querySelector("[data-summary-unit-price]");
				const summarySelectionTotal = root.querySelector("[data-summary-selection-total]");
				const summaryCartTotals = Array.from(root.querySelectorAll("[data-summary-cart-total]"));

				let currentPricePerKit = Number(pricePerKit || 0);
				let currentRetailPerKit = Number(retailPerKit || 0);
				const INVENTORY_FINISH_ID = "silver";
				const inventoryMap = new Map();
				if (!addSelectionToCart || !clearCart || !getCartCount || !loadBuilderSelection || !saveBuilderSelection || !loadCart || !removeCartItem) return;
				const colorwayMap = new Map((colorways || []).map((colorway) => [colorway.id, colorway]));
				const finishMap = new Map((finishOptions || []).map((finish) => [finish.id, finish]));
				const DEFAULT_SELECTION = {
					style: "B",
					colorwayId: "sorbet-pop-multi-color",
					finishId: "silver",
					quantity: 1,
				};
				const storedSelection = loadBuilderSelection();
				const allowedStyleIds = new Set(styleButtons.map((button) => button.dataset.styleId).filter(Boolean));
				const allowedFinishIds = new Set(finishButtons.map((button) => button.dataset.finishId).filter(Boolean));

				let selectedStyle = allowedStyleIds.has(storedSelection?.style) ? storedSelection.style : "B";
				let selectedColorwayId = storedSelection?.colorwayId || "sorbet-pop-multi-color";
				let selectedFinishId = allowedFinishIds.has(storedSelection?.finishId) ? storedSelection.finishId : "silver";
				let selectedQuantity = Math.max(1, Math.round(Number(storedSelection?.quantity || "1") || 1));

				const formatGBP = (value) => `£${Number(value).toFixed(2)}`;
				const getInventoryKey = (styleId, colorwayId, finishId = INVENTORY_FINISH_ID) => `${styleId}::${colorwayId}::${finishId}`;
				const getInventoryLevel = (styleId, colorwayId, finishId = INVENTORY_FINISH_ID) => inventoryMap.get(getInventoryKey(styleId, colorwayId, finishId));
				const getAvailabilityState = (level) => {
					if (!level) return { label: "Sold Out/Pre-Order Available", state: "default", soldOut: false };
					const quantity = Number(level.quantityOnHand || 0);
					if (quantity <= 0) return { label: "Sold Out/Pre-Order Available", state: "default", soldOut: false };
					if (quantity <= 3) return { label: `Only ${quantity} left`, state: "low", soldOut: false };
					return { label: `${quantity} available`, state: "ready", soldOut: false };
				};

				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 {
						if (heroPrice) heroPrice.textContent = `${formatGBP(currentPricePerKit)} before public release`;
						updateTotals();
					}
				};
				let cartToastTimer = null;

				const flashCartUi = () => {
					cartItemsNode?.setAttribute("data-cart-flash", "true");
					cartCountNodes.forEach((node) => {
						node.dataset.cartFlash = "true";
					});

					window.setTimeout(() => {
						cartItemsNode?.removeAttribute("data-cart-flash");
						cartCountNodes.forEach((node) => {
							delete node.dataset.cartFlash;
						});
					}, 550);
				};

				const showCartToast = (title, body, state = "success") => {
					if (!cartToast || !cartToastTitle || !cartToastBody) return;

					cartToastTitle.textContent = title;
					cartToastBody.textContent = body;
					cartToast.dataset.state = state;
					cartToast.hidden = false;
					requestAnimationFrame(() => {
						cartToast.dataset.visible = "true";
					});

					if (cartToastTimer) {
						window.clearTimeout(cartToastTimer);
					}

					cartToastTimer = window.setTimeout(() => {
						cartToast.dataset.visible = "false";
						window.setTimeout(() => {
							if (cartToast?.dataset.visible === "false") {
								cartToast.hidden = true;
							}
						}, 220);
					}, 1800);
				};

				const pulseAddButtons = (label) => {
					addToCartButtons.forEach((button) => {
						button.textContent = label;
						button.dataset.added = "true";
					});

					window.setTimeout(() => {
						addToCartButtons.forEach((button) => {
							delete button.dataset.added;
							button.textContent = button.disabled
								? "Sold out"
								: `Add ${selectedQuantity} ${selectedQuantity === 1 ? "kit" : "kits"} to cart`;
						});
					}, 950);
				};

				const renderCartItems = (cart) => {
					if (!cartItemsNode) return;

					if (!cart.length) {
						cartItemsNode.innerHTML = `<div class="${cartItemEmptyClass}">Your cart is empty.</div>`;
						return;
					}

					cartItemsNode.innerHTML = cart
						.map((item) => {
							const colorway = colorwayMap.get(item.colorwayId);
							const finish = finishMap.get(item.finishId);

							if (!colorway || !finish) return "";

							return `
								<article class="${cartItemClass}">
									<div class="${cartItemImageWrapClass}" style="background:${colorway.previewBackground}">
										<img src="${colorway.cardImage}" alt="${colorway.name} cart item" loading="lazy" />
									</div>
									<div class="${cartItemBodyClass}">
										<div class="${cartItemTopClass}">
											<p class="${cartItemTitleClass}">${colorway.name}</p>
											<button
												type="button"
												class="${cartItemRemoveClass}"
												data-remove-cart-item="${item.id}"
												aria-label="Remove ${colorway.name} from cart"
											>
												×
											</button>
										</div>
									<p class="${cartItemSubtitleClass}">${colorway.subtitle}</p>
									<p class="${cartItemMetaClass}">${colorway.styleText}</p>
								<div class="${cartItemFooterClass}">
									<p class="${cartItemMetaClass}">${item.quantity} ${item.quantity === 1 ? "kit" : "kits"} · Matched configuration</p>
								<p class="${cartItemPriceClass}">${formatGBP(currentPricePerKit * item.quantity)}</p>
								</div>
									</div>
								</article>
							`;
						})
						.join("");
				};

				const syncInventoryUi = () => {
					availabilityBadges.forEach((badge) => {
						const styleId = badge.dataset.styleId || "";
						const colorwayId = badge.dataset.colorwayId || "";
						const finishId = badge.dataset.finishId || INVENTORY_FINISH_ID;
						const availability = getAvailabilityState(getInventoryLevel(styleId, colorwayId, finishId));
						badge.textContent = availability.label;
						badge.dataset.state = availability.state;
						const card = badge.closest("[data-colorway-option]");
						if (card) {
							card.dataset.inventoryState = availability.state;
							card.dataset.soldOut = String(availability.soldOut);
							card.toggleAttribute("disabled", availability.soldOut || card.hidden);
						}
					});
				};

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

						inventoryMap.clear();
						(payload?.data?.inventory || []).forEach((entry) => {
							inventoryMap.set(getInventoryKey(entry.style, entry.colorwayId, entry.finishId), entry);
						});
					} catch (_error) {
						inventoryMap.clear();
					} finally {
						syncInventoryUi();
						updateCartUi();
					}
				};

				const syncBuilderSelection = () => {
					saveBuilderSelection({
						style: selectedStyle,
						colorwayId: selectedColorwayId,
						finishId: selectedFinishId,
						quantity: selectedQuantity,
					});
				};

				const updateCartUi = (message = "", state = "info") => {
					const cart = loadCart();
					const cartCount = getCartCount();
					const cartIsReady = cartCount > 0;
					const selectedAvailability = getAvailabilityState(getInventoryLevel(selectedStyle, selectedColorwayId, INVENTORY_FINISH_ID));
					const cartTotal = currentPricePerKit * cartCount;
					const statusText = cartCount === 0 ? "Cart empty · add your first configuration" : `${cartCount} ${cartCount === 1 ? "kit" : "kits"} in cart`;
					const feedbackText = message || (selectedAvailability.soldOut
						? "This configuration is currently sold out. Choose another colourway to continue."
						: cartIsReady
						? "Cart ready. Continue to details when you’re set."
							: "Add this kit to your cart, or use Buy now to go straight to details.");

					if (quantityInput) {
						quantityInput.value = String(selectedQuantity);
					}

					addToCartButtons.forEach((button) => {
						button.hidden = false;
						button.disabled = selectedAvailability.soldOut;
						button.textContent = selectedAvailability.soldOut
								? "Sold out"
							: `Add ${selectedQuantity} ${selectedQuantity === 1 ? "kit" : "kits"} to cart`;
					});

					clearCartButtons.forEach((button) => {
						button.disabled = !cartIsReady;
						button.setAttribute("aria-disabled", String(!cartIsReady));
					});

					cartStatusNodes.forEach((node) => {
						node.textContent = statusText;
					});

					cartCountNodes.forEach((node) => {
						node.textContent = `${cartCount} ${cartCount === 1 ? "kit" : "kits"}`;
					});

					renderCartItems(cart);

					cartFeedbackNodes.forEach((node) => {
						node.textContent = feedbackText;
						node.dataset.cartFeedbackState = state;
					});

						summaryCartTotals.forEach((node) => {
							node.textContent = formatGBP(cartTotal);
						});

					detailsButtons.forEach((button) => {
						button.disabled = selectedAvailability.soldOut;
						button.textContent = cartIsReady ? "Continue to details" : `Buy now for ${selectedQuantity} ${selectedQuantity === 1 ? "kit" : "kits"}`;
						button.dataset.mode = cartIsReady ? "details" : "buy-now";
					});
				};

				const getColorButton = (id) => colorButtons.find((button) => button.dataset.colorwayId === id);

				const resetBuilderSelection = () => {
					selectedStyle = DEFAULT_SELECTION.style;
					selectedColorwayId = DEFAULT_SELECTION.colorwayId;
					selectedFinishId = DEFAULT_SELECTION.finishId;
					selectedQuantity = DEFAULT_SELECTION.quantity;

					applyStyle(selectedStyle);

					const defaultColorButton = getColorButton(selectedColorwayId);
					if (!defaultColorButton || defaultColorButton.hidden || defaultColorButton.dataset.styleId !== selectedStyle) {
						selectedColorwayId = colorButtons.find((button) => button.dataset.styleId === selectedStyle && !button.hidden)?.dataset.colorwayId || selectedColorwayId;
					}

					applyColorway(selectedColorwayId);
					applyFinish(selectedFinishId);
					applyQuantity(selectedQuantity);
				};

				const updateTotals = () => {
					const total = currentPricePerKit * selectedQuantity;
					if (summaryQuantity) summaryQuantity.textContent = `${selectedQuantity} ${selectedQuantity === 1 ? "kit" : "kits"}`;
					if (summaryUnitPrice) summaryUnitPrice.textContent = `${formatGBP(currentPricePerKit)} per kit`;
					if (summarySelectionTotal) summarySelectionTotal.textContent = formatGBP(total);
					syncBuilderSelection();
					updateCartUi();
				};

				const applyColorway = (id) => {
					const activeButton = getColorButton(id);

					if (!activeButton) return;

					selectedColorwayId = id;

					colorButtons.forEach((button) => {
						button.setAttribute("aria-pressed", String(button === activeButton));
					});

					const image = activeButton.dataset.colorwayImage || "";
					const name = activeButton.dataset.colorwayName || "";
					const subtitle = activeButton.dataset.colorwaySubtitle || "";
					const style = activeButton.dataset.colorwayStyle || "";
					const crown = activeButton.dataset.colorwayCrown || "";

					if (summaryImage && image) summaryImage.setAttribute("src", image);
					if (summaryImage && name) summaryImage.setAttribute("alt", `${name} Royal Pop configuration preview`);
					if (summaryName) summaryName.textContent = name;
					if (summarySubtitle) summarySubtitle.textContent = subtitle;
					if (summaryStyle) summaryStyle.textContent = style;
					if (summaryCrown) summaryCrown.textContent = crown;
					if (summaryColorway) summaryColorway.textContent = name;
					syncBuilderSelection();
				};

				const applyStyle = (styleId) => {
					selectedStyle = styleId;

					styleButtons.forEach((button) => {
						button.setAttribute("aria-pressed", String(button.dataset.styleId === styleId));
					});

					let firstVisibleId = null;

					colorButtons.forEach((button) => {
						const matches = button.dataset.styleId === styleId;
						button.hidden = !matches;
						button.toggleAttribute("disabled", !matches || button.dataset.soldOut === "true");
						button.tabIndex = matches ? 0 : -1;

						if (matches && button.dataset.soldOut !== "true" && !firstVisibleId) {
							firstVisibleId = button.dataset.colorwayId;
						}
					});

					if (!firstVisibleId) {
						firstVisibleId = colorButtons.find((button) => button.dataset.styleId === styleId && !button.hidden)?.dataset.colorwayId || null;
					}

					const current = getColorButton(selectedColorwayId);
					const currentMatches = current && current.dataset.styleId === styleId;

					if (!currentMatches && firstVisibleId) {
						applyColorway(firstVisibleId);
					}

					syncBuilderSelection();
				};

				const applyFinish = (finishId) => {
					const activeButton = finishButtons.find((button) => button.dataset.finishId === finishId) || finishButtons[0];
					if (!activeButton) return;

					selectedFinishId = activeButton.dataset.finishId || "silver";

					finishButtons.forEach((button) => {
						button.setAttribute("aria-pressed", String(button === activeButton));
					});

						syncBuilderSelection();
					};

				const applyQuantity = (quantity) => {
					selectedQuantity = Math.max(1, Math.round(Number(quantity) || 1));
					if (quantityInput) {
						quantityInput.value = String(selectedQuantity);
					}
					updateTotals();
					syncBuilderSelection();
				};

				styleButtons.forEach((button) => {
					button.addEventListener("click", () => {
						const { styleId } = button.dataset;
						if (styleId) {
							applyStyle(styleId);
						}
					});
				});

				colorButtons.forEach((button) => {
					button.addEventListener("click", () => {
						if (button.hidden || button.dataset.soldOut === "true") return;
						const { colorwayId } = button.dataset;
						if (colorwayId) {
							applyColorway(colorwayId);
						}
					});
				});

				finishButtons.forEach((button) => {
					button.addEventListener("click", () => {
						const { finishId } = button.dataset;
						if (finishId) {
							applyFinish(finishId);
						}
					});
				});

				quantityInput?.addEventListener("input", () => {
					applyQuantity(quantityInput.value);
				});

				quantityInput?.addEventListener("change", () => {
					applyQuantity(quantityInput.value);
				});

				addToCartButtons.forEach((button) => {
					button.addEventListener("click", () => {
						if (button.disabled) return;
						const result = addSelectionToCart({
							style: selectedStyle,
							colorwayId: selectedColorwayId,
							finishId: selectedFinishId,
							quantity: selectedQuantity,
						});

						if (result.addedCount === 0) {
							updateCartUi("We couldn’t add that configuration right now. Please try again.", "error");
							showCartToast("Couldn’t add to cart", "Please try adding that configuration again.", "error");
							return;
						}

						const addedLabel = `${result.addedCount} ${result.addedCount === 1 ? "kit" : "kits"}`;
						resetBuilderSelection();
						updateCartUi(`Added ${addedLabel} to your cart.`, "success");
						pulseAddButtons(result.addedCount === 1 ? "Added to cart" : `Added ${addedLabel}`);
						flashCartUi();
						showCartToast(
							"Added to cart",
							`${addedLabel} added to your Royal Pop cart.`,
							"success",
						);
					});
				});

				clearCartButtons.forEach((button) => {
					button.addEventListener("click", () => {
						clearCart();
						resetBuilderSelection();
						updateCartUi("Cart cleared. You can build a new selection now.", "success");
						showCartToast("Cart cleared", "Your saved kits were removed from the cart.", "success");
					});
				});

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

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

					removeCartItem(itemId);
					updateCartUi("Kit removed from your cart.", "success");
					showCartToast("Removed from cart", "That kit was removed from your Royal Pop cart.", "success");
				});

					detailsButtons.forEach((button) => {
						button.addEventListener("click", () => {
							if (button.disabled) return;
							const cartCount = getCartCount();

						if (cartCount === 0) {
							const result = addSelectionToCart({
								style: selectedStyle,
								colorwayId: selectedColorwayId,
								finishId: selectedFinishId,
								quantity: selectedQuantity,
							});

							if (result.addedCount === 0) {
								updateCartUi("We couldn’t add that configuration right now. Please try again.", "error");
								showCartToast("Couldn’t add to cart", "Please try adding that configuration again.", "error");
								return;
							}

							updateCartUi(`Added ${result.addedCount} ${result.addedCount === 1 ? "kit" : "kits"} and continuing to details.`, "success");
						}

						window.location.href = "/details";
					});
				});

				applyStyle(selectedStyle);

				const initialColorButton = getColorButton(selectedColorwayId);
				if (!initialColorButton || initialColorButton.dataset.styleId !== selectedStyle || initialColorButton.hidden) {
					selectedColorwayId = colorButtons.find((button) => button.dataset.styleId === selectedStyle && !button.hidden)?.dataset.colorwayId || selectedColorwayId;
				}

					applyColorway(selectedColorwayId);
					applyFinish(selectedFinishId);
					applyQuantity(selectedQuantity);
					updateCartUi();
					loadInventory();
					loadPricing();
				};

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

	</main>
</BaseLayout>
