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

const apiBaseUrl = process.env.API_BASE_URL || (import.meta.env.PROD ? "" : "http://localhost:8081");
const secondaryCtaClass = styles.secondaryCta;
const emptyStateClass = styles.emptyState;
const orderCardClass = styles.orderCard;
const orderCardHeaderClass = styles.orderCardHeader;
const orderTitleClass = styles.orderTitle;
const orderSubtitleClass = styles.orderSubtitle;
const orderBadgeClass = styles.orderBadge;
const orderMetaGridClass = styles.orderMetaGrid;
const orderNotesClass = styles.orderNotes;
const orderItemsClass = styles.orderItems;
---

<BaseLayout
	title="Royal Pop Client Dashboard"
	description="Private dashboard for reviewing Royal Pop orders and fulfilment activity."
	noindex={true}
>
	<main class={styles.clientPage} data-client-dashboard>
		<header class={styles.topbar}>
			<div class={styles.topbarInner}>
				<a href="/" class={styles.backLink}>Royal Pop</a>

				<div class={styles.progress} aria-label="Client tools">
					<span class={styles.progressActive}>Client dashboard</span>
					<a href="/client/orders/" class={styles.ghostLink}>Orders</a>
					<a href="/client/stock/" class={styles.ghostLink}>Stock</a>
				</div>

				<div class={styles.topbarActions}>
					<p class={styles.helpText}>Private access only</p>
					<button type="button" class={styles.logoutButton} data-client-logout hidden>Log out</button>
				</div>
			</div>
		</header>

		<section class={styles.hero}>
			<div class={styles.heroInner}>
				<div>
					<p class={styles.eyebrow}>Client operations</p>
					<h1 class={styles.heroTitle}>Manage orders and stock without leaving the Royal Pop flow.</h1>
					<p class={styles.heroBody} data-dashboard-hero-body>
						Sign in to review customer orders, then jump into dedicated workspaces for fulfilment updates and inventory control.
					</p>
				</div>

				<div class={styles.heroMeta}>
					<div>
						<strong>Orders</strong>
						<span>Review recent customer submissions with totals, timestamps, and product details.</span>
					</div>
					<div>
						<strong>Fulfilment</strong>
						<span>Use the dedicated orders workspace to update statuses, tracking numbers, and shipping notes.</span>
					</div>
					<div>
						<strong>Stock</strong>
						<span>Open the dedicated stock workspace to adjust inventory counts that feed the public buy page.</span>
					</div>
				</div>
			</div>
		</section>

		<section class={styles.dashboardSection}>
			<div class={styles.dashboardShell}>
				<section class={styles.loginPanel} data-client-login-panel>
					<div class={styles.panelHeader}>
						<p class={styles.sectionKicker}>Sign in</p>
						<h2>Open the client dashboard.</h2>
						<p>Use the simple dashboard credentials configured for this environment.</p>
					</div>

					<form class={styles.loginForm} data-client-login-form>
						<label class={styles.field}>
							<span>Username</span>
							<input type="text" name="username" autocomplete="username" required />
						</label>
						<label class={styles.field}>
							<span>Password</span>
							<input type="password" name="password" autocomplete="current-password" required />
						</label>

						<div class={styles.loginActions}>
							<button type="submit" class={styles.primaryCta} data-client-login-submit>Unlock dashboard</button>
						</div>

						<p class={styles.formStatus} data-client-auth-feedback data-state="info">
							Sign in to load current orders and open the fulfilment workspace.
						</p>
					</form>
				</section>

				<section class={styles.dashboardPanel} data-client-dashboard-panel hidden>
					<div class={styles.summaryGrid}>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Total orders</p>
							<strong data-summary-total-orders>0</strong>
							<span>Recent customer orders currently visible in the dashboard.</span>
						</article>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Paid orders</p>
							<strong data-summary-paid-orders>0</strong>
							<span>Orders already confirmed by Stripe and persisted.</span>
						</article>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Processing</p>
							<strong data-summary-processing-orders>0</strong>
							<span>Orders already being prepared, packed, or actively worked on.</span>
						</article>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Shipped</p>
							<strong data-summary-shipped-orders>0</strong>
							<span>Orders already moved into shipped or delivered fulfilment states.</span>
						</article>
					</div>

					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.sectionKicker}>Orders</p>
							<h2>Recent orders</h2>
							<p>Latest customer submissions, totals, and fulfilment context from the checkout flow.</p>
							<div class={styles.loginActions}>
								<a href="/client/orders/" class={styles.secondaryCta}>Open dedicated orders page</a>
							</div>
						</div>

						<div class={styles.ordersList} data-client-orders-list></div>
					</section>

					<section class={styles.panel}>
						<div class={styles.panelHeader}>
							<p class={styles.sectionKicker}>Stock</p>
							<h2>Inventory workspace</h2>
							<p>Use the separate stock page to update live availability while keeping the public buy page tied to current inventory.</p>
							<div class={styles.loginActions}>
								<a href="/client/stock/" class={styles.secondaryCta}>Open dedicated stock page</a>
							</div>
						</div>
					</section>

					<p class={styles.dashboardStatus} data-client-dashboard-feedback data-state="info">Dashboard ready.</p>
				</section>
			</div>
		</section>

		<SiteFooter />

		<script
			define:vars={{
				apiBaseUrl,
				colorways,
				secondaryCtaClass,
				emptyStateClass,
				orderCardClass,
				orderCardHeaderClass,
				orderTitleClass,
				orderSubtitleClass,
				orderBadgeClass,
				orderMetaGridClass,
				orderNotesClass,
				orderItemsClass,
			}}
		>
			const normalizedApiBaseUrl = String(apiBaseUrl || "").replace(/\/$/, "");

			const initClientDashboard = () => {
				const root = document.querySelector("[data-client-dashboard]");
				if (!root || root.dataset.initialized === "true") return;
				root.dataset.initialized = "true";

				const loginPanel = root.querySelector("[data-client-login-panel]");
				const dashboardPanel = root.querySelector("[data-client-dashboard-panel]");
				const loginForm = root.querySelector("[data-client-login-form]");
				const loginSubmit = root.querySelector("[data-client-login-submit]");
				const authFeedback = root.querySelector("[data-client-auth-feedback]");
				const dashboardFeedback = root.querySelector("[data-client-dashboard-feedback]");
				const ordersList = root.querySelector("[data-client-orders-list]");
				const logoutButton = root.querySelector("[data-client-logout]");
				const summaryTotalOrders = root.querySelector("[data-summary-total-orders]");
				const summaryPaidOrders = root.querySelector("[data-summary-paid-orders]");
				const summaryProcessingOrders = root.querySelector("[data-summary-processing-orders]");
				const summaryShippedOrders = root.querySelector("[data-summary-shipped-orders]");
				const heroBody = root.querySelector("[data-dashboard-hero-body]");
				const colorwayMap = new Map((colorways || []).map((colorway) => [colorway.id, colorway]));

				const formatGBP = (value) =>
					new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" }).format(Number(value || 0) / 100);

				const formatDateTime = (value) => {
					if (!value) return "—";
					const parsed = new Date(value);
					if (Number.isNaN(parsed.getTime())) return value;
					return parsed.toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short" });
				};

				const setFeedback = (node, message, state = "info") => {
					if (!node) return;
					node.textContent = message;
					node.dataset.state = state;
				};

				const updateSummary = (ordersEntries) => {
					const totalOrders = (ordersEntries || []).length;
					const paidOrders = (ordersEntries || []).filter((order) => order.status === "paid").length;
					const processingOrders = (ordersEntries || []).filter((order) => ["processing", "packed"].includes(order.fulfillmentStatus)).length;
					const shippedOrders = (ordersEntries || []).filter((order) => ["shipped", "delivered"].includes(order.fulfillmentStatus)).length;

					if (summaryTotalOrders) summaryTotalOrders.textContent = String(totalOrders);
					if (summaryPaidOrders) summaryPaidOrders.textContent = String(paidOrders);
					if (summaryProcessingOrders) summaryProcessingOrders.textContent = String(processingOrders);
					if (summaryShippedOrders) summaryShippedOrders.textContent = String(shippedOrders);
				};

				const renderOrders = (ordersEntries) => {
					if (!ordersList) return;
					if (!ordersEntries?.length) {
						ordersList.innerHTML = `<div class="${emptyStateClass}">No orders have been stored yet.</div>`;
						return;
					}

					ordersList.innerHTML = ordersEntries
						.map((order) => {
							const items = (order.items || [])
								.map((item) => {
									const colorway = colorwayMap.get(item.colorwayId);
									return `<li><strong>${colorway?.name || item.colorwayId}</strong> · ${item.style} · ${item.finishId} · ${item.quantity} × ${formatGBP(item.unitAmount)}</li>`;
								})
								.join("");

							return `
								<article class="${orderCardClass}">
									<div class="${orderCardHeaderClass}">
										<div>
											<p class="${orderTitleClass}">${order.firstName} ${order.lastName}</p>
											<p class="${orderSubtitleClass}">${order.email} · ${order.country}</p>
										</div>
										<span class="${orderBadgeClass}" data-status="${order.fulfillmentStatus || order.status}">${order.fulfillmentStatus || order.status}</span>
									</div>
									<div class="${orderMetaGridClass}">
										<div><span>Order ID</span><strong>${order.id}</strong></div>
										<div><span>Total</span><strong>${formatGBP(order.amount)}</strong></div>
										<div><span>Created</span><strong>${formatDateTime(order.createdAt)}</strong></div>
										<div><span>Tracking</span><strong>${order.trackingNumber || "Not added"}</strong></div>
									</div>
									${order.notes ? `<p class="${orderNotesClass}">${order.notes}</p>` : ""}
									<ul class="${orderItemsClass}">${items}</ul>
									<p><a href="/client/orders/" class="${secondaryCtaClass}">Open in orders workspace</a></p>
								</article>
							`;
						})
						.join("");
				};

				const setAuthenticatedUi = (authenticated, username = "") => {
					if (loginPanel) loginPanel.hidden = authenticated;
					if (dashboardPanel) dashboardPanel.hidden = !authenticated;
					if (logoutButton) logoutButton.hidden = !authenticated;
				if (heroBody) {
					heroBody.textContent = authenticated
						? `Signed in as ${username || "client user"}. Review live order activity, then jump into dedicated orders or stock workspaces whenever you need fulfilment or inventory changes.`
						: "Sign in to review recent customer orders and open the dedicated orders or stock workspaces.";
				}
			};

				const loadDashboard = async () => {
					const ordersResponse = await fetch(`${normalizedApiBaseUrl}/v1/client/orders?limit=25`, { credentials: "include" });
					const ordersPayload = await ordersResponse.json().catch(() => null);

					if (!ordersResponse.ok) {
						throw new Error(ordersPayload?.error?.message || "The client dashboard could not load recent orders.");
					}

					const ordersEntries = ordersPayload?.data?.orders || [];
					renderOrders(ordersEntries);
					updateSummary(ordersEntries);
				};

				const syncSession = async () => {
					try {
						const response = await fetch(`${normalizedApiBaseUrl}/v1/client/session`, { credentials: "include" });
						const payload = await response.json().catch(() => null);
						const session = payload?.data;

						if (!response.ok || !session?.configured) {
							setAuthenticatedUi(false);
							setFeedback(authFeedback, session?.configured === false ? "Client dashboard credentials are not configured for this environment yet." : "Unable to verify dashboard access.", session?.configured === false ? "error" : "info");
							return;
						}

						if (!session.authenticated) {
							setAuthenticatedUi(false);
							setFeedback(authFeedback, "Sign in to load current orders and open the fulfilment workspace.", "info");
							return;
						}

						setAuthenticatedUi(true, session.username);
						setFeedback(dashboardFeedback, "Dashboard ready.", "success");
						await loadDashboard();
					} catch (error) {
						setAuthenticatedUi(false);
						setFeedback(authFeedback, error instanceof Error ? error.message : "Unable to verify dashboard access.", "error");
					}
				};

				loginForm?.addEventListener("submit", async (event) => {
					event.preventDefault();
					const formData = new FormData(loginForm);
					const username = String(formData.get("username") || "").trim();
					const password = String(formData.get("password") || "");

					if (!username || !password) {
						setFeedback(authFeedback, "Enter both the username and password.", "error");
						return;
					}

					if (loginSubmit) {
						loginSubmit.disabled = true;
						loginSubmit.textContent = "Unlocking…";
					}
					setFeedback(authFeedback, "Checking credentials…", "info");

					try {
						const response = await fetch(`${normalizedApiBaseUrl}/v1/client/login`, {
							method: "POST",
							credentials: "include",
							headers: { "Content-Type": "application/json" },
							body: JSON.stringify({ username, password }),
						});

						const payload = await response.json().catch(() => null);
						if (!response.ok) {
							throw new Error(payload?.error?.message || "The dashboard credentials were rejected.");
						}

						setFeedback(authFeedback, "Access granted. Loading dashboard…", "success");
						loginForm.reset();
						await syncSession();
					} catch (error) {
						setFeedback(authFeedback, error instanceof Error ? error.message : "The dashboard credentials were rejected.", "error");
					} finally {
						if (loginSubmit) {
							loginSubmit.disabled = false;
							loginSubmit.textContent = "Unlock dashboard";
						}
					}
				});

				logoutButton?.addEventListener("click", async () => {
					await fetch(`${normalizedApiBaseUrl}/v1/client/logout`, {
						method: "POST",
						credentials: "include",
					});
					setAuthenticatedUi(false);
					setFeedback(authFeedback, "Signed out. Sign in again to reopen the dashboard.", "info");
				});

				syncSession();
			};

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