---
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 fulfillmentStatuses = [
	"pending",
	"paid",
	"processing",
	"packed",
	"shipped",
	"delivered",
	"cancelled",
];
const finishOptions = [
	{ id: "silver", label: "Silver" },
	{ id: "black-pvd", label: "Black PVD" },
	{ id: "rose-gold", label: "Rose Gold" },
];

const resultCardClass = styles.resultCard;
const resultCardActiveClass = styles.resultCardActive;
const resultMetaClass = styles.resultMeta;
const resultCustomerClass = styles.resultCustomer;
const resultSummaryClass = styles.resultSummary;
const detailPanelClass = styles.detailPanel;
const detailSectionClass = styles.detailSection;
const detailGridClass = styles.detailGrid;
const detailAddressClass = styles.detailAddress;
const detailItemsClass = styles.detailItems;
const detailFormClass = styles.detailForm;
const searchControlsClass = styles.searchControls;
const toolbarClass = styles.toolbar;
const ordersWorkspaceClass = styles.ordersWorkspace;
const orderResultsClass = styles.orderResults;
const stickyDetailClass = styles.stickyDetail;
const selectFieldClass = styles.selectField;
const textareaFieldClass = styles.textareaField;
const emptyDetailClass = styles.emptyDetail;
const ghostLinkClass = styles.ghostLink;
const statRowClass = styles.statRow;
const orderBadgeClass = styles.orderBadge;
const orderTitleClass = styles.orderTitle;
const orderSubtitleClass = styles.orderSubtitle;
const orderCardHeaderClass = styles.orderCardHeader;
const fieldClass = styles.field;
const primaryCtaClass = styles.primaryCta;
const secondaryCtaClass = styles.secondaryCta;
const loginActionsClass = styles.loginActions;
const sectionKickerClass = styles.sectionKicker;
const searchActionsClass = styles.searchActions;
const searchHintClass = styles.searchHint;
const resultFooterClass = styles.resultFooter;
const detailCalloutClass = styles.detailCallout;
const detailSubgridClass = styles.detailSubgrid;
const detailFormFooterClass = styles.detailFormFooter;
---

<BaseLayout
	title="Royal Pop Client Orders"
	description="Private Royal Pop orders workspace for reviewing and updating customer orders."
	noindex={true}
