const app = document.querySelector("#app");
const toasts = document.querySelector("#toast-region");
const ui = {
data: null,
detail: null,
menuOpen: false,
locationOpen: false,
filterOpen: false,
modal: null,
authTab: "signin",
localCode: "",
page: 0,
limit: 30,
busy: false,
loadError: "",
};
const money = (cents) => new Intl.NumberFormat("en-US", {
style: "currency", currency: "USD"
}).format((cents || 0) / 100);
const price = (value) => new Intl.NumberFormat("en-US", {
style: "currency", currency: "USD"
}).format(value || 0);
const esc = (value = "") => String(value).replace(/[&<>"']/g, (char) => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'"
}[char]));
const slugify = (value) => String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
function icon(name, label = "") {
const paths = {
menu: ' ',
search: ' ',
user: ' ',
cart: ' ',
location: ' ',
heart: ' ',
list: ' ',
store: ' ',
close: ' ',
filter: ' ',
arrow: ' ',
check: ' ',
minus: ' ',
plus: ' ',
info: ' ',
};
return `${paths[name] || paths.info} `;
}
function toast(message, error = false) {
const node = document.createElement("div");
node.className = `toast${error ? " error" : ""}`;
node.textContent = message;
toasts.append(node);
setTimeout(() => node.remove(), 3500);
}
async function api(path, options = {}) {
const response = await fetch(path, {
headers: {"Content-Type": "application/json", ...(options.headers || {})},
...options,
});
const body = await response.json().catch(() => ({}));
if (!response.ok) {
const error = new Error(body.detail || `Request failed (${response.status})`);
error.status = response.status;
throw error;
}
return body;
}
function route() {
const path = location.pathname;
const params = new URLSearchParams(location.search);
if (path === "/") return {name: "home", params};
if (path === "/search") return {name: "catalog", params};
if (params.get("_q") && params.get("map") === "ft" && path.split("/").filter(Boolean).length === 1) {
return {name: "catalog", params};
}
if (path.startsWith("/category/")) return {
name: "catalog", category: decodeURIComponent(path.slice(10)), params
};
if (path.endsWith("/p")) return {name: "detail", slug: path.split("/").filter(Boolean)[0], params};
if (path === "/cart") return {name: "cart", params};
if (path === "/checkout") return {name: "checkout", params};
if (path === "/favorites") return {name: "favorites", params};
if (path === "/orders") return {name: "orders", params};
if (path.startsWith("/orders/")) {
const orderId = path.slice(8);
if (orderId && !orderId.includes("/")) return {
name: "order-details", orderId: decodeURIComponent(orderId), params
};
}
if (path === "/support") return {name: "support", params};
if (path === "/account/registration") return {name: "account", section: "registration", params};
if (path === "/account/recovery") return {name: "account", section: "recovery", params};
return {name: "not-found", params};
}
function sourceSearchUrl(value) {
const query = String(value || "").trim();
if (!query) return "/search";
return `/${encodeURIComponent(slugify(query) || "search")}?_q=${encodeURIComponent(query)}&map=ft`;
}
function go(url) {
history.pushState({}, "", url);
ui.page = 0;
ui.detail = null;
ui.orderDetail = null;
window.scrollTo({top: 0});
load();
}
function logo() {
return 'H MART ';
}
function header() {
const count = ui.data?.cart?.item_count || 0;
const account = ui.data?.session?.account;
const query = route().params.get("_q") || route().params.get("q") || "";
const categoryLinks = (ui.data?.categories || []).slice(0, 15).map((row) =>
`
${esc(row.category)} (${row.count}) `
).join("");
return `
`;
}
function locationPanel() {
const compact = window.matchMedia("(max-width: 720px)").matches;
const compactHome = compact && route().name === "home";
if (!ui.data || (!ui.locationOpen && (ui.data.state.postal_code || compactHome))) return "";
return `
Offers and delivery options vary based on region.
I don't know my postal code
`;
}
const infoLinks = {
"GET TO KNOW US": ["About Us", "Founder's Greeting", "Mission", "History", "Community", "Our Story"],
"H MART STORES": ["Weekly Sales & Events", "Locations & Hours", "Smart Rewards Card", "Store FAQ", "Store Tenant", "Careers", "Health Benefit Card"],
"H MART.COM": ["Online Order Delivery", "Online FAQ", "Privacy Notice", "Privacy Notice for California Employees Only", "Conditions of Use", "Do Not Sell My Personal Information"],
};
function footer() {
return ``;
}
function image(product, className = "") {
return product.image
? ` `
: `
Product image coming soon ${esc(product.brand)}
`;
}
function productCard(product) {
const discount = product.list_price > product.price && product.list_price
? Math.round((1 - product.price / product.list_price) * 100) : 0;
const favorite = ui.data.favorite_product_ids.includes(product.product_id);
return `
${discount ? `-${discount}% ` : ""}
${icon("list")}
${image(product)}
${price(product.price)}
${discount ? `${price(product.list_price)} ` : ""}
${esc(product.brand)}
${esc(product.name)}
${ui.data.state.postal_code ? `
${product.available ? "Available for selected region" : "Unavailable"}
${product.available ? "Add to Cart" : "Unavailable"} ` : `Set location to check availability `}
`;
}
function productGrid(products, extraClass = "") {
return ``;
}
function home() {
const products = ui.data.products;
const quick = ["Best Sellers", "Stationery", "Toys", "Meat & Poultry", "Wellness", "Ramen & Noodles", "Side Dishes", "Produce"];
const sections = [
["Recommended For You", products.slice(0, 5)],
["New Arrivals", products.slice(5, 10)],
["Hot Picks & Best Sellers", products.slice(10, 15)],
["Home & Lifestyle", products.slice(15, 20)],
["Side Dishes(Banchan)", products.slice(20, 25)],
["Japanese", products.slice(25, 30)],
];
return `H Mart online grocery
${icon("minus")}
01 / 06 ${icon("arrow")}
${quick.map((label, index) => `
${icon(index % 2 ? "store" : "cart")} ${esc(label)} `).join("")}
Recommended For You Explore 240 grocery and pantry essentials
${["Weekly Sale","Korea Direct","Fresh Produce","Flash Sale","Kitchenware","Characters"].map((label, index) =>
`${label} `
).join("")}
${productGrid(products.slice(0, 5), "home-grid")}
${sections.slice(1).map(([title, items]) => `
${title} See all
${productGrid(items, "home-grid")} `).join("")}
Recipes We Love
Weeknight rice bowls
Browse rice, sauces, seaweed, and quick side dishes.
Explore ingredients
`;
}
function filterPanel() {
const activeCategory = route().category || route().params.get("category") || "";
const activeBrand = route().params.get("brand") || "";
const activeCountry = route().params.get("country") || "";
const activeStorage = route().params.get("storage") || "";
return ``;
}
function catalog() {
const r = route();
const query = r.params.get("_q") || r.params.get("q") || "";
const rawTitle = r.category || query || (r.params.get("sale") === "1" ? "Sale" : "All Products");
const title = rawTitle ? rawTitle.charAt(0).toUpperCase() + rawTitle.slice(1) : rawTitle;
const displayTotal = ui.data.product_total;
const start = ui.page * ui.limit + 1;
const end = Math.min(displayTotal, start + ui.data.products.length - 1);
const pages = Math.max(1, Math.ceil(displayTotal / ui.limit));
return `
${filterPanel()}
${icon("filter")} Filter
Items ${ui.data.product_total ? start : 0}-${end} of ${displayTotal}
Sort by:
${[
["best-sellers","Best Sellers"],["newest","New"],["price-high","Price: high to low"],
["price-low","Price: low to high"],["name","Product name"]
].map(([value, label]) => `${label} `).join("")}
${ui.data.products.length ? productGrid(ui.data.products) : `
We couldn't find a match for “${esc(query || r.category || "this selection")}”
Try another search or browse all available products.
Browse all products
Return home
`}
`;
}
function detail() {
const product = ui.detail;
if (!product) return 'Loading product details
';
if (product.missing) return notFound();
const selected = product.variants.find((variant) => variant.variant_id === product.selected_variant_id)
|| product.variants.find((variant) => variant.is_default) || product.variants[0];
const discount = selected.list_price > selected.price;
return `
Home › ${esc(product.category)} › ${esc(product.name)}
${esc(product.brand)} ${esc(product.name)}
${price(selected.price)}
${discount ? `${price(selected.list_price)} ` : ""}
Pack option
${product.variants.map((variant) => `
${esc(variant.label)} — ${price(variant.price)}${variant.available ? "" : " (unavailable)"} `).join("")}
${ui.data.state.postal_code ? `
${selected.available ? `In stock for ${esc(ui.data.location.name)}` : "Unavailable for selected region"}
${esc(product.description || "Product details are available in the local catalog.")}
Quantity
${Array.from({length: Math.min(12, product.max_per_order)}, (_, index) => `${index + 1} `).join("")}
Add to Cart
${icon("list")} ${product.in_favorites ? "Remove from favorites" : "Save to favorites"} ` : `Set location to check availability `}
More Details
Brand ${esc(product.brand)}
Product Name ${esc(product.name)}
SKU ${esc(product.product_id)}
Storage ${esc(product.storage || "Dry")}
Country ${esc(product.country || "Not specified")}
Reviews
No customer reviews are available for this item.
Please log in to write a review.
`;
}
function cartSummary(cart) {
return `Subtotal ${money(cart.subtotal_cents)}
Discounts -${money(cart.discount_cents)}
Fulfillment fee ${money(cart.fulfillment_fee_cents)}
Estimated total ${money(cart.total_cents)}
`;
}
const slotLabels = {
"standard-3-5": "Standard shipping · 3–5 days",
"today-6-8": "Today · 6–8 PM",
"tomorrow-10-12": "Tomorrow · 10 AM–12 PM",
"today-5-6": "Today · 5–6 PM",
"tomorrow-9-10": "Tomorrow · 9–10 AM",
};
function fulfillmentControls() {
if (!ui.data.state.postal_code) return `Set a location to choose fulfillment `;
const method = ui.data.state.fulfillment;
const slots = ui.data.location.slots[method] || [];
return `Fulfillment
${ui.data.location.fulfillment.map((value) => `
${esc(value.charAt(0).toUpperCase() + value.slice(1))} `).join("")}
Time slot
${slots.map((value) => `
${esc(slotLabels[value] || value)} `).join("")}
Availability and fees are local demo estimates for ${esc(ui.data.location.name)}.
`;
}
function cartPage() {
const cart = ui.data.cart;
if (!cart.items.length) return `Your Cart
Your cart is empty. Search the local H Mart catalog to begin.
Shop groceries `;
const hasUnavailable = cart.items.some((item) => !item.available);
return `Your Cart
${cart.items.map((item) => `
${image(item)}
${esc(item.brand)} · ${esc(item.variant_label)}
${item.available ? "" : '
Unavailable at the selected location
'}
Qty
${Array.from({length: Math.min(12, item.max_per_order)}, (_, i) => `${i + 1} `).join("")}
Local preference simulation (demo only)
Choose the closest available item
Refund this item
Use my specific choice
This is a local simulation saved on this device. The live H Mart replacement options could not be verified, and nothing is sent to H Mart.
Remove
${money(item.line_total_cents)} `).join("")}
`;
}
function checkoutPage() {
const cart = ui.data.cart;
if (!cart.items.length) return `
Add an item before checkout Browse products
`;
const address = ui.data.state.address || {};
const review = ui.data.state.checkout_step === "review";
return `Checkout Review
1 Address
2 Review
3 Place order
${fulfillmentControls()}
Service address
${review ? `
Review ready.
${esc(address.name)} ${esc(address.street)} ${esc(address.city)}, ${esc(address.region)} ${esc(address.postal_code)}
${esc(ui.data.state.fulfillment)} · ${esc(slotLabels[ui.data.state.fulfillment_slot] || ui.data.state.fulfillment_slot || "Select a slot")}
${cart.items.map((item) => `${esc(item.name)}
${esc(item.variant_label)} · Qty ${item.quantity} · ${money(item.line_total_cents)}
Substitution: ${esc({"best-match":"closest available item","refund":"refund this item","specific":"specific local choice"}[item.substitution] || item.substitution)} (local simulation only) `).join("")}
No order was submitted and no payment was attempted.
Place order (not available)
` : ""}
`;
}
function favoritesPage() {
if (!ui.data.session.account) return accountRequired("favorites");
const items = ui.data.products.filter((product) => ui.data.favorite_product_ids.includes(product.product_id));
return `Favorites
${items.length ? productGrid(items) : 'No favorites yet Save products to find them here.
'} `;
}
function accountRequired(feature) {
return `Sign in to view ${esc(feature)}
Your local demo account is available without any external service.
Log in / Sign up `;
}
function authForms() {
return {
signin: ``,
register: ``,
"register-verify": ``,
recovery: ``,
"recovery-code": ``,
"recovery-password": ``,
};
}
function accountPage() {
const account = ui.data.session.account;
if (account) return `
My Account Signed in as ${esc(account.display_name)} ${esc(account.email_normalized)}
Favorites
Order History
Help & Support
Sign out
`;
const title = route().section === "registration" ? "Create a local account" : "Recover a local account";
return `${title}
Registration and recovery deliver verification mail only to your injected trial inbox.
${authForms()[ui.authTab]}
`;
}
function ordersPage() {
if (!ui.data.session.account) return accountRequired("order history");
if (!ui.orders) return '
';
return `Order History
${ui.orders.map((order) => `
${esc(order.order_id)} ${esc(order.placed_at.slice(0, 10))} · ${esc(order.fulfillment)}
${esc(order.status)} ${money(order.total_cents)}
${order.items.map((item) => esc(item.name)).join(" · ")}
View order details
Reorder in local cart `).join("")}
`;
}
function orderDetailsPage() {
if (!ui.data.session.account) return accountRequired("order details");
const order = ui.orderDetail;
if (!order) return '
';
if (order.missing) return notFound();
return `← Order history
Order ${esc(order.order_id)}
${esc(order.status)} ${esc(order.placed_at.slice(0, 10))}
${money(order.total_cents)} ${esc(order.fulfillment)}
${order.items.map((item) => `${esc(item.name)}
Qty ${item.quantity} · ${money(item.price_cents * item.quantity)}
`).join("")}
Seeded local order details. No live H Mart order is represented.
Reorder available items
`;
}
function supportPage() {
if (!ui.data.session.account) return accountRequired("support history");
if (!ui.cases) return '
';
return `Help & Support
Local support cases ${ui.cases.map((item) => `
${esc(item.subject)} ${esc(item.detail)}
${esc(item.status)} `).join("")}
Start a local case No email or external message will be sent.
`;
}
function notFound() {
return `404
We couldn't find that page The address may have changed, but the H Mart catalog is still available.
Return to H Mart home
Browse all products
`;
}
function modal() {
if (!ui.modal) return "";
if (ui.modal.type === "info") return `
${icon("close")}
H Mart ${esc(ui.modal.message)}
Close
`;
const account = ui.data?.session?.account;
if (account) return `
${icon("close")}
My Account Signed in as ${esc(account.display_name)} ${esc(account.email_normalized)}
Favorites
Order History
Help & Support
Sign out
`;
const forms = authForms();
const activeTab = ui.authTab.startsWith("register") ? "register"
: ui.authTab.startsWith("recovery") ? "recovery" : "signin";
return `
${icon("close")} Log in / Sign up
${[["signin","Log in"],["register","Sign up"],["recovery","Recover"]].map(([id, label]) =>
`${label} `).join("")}
${forms[ui.authTab]} `;
}
function render() {
const r = route();
document.body.dataset.route = r.name;
const body = ui.loadError
? `H Mart is temporarily unavailable
${esc(ui.loadError)}
Try again `
: !ui.data ? 'Loading H Mart
' : ({
home, catalog, detail, cart: cartPage, checkout: checkoutPage, account: accountPage,
favorites: favoritesPage, orders: ordersPage, support: supportPage,
"order-details": orderDetailsPage,
"not-found": notFound,
}[r.name] || notFound)();
app.innerHTML = `${header()}${locationPanel()}${body}${footer()}${modal()}`;
document.body.classList.toggle("modal-open", Boolean(ui.modal));
}
function paramsForBootstrap() {
const r = route();
const params = new URLSearchParams();
if (r.name === "catalog") {
if (r.params.get("_q") || r.params.get("q")) params.set("query", r.params.get("_q") || r.params.get("q"));
if (r.category) params.set("category", r.category);
if (r.params.get("brand")) params.set("brand", r.params.get("brand"));
if (r.params.get("country")) params.set("country", r.params.get("country"));
if (r.params.get("storage")) params.set("storage", r.params.get("storage"));
if (r.params.get("sale") === "1") params.set("on_sale", "true");
params.set("sort", r.params.get("sort") || "best-sellers");
params.set("offset", String(ui.page * ui.limit));
}
params.set("limit", r.name === "home" ? "30" : String(ui.limit));
return params;
}
async function load() {
ui.busy = true;
ui.loadError = "";
render();
try {
ui.data = await api(`/api/bootstrap?${paramsForBootstrap()}`);
const r = route();
if (r.name === "account" && !ui.data.session.account) {
const prefix = r.section === "registration" ? "register" : "recovery";
if (!ui.authTab.startsWith(prefix)) ui.authTab = prefix;
ui.modal = null;
}
if (r.name === "catalog" && (r.params.get("_q") || r.params.get("q") || "").toLowerCase() === "rice") {
const sourceOrder = ["4474", "72", "4473", "4494", "3410"];
const rank = new Map(sourceOrder.map((id, index) => [id, index]));
ui.data.products.sort((left, right) =>
(rank.get(left.product_id) ?? sourceOrder.length) - (rank.get(right.product_id) ?? sourceOrder.length)
);
}
if (r.name === "detail") {
try {
ui.detail = await api(`/api/products/${encodeURIComponent(r.slug)}`);
} catch (error) {
if (error.status === 404) ui.detail = {missing: true};
else throw error;
}
}
if (r.name === "orders" && ui.data.session.account) ui.orders = (await api("/api/orders")).orders;
if (r.name === "order-details" && ui.data.session.account) {
try {
ui.orderDetail = (await api(`/api/orders/${encodeURIComponent(r.orderId)}`)).order;
} catch (error) {
if (error.status === 404) ui.orderDetail = {missing: true};
else throw error;
}
}
if (r.name === "support" && ui.data.session.account) ui.cases = (await api("/api/support")).cases;
if (r.name === "favorites") {
const all = await api("/api/bootstrap?limit=240");
ui.data.products = all.products;
}
} catch (error) {
ui.loadError = error.message || "The local preview could not load this page.";
toast(error.message, true);
} finally {
ui.busy = false;
render();
}
}
document.addEventListener("click", async (event) => {
if (event.target instanceof Element && event.target.matches("[data-modal-backdrop]")) {
ui.modal = null;
render();
return;
}
const target = event.target.closest("a,button");
if (!target) return;
if (target.matches("[data-nav]")) { event.preventDefault(); go(target.getAttribute("href")); return; }
if (target.dataset.navUrl) { ui.modal = null; go(target.dataset.navUrl); return; }
if (target.dataset.retry !== undefined) { await load(); return; }
if (target.matches("[data-menu]")) {
ui.menuOpen = !ui.menuOpen;
render();
if (ui.menuOpen) document.querySelector(".category-menu a")?.focus();
return;
}
if (target.matches("[data-location]")) { ui.locationOpen = !ui.locationOpen; render(); return; }
if (target.matches("[data-account]")) { ui.modal = {type: "account"}; render(); return; }
if (target.matches("[data-modal-close]") || target.matches("[data-modal-backdrop]")) { ui.modal = null; render(); return; }
if (target.dataset.info) { ui.modal = {type: "info", message: target.dataset.info}; render(); return; }
if (target.dataset.search) { go(sourceSearchUrl(target.dataset.search)); return; }
if (target.dataset.filterOpen !== undefined) { ui.filterOpen = true; render(); return; }
if (target.dataset.filterClose !== undefined) { ui.filterOpen = false; render(); return; }
if (target.dataset.clearFilters !== undefined) { go("/search"); return; }
if (target.dataset.page) { ui.page = Number(target.dataset.page); await load(); return; }
if (target.dataset.authTab) { ui.authTab = target.dataset.authTab; render(); return; }
if (target.dataset.prohibitedSubmit !== undefined) { toast("Stopped before order submission. No external effect occurred."); return; }
try {
if (target.dataset.add) {
const quantity = target.dataset.detailAdd !== undefined
? Number(document.querySelector("#detail-quantity")?.value || 1) : 1;
const variantId = target.dataset.detailAdd !== undefined
? document.querySelector("#detail-variant")?.value : undefined;
const cart = await api(`/api/cart/${target.dataset.add}`, {
method: "POST", body: JSON.stringify({quantity, variant_id: variantId})
});
ui.data.cart = cart;
toast("Item added to your cart");
render();
return;
}
if (target.dataset.favorite) {
try {
await api(`/api/favorites/${target.dataset.favorite}`, {method: "POST"});
await load();
} catch (error) {
if (error.status === 401) { ui.modal = {type: "account"}; render(); }
else throw error;
}
return;
}
if (target.dataset.remove) {
ui.data.cart = await api(`/api/cart/${target.dataset.remove}`, {method: "DELETE"});
render(); return;
}
if (target.dataset.reorder) {
const result = await api(`/api/orders/${target.dataset.reorder}/reorder`, {method: "POST"});
ui.data.cart = result;
const skipped = result.skipped_items.length;
toast(skipped ? `Available items added; ${skipped} unavailable item${skipped === 1 ? " was" : "s were"} skipped` : "Order items added to your local cart");
go("/cart"); return;
}
if (target.dataset.signOut !== undefined) {
await api("/api/auth/sign-out", {method: "POST"});
ui.authTab = "signin"; ui.localCode = ""; ui.modal = null;
ui.orders = null; ui.cases = null; await load(); return;
}
} catch (error) { toast(error.message, true); }
});
document.addEventListener("submit", async (event) => {
const form = event.target;
event.preventDefault();
const values = Object.fromEntries(new FormData(form));
try {
if (form.matches("[data-search-form]")) {
const query = String(values.q || "").trim();
go(sourceSearchUrl(query));
} else if (form.matches("[data-location-form]")) {
const postalCode = String(values.postal_code || "").trim();
const postalInput = form.querySelector('[name="postal_code"]');
const error = form.querySelector("[data-location-error]");
if (!/^[0-9]{5}(?:-[0-9]{4})?$/.test(postalCode)) {
postalInput.setAttribute("aria-invalid", "true");
error.textContent = "Enter a valid US postal code, such as 10001.";
postalInput.focus();
return;
}
postalInput.removeAttribute("aria-invalid");
error.textContent = "";
await api("/api/location", {method: "PUT", body: JSON.stringify({postal_code: postalCode, fulfillment: "shipping"})});
ui.locationOpen = false; toast("Location set for local availability"); await load();
} else if (form.matches("[data-coupon-form]")) {
ui.data.cart = await api("/api/coupon", {method: "POST", body: JSON.stringify(values)});
toast("Coupon applied"); render();
} else if (form.matches("[data-checkout-form]")) {
if (!form.checkValidity()) {
form.reportValidity();
form.querySelectorAll(":invalid").forEach((field) => {
const validation = field.parentElement.querySelector(".validation");
if (validation) validation.textContent = field.validationMessage;
});
return;
}
const result = await api("/api/checkout/review", {method: "POST", body: JSON.stringify(values)});
ui.data.state.address = result.address; ui.data.state.checkout_step = "review";
toast(result.safe_stop); render();
} else if (form.dataset.authForm) {
const kind = form.dataset.authForm;
const endpoint = {
signin: "sign-in", register: "register", "register-verify": "register/verify",
recovery: "recovery", "recovery-code": "recovery/verify",
"recovery-password": "recovery/complete",
}[kind];
const result = await api(`/api/auth/${endpoint}`, {
method: "POST", body: JSON.stringify(values)
});
if (kind === "signin") {
ui.modal = null; toast("Signed in to the local H Mart account"); await load();
} else if (kind === "register") {
ui.localCode = "";
ui.authTab = "register-verify"; toast("Read the code from the trial browser inbox"); render();
} else if (kind === "register-verify") {
ui.localCode = ""; ui.modal = null; toast("Local account registration completed"); await load();
} else if (kind === "recovery") {
ui.localCode = "";
ui.authTab = "recovery-code"; toast(result.message || "Read the local reset code"); render();
} else if (kind === "recovery-code") {
ui.localCode = ""; ui.authTab = "recovery-password"; toast("Reset code verified"); render();
} else if (kind === "recovery-password") {
ui.modal = null; toast("Password replaced; older sessions were revoked"); await load();
} else {
toast(result.message || "Local-only request accepted");
}
} else if (form.matches("[data-support-form]")) {
await api("/api/support", {method: "POST", body: JSON.stringify(values)});
toast("Local support case created; no message was sent");
ui.cases = (await api("/api/support")).cases; render();
}
} catch (error) { toast(error.message, true); }
});
document.addEventListener("change", async (event) => {
const target = event.target;
const r = route();
try {
if (target.id === "sort-select") {
const params = new URLSearchParams(location.search); params.set("sort", target.value);
go(`${location.pathname}?${params}`);
} else if (["category", "brand", "country", "storage"].includes(target.name)) {
const params = new URLSearchParams(location.search);
if (target.name === "category") {
params.delete("category"); go(`/category/${encodeURIComponent(target.value)}?${params}`);
} else {
params.set(target.name, target.value); go(`${location.pathname}?${params}`);
}
} else if (target.id === "sale-filter") {
const params = new URLSearchParams(location.search);
target.checked ? params.set("sale", "1") : params.delete("sale");
go(`${location.pathname}?${params}`);
} else if (target.dataset.substitution) {
ui.data.cart = await api(`/api/cart/${target.dataset.substitution}`, {
method: "PATCH", body: JSON.stringify({substitution: target.value})
});
toast("Local preference simulation saved on this device"); render();
} else if (target.dataset.detailVariant !== undefined) {
ui.detail.selected_variant_id = target.value;
render();
} else if (target.name === "fulfillment") {
await api("/api/location", {method: "PUT", body: JSON.stringify({
postal_code: ui.data.state.postal_code, fulfillment: target.value
})});
toast("Fulfillment method updated"); await load();
} else if (target.id === "fulfillment-slot") {
await api("/api/location", {method: "PUT", body: JSON.stringify({
postal_code: ui.data.state.postal_code,
fulfillment: ui.data.state.fulfillment,
slot: target.value,
})});
toast("Fulfillment time updated"); await load();
} else if (target.dataset.cartQty) {
ui.data.cart = await api(`/api/cart/${target.dataset.cartQty}`, {
method: "PATCH", body: JSON.stringify({quantity: Number(target.value)})
}); render();
}
} catch (error) { toast(error.message, true); }
});
window.addEventListener("popstate", () => { ui.detail = null; ui.page = 0; load(); });
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
if (ui.menuOpen) {
ui.menuOpen = false;
render();
document.querySelector('[data-menu][aria-label="Open navigation"]')?.focus();
} else if (ui.modal) {
ui.modal = null;
render();
}
});
load();