<p id="status">Loading your cart…</p>

<script>
(async function () {
  // Map your Meta Content IDs to Squarespace IDs.
  // itemId = the product's internal ID; sku = the variant SKU.
  const CATALOG = {
    "BLANKET-NAVY":  { itemId: "PASTE_ITEM_ID_HERE", sku: "BLANKET-NAVY" },
    "YOGA-SHORTS-M": { itemId: "PASTE_ITEM_ID_HERE", sku: "YOGA-SHORTS-M" }
  };

  const params = new URLSearchParams(window.location.search);
  const products = (params.get("products") || "").split(",").filter(Boolean);
  const coupon = params.get("coupon");
  const status = document.getElementById("status");

  const crumb = (document.cookie.match(/(?:^|;\s*)crumb=([^;]+)/) || [])[1];

  try {
    for (const entry of products) {
      const [id, qty] = entry.split(":");
      const item = CATALOG[id];
      if (!item) { console.warn("Unknown product ID:", id); continue; }

      const res = await fetch("/api/commerce/shopping-cart/add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-Token": crumb || ""
        },
        body: JSON.stringify({
          itemId: item.itemId,
          sku: item.sku,
          quantity: parseInt(qty, 10) || 1,
          additionalFields: "[]"
        })
      });
      if (!res.ok) throw new Error("Add to cart failed for " + id);
    }
    // Squarespace has no coupon URL parameter, so the shopper
    // enters the code at checkout.
    window.location.href = "/cart";
  } catch (err) {
    console.error(err);
    status.textContent = "Something went wrong. Redirecting to the shop…";
    setTimeout(() => (window.location.href = "/shop"), 2000);
  }
})();
</script>