>
	<main class={styles.clientPage} data-client-orders-page>
		<header class={styles.topbar}>
			<div class={styles.topbarInner}>
				<a href="/client/" class={styles.backLink}>Royal Pop</a>

				<div class={styles.progress} aria-label="Client tools">
					<a href="/client/" class={ghostLinkClass}>Client dashboard</a>
					<span class={styles.progressActive}>Orders</span>
					<a href="/client/stock/" class={ghostLinkClass}>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 orders</p>
					<h1 class={styles.heroTitle}>Search orders, open full details, and manage fulfilment in one place.</h1>
					<p class={styles.heroBody} data-orders-hero-body>
						Review customer details, shipping addresses, line items, and update tracking without leaving the Royal Pop admin flow.
					</p>
				</div>

				<div class={styles.heroMeta}>
					<div>
						<strong>Search</strong>
						<span>Filter by order ID, customer name, email, or tracking number.</span>
					</div>
					<div>
						<strong>Detail</strong>
						<span>Open full shipping details, payment state, webhook notes, and order contents.</span>
					</div>
					<div>
						<strong>Fulfilment</strong>
						<span>Move orders through approved statuses and attach carrier + tracking updates.</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 orders console.</h2>
						<p>Use the same simple client credentials as the main dashboard.</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 orders</button>
						</div>

						<p class={styles.formStatus} data-client-auth-feedback data-state="info">
							Sign in to search and update customer orders.
						</p>
					</form>
				</section>

				<section class={styles.dashboardPanel} data-client-orders-panel hidden>
					<div class={toolbarClass}>
						<div class={styles.panelHeader}>
							<p class={styles.sectionKicker}>Orders workspace</p>
							<h2>Dedicated order management</h2>
							<p>Search your current order set and open any order to review the address, payment state, and fulfilment details.</p>
						</div>

						<form class={searchControlsClass} data-orders-search-form>
							<label class={styles.field}>
								<span>Search</span>
								<input type="search" name="search" placeholder="Order ID, customer, email, or tracking" />
							</label>
							<label class={selectFieldClass}>
								<span>Status</span>
								<select name="status">
									<option value="">All fulfilment statuses</option>
									{fulfillmentStatuses.map((status) => (
										<option value={status}>{status}</option>
									))}
								</select>
							</label>
							<div class={searchActionsClass}>
								<button type="submit" class={styles.primaryCta}>Search orders</button>
								<button type="button" class={secondaryCtaClass} data-orders-reset>Clear</button>
							</div>
						</form>

						<p class={searchHintClass}>Tip: use the detail panel to save fulfilment changes without losing your filtered order list.</p>
					</div>

					<div class={styles.summaryGrid}>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Total orders</p>
							<strong data-summary-total-orders>0</strong>
							<span>Current results in this filtered view.</span>
						</article>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Open fulfilment</p>
							<strong data-summary-open-orders>0</strong>
							<span>Pending, paid, processing, or packed orders still moving forward.</span>
						</article>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Shipped</p>
							<strong data-summary-shipped-orders>0</strong>
							<span>Orders dispatched with tracking already attached.</span>
						</article>
						<article class={styles.summaryCard}>
							<p class={styles.sectionKicker}>Delivered</p>
							<strong data-summary-delivered-orders>0</strong>
							<span>Orders marked complete after successful arrival.</span>
						</article>
					</div>

					<div class={ordersWorkspaceClass}>
						<section class={orderResultsClass}>
							<div class={statRowClass}>
								<p class={styles.helpText}>Results</p>
								<strong data-orders-count>0 orders</strong>
							</div>
							<div class={styles.ordersList} data-orders-results></div>
						</section>

						<section class={stickyDetailClass}>
							<div data-order-detail></div>
							<p class={styles.dashboardStatus} data-order-detail-feedback data-state="info">Choose an order to inspect and update it.</p>
						</section>
					</div>

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

		<SiteFooter />

		<script
			define:vars={{
				apiBaseUrl,
				colorways,
				finishOptions,
				fulfillmentStatuses,
				resultCardClass,
				resultCardActiveClass,
				resultMetaClass,
				resultCustomerClass,
				resultSummaryClass,
				detailPanelClass,
				detailSectionClass,
				detailGridClass,
				detailAddressClass,
				detailItemsClass,
				detailFormClass,
				searchControlsClass,
				toolbarClass,
				ordersWorkspaceClass,
				orderResultsClass,
				stickyDetailClass,
				selectFieldClass,
				textareaFieldClass,
				emptyDetailClass,
				ghostLinkClass,
				statRowClass,
				orderBadgeClass,
				orderTitleClass,
				orderSubtitleClass,
				orderCardHeaderClass,
				fieldClass,
				primaryCtaClass,
				secondaryCtaClass,
				loginActionsClass,
				sectionKickerClass,
				searchActionsClass,
				searchHintClass,
				resultFooterClass,
				detailCalloutClass,
				detailSubgridClass,
				detailFormFooterClass,
			}}
		>
			const normalizedApiBaseUrl = String(apiBaseUrl || "").replace(/\/$/, "");

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

				const loginPanel = root.querySelector("[data-client-login-panel]");
				const ordersPanel = root.querySelector("[data-client-orders-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 ordersFeedback = root.querySelector("[data-client-orders-feedback]");
				const detailFeedback = root.querySelector("[data-order-detail-feedback]");
				const searchForm = root.querySelector("[data-orders-search-form]");
				const resetButton = root.querySelector("[data-orders-reset]");
				const resultsNode = root.querySelector("[data-orders-results]");
				const detailNode = root.querySelector("[data-order-detail]");
				const ordersCount = root.querySelector("[data-orders-count]");
				const summaryTotalOrders = root.querySelector("[data-summary-total-orders]");
				const summaryOpenOrders = root.querySelector("[data-summary-open-orders]");
				const summaryShippedOrders = root.querySelector("[data-summary-shipped-orders]");
				const summaryDeliveredOrders = root.querySelector("[data-summary-delivered-orders]");
				const heroBody = root.querySelector("[data-orders-hero-body]");
				const logoutButton = root.querySelector("[data-client-logout]");

				const colorwayMap = new Map((colorways || []).map((colorway) => [colorway.id, colorway]));
				const finishMap = new Map((finishOptions || []).map((finish) => [finish.id, finish.label]));
				const state = {
					orders: [],
					selectedOrderId: "",
					selectedOrder: null,
					filters: {
						search: "",
						status: "",
					},
				};

				const escapeHtml = (value) =>
					String(value ?? "")
						.replace(/&/g, "&amp;")
						.replace(/</g, "&lt;")
						.replace(/>/g, "&gt;")
						.replace(/\"/g, "&quot;")
						.replace(/'/g, "&#39;");

				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, stateName = "info") => {
					if (!node) return;
					node.textContent = message;
					node.dataset.state = stateName;
				};

				const setAuthenticatedUi = (authenticated, username = "") => {
					if (loginPanel) loginPanel.hidden = authenticated;
					if (ordersPanel) ordersPanel.hidden = !authenticated;
					if (logoutButton) logoutButton.hidden = !authenticated;
					if (heroBody) {
						heroBody.textContent = authenticated
							? `Signed in as ${username || "client user"}. Search current orders, inspect addresses, and update fulfilment details.`
							: "Review customer details, shipping addresses, line items, and update tracking without leaving the Royal Pop admin flow.";
					}
				};

				const updateSummary = () => {
					const total = state.orders.length;
					const open = state.orders.filter((order) => ["pending", "paid", "processing", "packed"].includes(order.fulfillmentStatus)).length;
					const shipped = state.orders.filter((order) => order.fulfillmentStatus === "shipped").length;
					const delivered = state.orders.filter((order) => order.fulfillmentStatus === "delivered").length;

					if (summaryTotalOrders) summaryTotalOrders.textContent = String(total);
					if (summaryOpenOrders) summaryOpenOrders.textContent = String(open);
					if (summaryShippedOrders) summaryShippedOrders.textContent = String(shipped);
					if (summaryDeliveredOrders) summaryDeliveredOrders.textContent = String(delivered);
				};

				const renderResults = () => {
					if (!resultsNode) return;
					if (!state.orders.length) {
						resultsNode.innerHTML = `<div class="${emptyDetailClass}">No orders matched this search yet.</div>`;
						if (ordersCount) ordersCount.textContent = "0 orders";
						updateSummary();
						return;
					}

					if (ordersCount) {
						ordersCount.textContent = `${state.orders.length} ${state.orders.length === 1 ? "order" : "orders"}`;
					}

					resultsNode.innerHTML = state.orders
						.map((order) => {
							const activeClass = order.id === state.selectedOrderId ? ` ${resultCardActiveClass}` : "";
							return `
								<button type="button" class="${resultCardClass}${activeClass}" data-order-select="${escapeHtml(order.id)}">
									<div class="${resultCustomerClass}">
										<div>
											<strong>${escapeHtml(order.firstName)} ${escapeHtml(order.lastName)}</strong>
											<p>${escapeHtml(order.email)}</p>
										</div>
									<span class="${orderBadgeClass}" data-status="${escapeHtml(order.fulfillmentStatus || order.status)}">${escapeHtml(order.fulfillmentStatus || order.status)}</span>
									</div>
									<div class="${resultMetaClass}">
										<span>${escapeHtml(order.id)}</span>
										<span>${formatGBP(order.amount)}</span>
										<span>${formatDateTime(order.createdAt)}</span>
									</div>
									<p class="${resultSummaryClass}">${escapeHtml(order.city || "—")}, ${escapeHtml(order.country || "—")} · ${Number(order.itemCount || 0)} items</p>
									<div class="${resultFooterClass}">
										<span>Tracking: ${escapeHtml(order.trackingNumber || "Not added")}</span>
										<span>Carrier: ${escapeHtml(order.shippingCarrier || "Not set")}</span>
									</div>
								</button>
							`;
						})
						.join("");
					updateSummary();

					Array.from(resultsNode.querySelectorAll("[data-order-select]"))?.forEach((button) => {
						button.addEventListener("click", async () => {
							const orderID = button.getAttribute("data-order-select") || "";
							if (!orderID) return;
							await loadOrderDetail(orderID);
						});
					});
				};

				const renderDetail = () => {
					if (!detailNode) return;
					const order = state.selectedOrder;
					if (!order) {
						detailNode.innerHTML = `<div class="${emptyDetailClass}">Choose an order from the left to view the customer address, items, and fulfilment controls.</div>`;
						return;
					}

					const addressParts = [order.addressLine1, order.addressLine2, order.city, order.region, order.postalCode, order.country]
						.filter(Boolean)
						.map((part) => `<span>${escapeHtml(part)}</span>`)
						.join("");
					const itemsMarkup = (order.items || [])
						.map((item) => {
							const colorway = colorwayMap.get(item.colorwayId);
							const finishLabel = finishMap.get(item.finishId) || item.finishId;
							return `<li><strong>${escapeHtml(colorway?.name || item.colorwayId)}</strong><span>${escapeHtml(item.style)} · ${escapeHtml(finishLabel)} · ${Number(item.quantity || 0)} × ${formatGBP(item.unitAmount)}</span></li>`;
						})
						.join("");

					detailNode.innerHTML = `
						<article class="${detailPanelClass}">
							<div class="${orderCardHeaderClass}">
								<div>
									<p class="${orderTitleClass}">${escapeHtml(order.firstName)} ${escapeHtml(order.lastName)}</p>
									<p class="${orderSubtitleClass}">${escapeHtml(order.email)}${order.phone ? ` · ${escapeHtml(order.phone)}` : ""}</p>
								</div>
								<span class="${orderBadgeClass}" data-status="${escapeHtml(order.fulfillmentStatus)}">${escapeHtml(order.fulfillmentStatus)}</span>
							</div>

							<section class="${detailSectionClass}">
								<div class="${detailCalloutClass}">
									<div>
										<span>Customer note</span>
										<strong>${escapeHtml(order.notes || "No customer note saved.")}</strong>
									</div>
									<div>
										<span>Tracking</span>
										<strong>${escapeHtml(order.trackingNumber || "Not attached yet")}</strong>
									</div>
								</div>
							</section>

							<section class="${detailSectionClass}">
								<div class="${detailGridClass}">
									<div><span>Order ID</span><strong>${escapeHtml(order.id)}</strong></div>
									<div><span>Payment</span><strong>${escapeHtml(order.status)}</strong></div>
									<div><span>Total</span><strong>${formatGBP(order.amount)}</strong></div>
									<div><span>Webhook</span><strong>${escapeHtml(order.webhookStatus || "awaiting_webhook")}</strong></div>
									<div><span>Created</span><strong>${formatDateTime(order.createdAt)}</strong></div>
									<div><span>Shipped</span><strong>${formatDateTime(order.shippedAt)}</strong></div>
								</div>
							</section>

							<section class="${detailSectionClass}">
								<div class="${detailSubgridClass}">
									<div class="${detailAddressClass}">
										<p class="${sectionKickerClass}">Shipping address</p>
										${addressParts || "<span>No shipping address saved.</span>"}
									</div>
									<div class="${detailAddressClass}">
										<p class="${sectionKickerClass}">Shipping snapshot</p>
										<span>Carrier: ${escapeHtml(order.shippingCarrier || "Not set")}</span>
										<span>Tracking: ${escapeHtml(order.trackingNumber || "Not attached yet")}</span>
										<span>Updated: ${formatDateTime(order.updatedAt)}</span>
									</div>
								</div>
							</section>

							<section class="${detailSectionClass}">
								<p class="${sectionKickerClass}">Items</p>
								<ul class="${detailItemsClass}">${itemsMarkup || "<li>No line items found.</li>"}</ul>
							</section>

							<form class="${detailFormClass}" data-order-update-form>
								<label class="${selectFieldClass}">
									<span>Fulfilment status</span>
									<select name="fulfillmentStatus">
										${(fulfillmentStatuses || []).map((status) => `<option value="${escapeHtml(status)}" ${status === order.fulfillmentStatus ? "selected" : ""}>${escapeHtml(status)}</option>`).join("")}
									</select>
								</label>

								<label class="${fieldClass}">
									<span>Shipping carrier</span>
									<input type="text" name="shippingCarrier" value="${escapeHtml(order.shippingCarrier || "")}" placeholder="Royal Mail, DHL, UPS…" />
								</label>

								<label class="${fieldClass}">
									<span>Tracking number</span>
									<input type="text" name="trackingNumber" value="${escapeHtml(order.trackingNumber || "")}" placeholder="Add the client-facing tracking reference" />
								</label>

								<label class="${textareaFieldClass}">
									<span>Internal fulfilment notes</span>
									<textarea name="fulfillmentNotes" rows="4" placeholder="Packing notes, dispatch details, customer follow-up…">${escapeHtml(order.fulfillmentNotes || "")}</textarea>
								</label>

								<div class="${detailFormFooterClass}">
									<p class="${searchHintClass}">Saving here updates the local dashboard backend immediately.</p>
									<button type="submit" class="${primaryCtaClass}">Save fulfilment update</button>
								</div>
							</form>
						</article>
					`;

					const updateForm = detailNode.querySelector("[data-order-update-form]");
					updateForm?.addEventListener("submit", async (event) => {
						event.preventDefault();
						const formData = new FormData(updateForm);
						const nextStatus = String(formData.get("fulfillmentStatus") || "").trim();
						const currentlyShipped = Boolean(order.shippedAt);
						const shouldMarkShippedNow = nextStatus === "shipped" && !currentlyShipped;
						const shouldClearShippedAt = currentlyShipped && !["shipped", "delivered"].includes(nextStatus);

						setFeedback(detailFeedback, `Saving ${order.id}…`, "info");

						try {
							const response = await fetch(`${normalizedApiBaseUrl}/v1/client/orders/${encodeURIComponent(order.id)}`, {
								method: "PATCH",
								credentials: "include",
								headers: { "Content-Type": "application/json" },
								body: JSON.stringify({
									fulfillmentStatus: nextStatus,
									shippingCarrier: String(formData.get("shippingCarrier") || ""),
									trackingNumber: String(formData.get("trackingNumber") || ""),
									fulfillmentNotes: String(formData.get("fulfillmentNotes") || ""),
									markShippedAtNow: shouldMarkShippedNow,
									clearShippedAt: shouldClearShippedAt,
								}),
							});

							const payload = await response.json().catch(() => null);
							if (!response.ok) {
								throw new Error(payload?.error?.message || "The order update could not be saved.");
							}

							state.selectedOrder = payload?.data?.order || null;
							setFeedback(detailFeedback, `Saved fulfilment update for ${order.id}.`, "success");
							await loadOrders(order.id, false);
							if (state.selectedOrder) renderDetail();
						} catch (error) {
							setFeedback(detailFeedback, error instanceof Error ? error.message : "The order update could not be saved.", "error");
						}
					});
				};

				const loadOrderDetail = async (orderID) => {
					state.selectedOrderId = orderID;
					renderResults();
					setFeedback(detailFeedback, `Loading ${orderID}…`, "info");
					try {
						const response = await fetch(`${normalizedApiBaseUrl}/v1/client/orders/${encodeURIComponent(orderID)}`, {
							credentials: "include",
						});
						const payload = await response.json().catch(() => null);
						if (!response.ok) {
							throw new Error(payload?.error?.message || "The order details could not be loaded.");
						}
						state.selectedOrder = payload?.data?.order || null;
						renderDetail();
						setFeedback(detailFeedback, `Viewing ${orderID}.`, "success");
					} catch (error) {
						state.selectedOrder = null;
						renderDetail();
						setFeedback(detailFeedback, error instanceof Error ? error.message : "The order details could not be loaded.", "error");
					}
				};

				const loadOrders = async (preferredOrderID = "", preserveDetail = true) => {
					setFeedback(ordersFeedback, "Loading orders…", "info");
					const params = new URLSearchParams({ limit: "100" });
					if (state.filters.search) params.set("search", state.filters.search);
					if (state.filters.status) params.set("status", state.filters.status);

					const response = await fetch(`${normalizedApiBaseUrl}/v1/client/orders?${params.toString()}`, {
						credentials: "include",
					});
					const payload = await response.json().catch(() => null);
					if (!response.ok) {
						throw new Error(payload?.error?.message || "The orders list could not be loaded.");
					}

					state.orders = payload?.data?.orders || [];
					const nextSelected = preferredOrderID || state.selectedOrderId || state.orders[0]?.id || "";
					state.selectedOrderId = nextSelected;
					renderResults();

					if (!nextSelected) {
						state.selectedOrder = null;
						renderDetail();
						setFeedback(ordersFeedback, "No orders matched the current filters.", "info");
						return;
					}

					if (preserveDetail && state.selectedOrder?.id === nextSelected) {
						renderDetail();
						setFeedback(ordersFeedback, "Orders list refreshed.", "success");
						return;
					}

					await loadOrderDetail(nextSelected);
					setFeedback(ordersFeedback, "Orders loaded.", "success");
				};

				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 orders access.", session?.configured === false ? "error" : "info");
							return;
						}

						if (!session.authenticated) {
							setAuthenticatedUi(false);
							setFeedback(authFeedback, "Sign in to search and update customer orders.", "info");
							return;
						}

						setAuthenticatedUi(true, session.username);
						await loadOrders();
					} catch (error) {
						setAuthenticatedUi(false);
						setFeedback(authFeedback, error instanceof Error ? error.message : "Unable to verify orders 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 orders credentials were rejected.");
						}
						loginForm.reset();
						setFeedback(authFeedback, "Access granted. Loading orders…", "success");
						await syncSession();
					} catch (error) {
						setFeedback(authFeedback, error instanceof Error ? error.message : "The orders credentials were rejected.", "error");
					} finally {
						if (loginSubmit) {
							loginSubmit.disabled = false;
							loginSubmit.textContent = "Unlock orders";
						}
					}
				});

				searchForm?.addEventListener("submit", async (event) => {
					event.preventDefault();
					const formData = new FormData(searchForm);
					state.filters.search = String(formData.get("search") || "").trim();
					state.filters.status = String(formData.get("status") || "").trim();
					try {
						await loadOrders();
					} catch (error) {
						setFeedback(ordersFeedback, error instanceof Error ? error.message : "The orders list could not be loaded.", "error");
					}
				});

				resetButton?.addEventListener("click", async () => {
					if (searchForm instanceof HTMLFormElement) {
						searchForm.reset();
					}
					state.filters.search = "";
					state.filters.status = "";
					try {
						await loadOrders();
					} catch (error) {
						setFeedback(ordersFeedback, error instanceof Error ? error.message : "The orders list could not be loaded.", "error");
					}
				});

				logoutButton?.addEventListener("click", async () => {
					await fetch(`${normalizedApiBaseUrl}/v1/client/logout`, {
						method: "POST",
						credentials: "include",
					});
					state.orders = [];
					state.selectedOrder = null;
					state.selectedOrderId = "";
					setAuthenticatedUi(false);
					renderResults();
					renderDetail();
					setFeedback(authFeedback, "Signed out. Sign in again to reopen the orders console.", "info");
				});

				renderDetail();
				syncSession();
			};

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