---
// Path: Store/src/pages/index.astro
import ColorwaysSection from "../components/royal-pop/ColorwaysSection.astro";
import FeatureSections from "../components/royal-pop/FeatureSections.astro";
import HeroSection from "../components/royal-pop/HeroSection.astro";
import PreorderSection from "../components/royal-pop/PreorderSection.astro";
import SiteFooter from "../components/royal-pop/SiteFooter.astro";
import SpecsSection from "../components/royal-pop/SpecsSection.astro";
import StatsBand from "../components/royal-pop/StatsBand.astro";
import { colorways, heroStats, specRows } from "../data/royalPop";
import BaseLayout from "../layouts/BaseLayout.astro";
import styles from "./index.module.scss";

const apiBaseUrl = process.env.API_BASE_URL || (import.meta.env.PROD ? "" : "http://localhost:8081");
const siteUrl = "https://royal-pop-accessory.com";
const socialImage = "/images/png/pure-white.png";

const structuredData = [
	{
		"@context": "https://schema.org",
		"@type": "Organization",
		name: "Royal Pop Accessory",
		url: siteUrl,
		logo: `${siteUrl}/favicon/android-chrome-512x512.png`,
		image: `${siteUrl}${socialImage}`,
		description:
			"Royal Pop Accessory creates bold interchangeable watch strap accessories in standout colourways for collectors who want a fast visual transformation.",
	},
	{
		"@context": "https://schema.org",
		"@type": "WebSite",
		name: "Royal Pop Accessory",
		url: siteUrl,
		description:
			"Upgrade your watch with Royal Pop Accessory — bold interchangeable strap accessories in standout colourways, built to change your look in seconds.",
	},
];
---

<BaseLayout
	title="Turn Your Strap Into a Statement"
	description="Upgrade your watch with Royal Pop Accessory — bold interchangeable strap accessories in standout colourways, built to change your look in seconds."
	socialTitle="Royal Pop Accessory | Turn Your Strap Into a Statement"
	socialImage={socialImage}
	structuredData={structuredData}
>
	<main class={styles.homepage} data-home-page>
		<nav class={styles.nav} aria-label="Primary">
			<div class={styles.navInner}>
				<a class={styles.navLogo} href="#top">Royal Pop</a>
				<a href="/buy" class:list={[styles.navCta, styles.navCtaMobile]}>Pre-Order</a>

				<div class={styles.navLinks}>
					<a href="#features">Features</a>
					<a href="#colorways">Colorways</a>
					<a href="#specs">Specs</a>
					<a href="/buy" class={styles.navCta}>Pre-Order</a>
				</div>
			</div>
		</nav>

		<section id="top">
			<HeroSection />
		</section>

		<section class={styles.taglineBand}>
			<div class={styles.taglineInner}>
				<p>From pocket to wrist.</p>
				<p><span>Without compromise.</span></p>
			</div>
		</section>

		<StatsBand items={heroStats} />
		<FeatureSections />
		<ColorwaysSection colorways={colorways} />
		<SpecsSection rows={specRows} />
		<PreorderSection />
		<SiteFooter />

		<script define:vars={{ apiBaseUrl }}>
			const initHomePage = () => {
				const root = document.querySelector("[data-home-page]");
				if (!root) return;

				const normalizedApiBaseUrl = String(apiBaseUrl || "").replace(/\/$/, "");
				const preorderBody = root.querySelector("[data-preorder-body]");
				const preorderPriceNow = root.querySelector("[data-preorder-price-now]");
				const preorderPriceRetail = root.querySelector("[data-preorder-price-retail]");
				const heroCta = root.querySelector("[data-hero-cta]");
				const earlyBirdStat = root.querySelector('[data-stat-id="early-bird-stat-value"]');

				const reveals = Array.from(root.querySelectorAll(".reveal"));

				const formatCurrency = (amount, currency = "gbp") =>
					new Intl.NumberFormat("en-GB", {
						style: "currency",
						currency: String(currency || "gbp").toUpperCase(),
						minimumFractionDigits: 2,
					}).format(Number(amount || 0));

				const updatePricing = async () => {
					try {
						const response = await fetch(`${normalizedApiBaseUrl}/v1/storefront/pricing`);
						if (!response.ok) throw new Error(`pricing request failed: ${response.status}`);
						const payload = await response.json();
						const pricing = payload?.data;
						if (!pricing?.unitAmount) return;

						const unitPrice = formatCurrency(Number(pricing.unitAmount) / 100, pricing.currency);
						const retailPrice = pricing.retailAmount
							? formatCurrency(Number(pricing.retailAmount) / 100, pricing.currency)
							: null;

						if (preorderPriceNow) preorderPriceNow.textContent = unitPrice;
						if (preorderPriceRetail && retailPrice) preorderPriceRetail.textContent = retailPrice;
						if (earlyBirdStat) earlyBirdStat.textContent = unitPrice;
						if (preorderBody) {
							preorderBody.textContent = `Pre-orders typically ship in around 1 month. Each kit is matched to a specific Royal Pop colourway — lock in yours before the ${unitPrice} early bird closes.`;
						}
						if (heroCta) {
							heroCta.textContent = `Pre-Order · ${unitPrice} Early Bird`;
						}
					} catch {
						// Keep baked fallback pricing copy when pricing lookup fails.
					}
				};

				if (reveals.length > 0) {
					if ("IntersectionObserver" in window) {
						const observer = new IntersectionObserver(
							(entries) => {
								entries.forEach((entry) => {
									if (entry.isIntersecting) {
										entry.target.classList.add("in");
										observer.unobserve(entry.target);
									}
								});
							},
							{ threshold: 0.15 },
						);

						reveals.forEach((element) => {
							if (element.classList.contains("in")) return;
							observer.observe(element);
						});
					} else {
						reveals.forEach((element) => element.classList.add("in"));
					}
				}

				updatePricing();
			};

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