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AAMkgB,EAASxmB,SAASC,cAAc,UACtCumB,EAAOlqB,MAAQuU,EAAQhT,QAAQ8M,GAC/B6b,EAAO7mB,YAAckR,EAAQhT,QAAQkC,MAEH,SAA9B8Q,EAAQhT,QAAQ6e,YAClB8J,EAAO7mB,aAAe,kBACtB6mB,EAAOpR,SAAWmR,GAGhB1V,EAAQhT,QAAQ8M,KAAOqb,IACzBQ,EAAOvH,UAAW,GAGpBqH,EAAO7lB,YAAY+lB,EACrB,CAEA,OAAOlgB,EAAS5F,MAClB,CAMA,SAAS6hB,EAAwBkE,EAAuBvb,EACtDgB,GACA,MAAM2W,EAAU4D,EAAI/mB,cAAc,UAClCmjB,EAAQhlB,QAAQiO,WAAaZ,EAAeP,GAC5CkY,EAAQhY,aAAa,aAAc,cAAcK,EAAerN,QAAQkC,SAExE,MAAM4a,EAAeC,EAAqBiI,EAAS3X,EAAgBgB,GAAW,GAC9E2W,EAAQjjB,OAAS+a,EAAe,CAClC,CAiEA,SAASxI,EAAcuE,EAAyBxK,GAC9CgG,EAAoBwE,GAEpB,MAAMgQ,EAAkBra,EAAqBqK,EAASxK,GAClDwa,IACFA,EAAgB7oB,QAAQohB,SAAW,OACnCvI,EAAQ7Y,QAAQmoB,kBAAoBU,EAAgB7oB,QAAQ8M,GAEhE,CAKA,SAASuM,EAAgBrG,GACvB,OAAOA,EAAQ6L,SACjB,CAyKK/Z,eAAeC,IAAI,mBACtBD,eAAeE,OAAO,iBAAkBwD","sources":["webpack://lange/../node_modules/@integrabeauty/assert/src/index.ts","webpack://lange/./lib/decorate-error.ts","webpack://lange/./sections/yotpo-product-reviews/yotpo-ai-summary-simple/index.ts","webpack://lange/./sections/yotpo-product-reviews/yotpo-fetch-reviews-summary.ts","webpack://lange/../node_modules/@integrabeauty/cookie/src/index.ts","webpack://lange/../node_modules/uuid/dist/rng.js","webpack://lange/../node_modules/uuid/dist/stringify.js","webpack://lange/../node_modules/uuid/dist/v4.js","webpack://lange/./sections/bundle-builder-element/bundle-builder/promo.ts","webpack://lange/./sections/bundle-builder-element/bundle-builder/index.ts"],"sourcesContent":["/**\n * Throws an assertion error if the given condition is falsy.\n *\n * @param expression any expression, although one that evaluates to true or false is preferred by\n * convention\n * @param message optional error text\n */\nexport function assert(expression: unknown, message?: string) {\n  if (!expression) {\n    throw new AssertionError(message);\n  }\n}\n\nexport class AssertionError extends Error {\n  constructor(message = 'Assertion error') {\n    super(message);\n    this.name = this.constructor.name;\n  }\n}\n","/**\n * Copies a single piece of supplementary context onto an error before it is thrown or reported.\n *\n * Use this when decorating a value the calling code did not construct, such as a caught value or an\n * error handed in by another module. An error the caller just built with new is always writable, so\n * plain assignment is fine there. A value from elsewhere may be a foreign object this code does not\n * own. Such a value can carry a non-writable property, such as a DOMException whose code is a read-\n * only accessor, or be frozen outright, and assigning to it then throws. Attaching context must\n * never itself fail, so a rejected assignment is swallowed and the remaining context is still\n * attempted. Guarding each property in isolation means a single read-only slot, the common case,\n * costs only that one property rather than all of them.\n *\n * In practice the value that triggers this is almost always a DOMException that reached the caller\n * from a fetch the browser cut short, such as an abort when an in-flight request is interrupted.\n * The platform defines a DOMException's code, name, and message as read-only attributes, so\n * assigning a code onto one throws under the strict mode that all bundled module code runs in. It\n * surfaces from Safari far more than elsewhere for two reasons. The reported wording, attempted to\n * assign to readonly property, is JavaScriptCore's phrasing for this failure, so the same bug in\n * another engine is worded differently and groups as a separate report, which makes this one look\n * Safari specific even though the read-only rule is not. And iOS Safari abandons in-flight fetches\n * aggressively when a tab is backgrounded or a connection drops, which is when such a DOMException\n * tends to be produced and handed to code that assumed an ordinary writable error.\n *\n * A swallowed failure is logged at a level low enough that it is recorded as a breadcrumb for\n * monitoring rather than escalated into its own captured event. That keeps the lost context visible\n * alongside the eventual report without adding fresh noise of its own. The breadcrumb names the\n * property that could not be attached, the kind of value that rejected it, and why, which is enough\n * to recognize a read-only or frozen caught value after the fact.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Read-only\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n * @see https://webidl.spec.whatwg.org/#dfn-read-only\n */\nexport function decorateError(error: any, key: string, value: unknown) {\n  try {\n    error[key] = value;\n  } catch (assignmentError) {\n    let reason: string;\n    if (assignmentError instanceof Error) {\n      reason = assignmentError.message;\n    } else {\n      reason = `${assignmentError}`;\n    }\n\n    console.log('Failed to assign error property', {\n      key,\n      name: error?.name,\n      tag: Object.prototype.toString.call(error),\n      reason\n    });\n  }\n}\n","import type { CustomElement } from '@integrabeauty/custom-elements';\nimport { fetchReviewsSummary, type SummaryHighlight, type SummaryTopic } from '../yotpo-fetch-reviews-summary.js';\nimport html from './index.html';\nimport styles from './index.scss';\n\n/**\n * Renders Yotpo's AI summary for a product as plain copy, with nothing to click and no drawer. This\n * is the read-only counterpart to `yotpo-ai-summary`, for places where a second modal on top of\n * whatever is already open would not work, such as inside the bundle builder's product details\n * modal.\n *\n * The \"Reviews summary\" heading is always there. Under it, a loading line stays up until the\n * summary comes back, then either the summary or, when the product has none or the request failed,\n * a line saying so.\n *\n * @see https://support.yotpo.com/docs/adding-the-reviews-summary\n */\nclass YotpoAiSummarySimple extends HTMLElement implements CustomElement {\n  declare readonly dataset: {\n    /**\n     * The product id, which could be a product sku, with which this element is associated.\n     */\n    productId: string;\n\n    /**\n     * The api key used to send requests to the Yotpo reviews API.\n     */\n    yotpoAppKey: string;\n  };\n\n  /**\n   * Whether this element started to fetch results.\n   */\n  private fetchStarted = false;\n\n  public connectedCallback() {\n    this.initializeShadowRoot();\n\n    this.startFetching().catch(error => {\n      // The Load failed error is a routinely occurring networking error that we are not interested\n      // in tracing. It has moderate frequency and is outside of our control.\n\n      if (error instanceof Error && error.message === 'Load failed') {\n        console.log(error);\n      } else {\n        console.warn(error);\n      }\n\n      // A failed request shows the no-summary line, so the loading line does not stay up.\n      this.render('', [], []);\n    });\n  }\n\n  private initializeShadowRoot() {\n    if (!this.shadowRoot) {\n      this.attachShadow({ mode: 'open' });\n      this.shadowRoot.innerHTML = `<style>${styles}</style>${html}`;\n    }\n  }\n\n  /**\n   * Fetches the reviews summary data from Yotpo and renders whatever came back.\n   */\n  private async startFetching() {\n    // Allow this method to be called multiple times but only run once.\n    if (this.fetchStarted) {\n      return;\n    }\n\n    this.fetchStarted = true;\n\n    if (!this.dataset.yotpoAppKey || !this.dataset.productId) {\n      this.render('', [], []);\n      return;\n    }\n\n    const productId = parseInt(this.dataset.productId, 10);\n    if (!productId) {\n      this.render('', [], []);\n      return;\n    }\n\n    const response = await fetchReviewsSummary({\n      app_key: this.dataset.yotpoAppKey,\n      product_id: productId\n    });\n\n    this.render(response?.paragraphSummary || '', response?.summaryTopics || [],\n      response?.summaryHighlights || []);\n  }\n\n  private render(paragraphSummary: string, topics: SummaryTopic[], highlights: SummaryHighlight[]) {\n    const copy = this.shadowRoot.querySelector<HTMLElement>('.copy');\n    copy.textContent = paragraphSummary;\n    copy.hidden = !paragraphSummary;\n\n    const topicsList = this.shadowRoot.querySelector('.topics');\n    for (const topic of topics) {\n      const title = document.createElement('h5');\n      title.textContent = topic.displayTopic;\n\n      const summary = document.createElement('p');\n      summary.textContent = topic.summary;\n\n      const mentioned = document.createElement('p');\n      mentioned.classList.add('mentioned');\n      mentioned.textContent = `Mentioned in ${topic.coverage} of reviews`;\n\n      const li = document.createElement('li');\n      li.appendChild(title);\n      li.appendChild(summary);\n      li.appendChild(mentioned);\n\n      topicsList.appendChild(li);\n    }\n\n    const topicsSection = this.shadowRoot.querySelector<HTMLElement>('.topics-section');\n    topicsSection.hidden = topics.length === 0;\n\n    const highlightsList = this.shadowRoot.querySelector('.highlights ul');\n    for (const highlight of highlights) {\n      const blockquote = document.createElement('blockquote');\n      blockquote.textContent = highlight.highlight;\n\n      const li = document.createElement('li');\n      li.appendChild(blockquote);\n\n      highlightsList.appendChild(li);\n    }\n\n    const highlightsSection = this.shadowRoot.querySelector<HTMLElement>('.highlights');\n    highlightsSection.hidden = highlights.length === 0;\n\n    // The disclaimer sits outside the three blocks above, so showing the wrapper when they are all\n    // empty would leave the AI notice on screen with nothing for it to be about.\n    const content = this.shadowRoot.querySelector<HTMLElement>('.content');\n    content.hidden = !paragraphSummary && topics.length === 0 && highlights.length === 0;\n\n    const loading = this.shadowRoot.querySelector<HTMLElement>('.loading');\n    loading.hidden = true;\n\n    const empty = this.shadowRoot.querySelector<HTMLElement>('.empty');\n    empty.hidden = !content.hidden;\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'yotpo-ai-summary-simple': YotpoAiSummarySimple;\n  }\n}\n\nif (!customElements.get('yotpo-ai-summary-simple')) {\n  customElements.define('yotpo-ai-summary-simple', YotpoAiSummarySimple);\n}\n","import { assert } from '@integrabeauty/assert';\nimport { decorateError } from '../../lib/decorate-error.js';\n\nexport interface Input {\n  /**\n   * The store ID\n   */\n  app_key: string;\n\n  /**\n   * Shopify product ID\n   */\n  product_id: number;\n}\n\nexport interface SummaryTopic {\n  avgSentiment: number;\n\n  /**\n   * Number of reviews covering this topic\n   */\n  coverage: string;\n\n  displayTopic: string;\n\n  summary: string;\n\n  topic: string;\n}\n\nexport interface SummaryHighlight {\n  highlight: string;\n\n  reviewId: number;\n\n  reviewerName: string;\n}\n\ninterface ResponseData {\n  bundledProductsData: unknown;\n  countries: unknown;\n  customQuestions: unknown;\n  externalId: string;\n  metadata: unknown;\n\n  /**\n   * A paragraph summarizing all reviews for the product\n   */\n  paragraphSummary: string;\n\n  productId: string;\n  productVariants: unknown;\n  storeId: string;\n  summaryHighlights: SummaryHighlight[];\n  summaryTopics: SummaryTopic[];\n  topics: unknown[];\n}\n\nexport interface ResponseBody {\n  response: ResponseData;\n\n  status: {\n    /**\n     * @example 200\n     */\n    code: number;\n\n    /**\n     * @example \"OK\"\n     */\n    message: string;\n  };\n}\n\n/**\n * Fetch AI-generated review summary data for a product from Yotpo.\n */\nexport async function fetchReviewsSummary(input: Input) {\n  assert(input.app_key, 'Invalid app key');\n  assert(Number.isInteger(input.product_id) && input.product_id > 0, 'Invalid product id');\n\n  const path = `/apps/yotpo-ugc-api-cdn/v3/storefront/stores/${input.app_key}/products/` +\n    `${input.product_id}/productData?include=reviewsSummary`;\n\n  const response = await fetch(path);\n\n  if (!response.ok) {\n    const error: any = new Error(`Received status ${response.status} fetching reviews summary`);\n    error.code = response.status;\n    error.url = response.url;\n    throw error;\n  }\n\n  let responseText;\n  try {\n    responseText = await response.text();\n  } catch (error) {\n    decorateError(error, 'code', response.status);\n    decorateError(error, 'url', response.url);\n    throw error;\n  }\n\n  let body;\n  try {\n    body = JSON.parse(responseText);\n  } catch (error) {\n    decorateError(error, 'body', responseText);\n    decorateError(error, 'code', response.status);\n    decorateError(error, 'url', response.url);\n    throw error;\n  }\n\n  if (!isResponseBody(body)) {\n    const error: any = new Error('Unexpected response body');\n    error.body = body;\n    error.code = response.status;\n    error.url = response.url;\n    throw error;\n  }\n\n  if (body.status.code > 399) {\n    const error: any = new Error('Nested response body status code is not 200');\n    error.body = body;\n    error.code = response.status;\n    error.url = response.url;\n    throw error;\n  }\n\n  return body.response;\n}\n\nfunction isResponseBody(value: any): value is ResponseBody {\n  return typeof value === 'object' && value !== null && typeof value.status === 'object' &&\n    value.status !== null && typeof value.response === 'object' && value.response !== null;\n}\n","/**\n * Represents the properties of a cookie.\n */\nexport interface Cookie {\n  /**\n   * Include a leading \".\" to include subdomains.\n   *\n   * @example \".langehair.com\"\n   */\n  domain: string;\n\n  /**\n   * Indicates the maximum lifetime of the cookie as an HTTP-date timestamp. See Date for the\n   * required formatting.\n   *\n   * If unspecified, the cookie becomes a session cookie. A session finishes when the client shuts\n   * down, after which the session cookie is removed.\n   *\n   * Warning: Many web browsers have a session restore feature that will save all tabs and restore\n   * them the next time the browser is used. Session cookies will also be restored, as if the\n   * browser was never closed.\n   *\n   * When an Expires date is set, the deadline is relative to the client the cookie is being set on,\n   * not the server.\n   */\n  expires: Date;\n\n  /**\n   * A <cookie-name> can contain any US-ASCII characters except for: control characters (ASCII\n   * characters `0` up to `31` and ASCII character `127`) or separator characters (space, tab and\n   * the characters: `( ) < > @ , ; : \\ \" / [ ] ? = { })`.\n   */\n  name: string;\n\n  /**\n   * Path is generally \"/\" which is for all pages for a domain. Otherwise the cookie is specific to\n   * the given path (e.g. particular page).\n   */\n  path: string;\n\n  /**\n   * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n   * against cross-site request forgery attacks (CSRF).\n   *\n   * * Strict Means that the browser sends the cookie only for same-site requests, that is, requests\n   *   originating from the same site that set the cookie. If a request originates from a different\n   *   domain or scheme (even with the same domain), no cookies with the SameSite=Strict attribute\n   *   are sent.\n   * * Lax Means that the cookie is not sent on cross-site requests, such as on requests to load\n   *   images or frames, but is sent when a user is navigating to the origin site from an external\n   *   site (for example, when following a link). This is the default behavior if the SameSite\n   *   attribute is not specified.\n   * * None means that the browser sends the cookie with both cross-site and same-site requests. The\n   *   Secure attribute must also be set when setting this value, like so SameSite=None; Secure. If\n   *   Secure is missing an error will be logged\n   *\n   * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie\n   */\n  same_site: 'Lax' | 'None' | 'Strict';\n\n  /**\n   * Indicates that the cookie is sent to the server only when a request is made with the https:\n   * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n   */\n  secure: boolean;\n\n  /**\n   * A <cookie-value> can optionally be wrapped in double quotes and include any US-ASCII character\n   * excluding control characters (ASCII characters 0 up to 31 and ASCII character 127), Whitespace,\n   * double quotes, commas, semicolons, and backslashes.\n   */\n  value: string;\n}\n\n/**\n * Decodes a percent-encoded cookie name or value, falling back to the raw input when decoding is\n * not possible.\n *\n * Cookie storage is shared by every script on a domain, including third party libraries that write\n * raw, improperly-encoded values. A single cookie whose value contains a malformed percent-\n * sequence, such as a literal percent sign that is not followed by two hexadecimal digits, makes\n * decodeURIComponent throw a URIError. Because the whole cookie string is parsed at once, one such\n * cookie would otherwise poison every read on the page rather than just its own entry. Returning\n * the undecoded text keeps the remaining cookies readable, and a value that was never percent-\n * encoded is returned unchanged anyway.\n */\nfunction safeDecode(value: string) {\n  try {\n    return decodeURIComponent(value);\n  } catch (error) {\n    return value;\n  }\n}\n\n/**\n * Parses the value of document.cookie into an an array of cookie objects.\n *\n * **This decodes the cookie name and value. You should not decode the cookie name or value\n * yourself**.\n *\n * Cookies can be set with separate flags. When there are two cookies with the same name but with\n * different flags, the name will appear twice in document.cookie. Therefore, this returns an array\n * of Cookie objects instead of a single object where each name is a property.\n *\n * @throws {Error} if document is undefined, if document.cookie cannot be accessed for some reason\n * such as security restrictions on iframes or browser restrictions, or if document.cookie does not\n * produce a string\n */\nexport function parse() {\n  return document.cookie.split(';').map<Pick<Cookie, 'name' | 'value'>>(parts => {\n    const index = parts.indexOf('=');\n    // decodeURIComponent(undefined) produces strange results in some browsers, such as the string\n    // undefined, so we have to avoid that\n    const encodedValue = parts.slice(index + 1)?.trim();\n    return {\n      name: safeDecode(parts.slice(0, index).trim()),\n      value: typeof encodedValue === 'string' ? safeDecode(encodedValue) : undefined\n    };\n  });\n}\n\n/**\n * Retrieves the value of a particular cookie by name.\n *\n * If a cookie with the given name is not found, then undefined is returned.\n *\n * Internally this calls a private function to parse the cookie and that function accesses\n * document.cookie and for that reason this function can throw. This will almost never happen except\n * when attempting to access cookies cross-context, e.g. accessing parent window cookies from within\n * an iframe where the iframe has certain attributes. Some third party libraries do this naively and\n * without concern for the security constraints imposed by browsers. As a result, you should always\n * consider handling errors when calling this function.\n *\n * Because this can throw, **please implement proper error handling** when calling this function.\n *\n * **This decodes the cookie name and value. You should not decode the cookie name or value\n * yourself**.\n *\n * Cookie values are always strings. If you happen to be storing something like a JSON-like object\n * in the cookie value, then the raw JSON string is returned and is not parsed on your behalf. If\n * you are enclosing your value in double quotes, the leading and trailing double quote characters\n * are included in the returned value.\n *\n * **WARNING**: This is a naive read. When examining the list of cookies, this returns the first one\n * in the list. More than one cookie can have the same name when two or more cookies have the same\n * name but different flags. This is entirely dependent on the order of the names in\n * document.cookie, which is completely unknown and can change at any time and probably varies by\n * browser. Therefore, when there is more than one cookie with the same name, it is possible this\n * returns an unexpected cookie value.\n *\n * @throws {SecurityError}\n * @throws {Error}\n */\nexport function read(name: string) {\n  return readAll(name).shift();\n}\n\nexport function readAll(name: string) {\n  return parse().filter(cookie => cookie.name === name).map(cookie => cookie.value);\n}\n\n/**\n * Given a cookie, generate the string that can be supplied to document.cookie\n *\n * **This encodes the cookie name and cookie. Do not encode these yourself**.\n */\nexport function serialize(cookie: Partial<Cookie>) {\n  if (!cookie.name) {\n    throw new Error('Cookie name is required');\n  }\n\n  const parts: string[] = [];\n\n  parts.push(`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value || '')}`);\n\n  if (typeof cookie.path === 'string') {\n    parts.push(`Path=${cookie.path}`);\n  }\n\n  if (typeof cookie.domain === 'string') {\n    parts.push(`Domain=${cookie.domain}`);\n  }\n\n  if (cookie.expires && typeof cookie.expires.getTime === 'function') {\n    parts.push(`Expires=${cookie.expires.toUTCString()}`);\n  }\n\n  if (typeof cookie.same_site === 'string') {\n    parts.push(`SameSite=${cookie.same_site}`);\n  }\n\n  if (cookie.secure) {\n    parts.push('Secure');\n  }\n\n  // The delimiter must include a single space after semicolon\n\n  return parts.join('; ');\n}\n\n/**\n * This function can throw because setting document.cookie sometimes throws an error.\n *\n * This function can throw on invalid input, such as when not specifying a required property such as\n * cookie name.\n *\n * **This encodes the cookie name and cookie. Do not encode these yourself**.\n */\nexport function write(cookie: Partial<Cookie>) {\n  document.cookie = serialize(cookie);\n}\n\n/**\n * Deletes a cookie.\n *\n * Of the cookie properties, only the name is required. However, some browsers are extremely strict\n * about how a cookie is deleted. To delete a cookie the exact same other properties must also be\n * provided, other than the cookie's value and expiration date. For example, if the cookie to be\n * deleted is secure, then you must specify the secure property to delete the cookie.\n *\n * If the properties do not match, this completes without error and the cookie that was to be\n * deleted still remains.\n *\n * Deleting a cookie is done by setting its value to an empty string and then assigning the full\n * cookie value to document.cookie.\n *\n * This function may throw an error because deleting a cookie is done by assigning a value to\n * document.cookie which can sometimes throw.\n *\n * The expires property is ignored. This sets expiration date to 1970 to force cookie to become\n * expired.\n *\n * Insecure cookies cannot be removed. These are cookies belonging to the http protocol.\n */\nexport function remove(cookie: Partial<Cookie>) {\n  write({ ...cookie, value: '', expires: new Date(0) });\n}\n","const rnds8 = new Uint8Array(16);\nexport default function rng() {\n    return crypto.getRandomValues(rnds8);\n}\n","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n    byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n    return (byteToHex[arr[offset + 0]] +\n        byteToHex[arr[offset + 1]] +\n        byteToHex[arr[offset + 2]] +\n        byteToHex[arr[offset + 3]] +\n        '-' +\n        byteToHex[arr[offset + 4]] +\n        byteToHex[arr[offset + 5]] +\n        '-' +\n        byteToHex[arr[offset + 6]] +\n        byteToHex[arr[offset + 7]] +\n        '-' +\n        byteToHex[arr[offset + 8]] +\n        byteToHex[arr[offset + 9]] +\n        '-' +\n        byteToHex[arr[offset + 10]] +\n        byteToHex[arr[offset + 11]] +\n        byteToHex[arr[offset + 12]] +\n        byteToHex[arr[offset + 13]] +\n        byteToHex[arr[offset + 14]] +\n        byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n    const uuid = unsafeStringify(arr, offset);\n    if (!validate(uuid)) {\n        throw TypeError('Stringified UUID is invalid');\n    }\n    return uuid;\n}\nexport default stringify;\n","import rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n    if (!buf && !options && crypto.randomUUID) {\n        return crypto.randomUUID();\n    }\n    return _v4(options, buf, offset);\n}\nfunction _v4(options, buf, offset) {\n    options = options || {};\n    const rnds = options.random ?? options.rng?.() ?? rng();\n    if (rnds.length < 16) {\n        throw new Error('Random bytes length must be >= 16');\n    }\n    rnds[6] = (rnds[6] & 0x0f) | 0x40;\n    rnds[8] = (rnds[8] & 0x3f) | 0x80;\n    if (buf) {\n        offset = offset || 0;\n        if (offset < 0 || offset + 16 > buf.length) {\n            throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n        }\n        for (let i = 0; i < 16; ++i) {\n            buf[offset + i] = rnds[i];\n        }\n        return buf;\n    }\n    return unsafeStringify(rnds);\n}\nexport default v4;\n","// A promo is a ladder of tiers. Each tier holds the number of items that turns it on, the discount\n// code Shopify applies once it does, and a reward saying what the customer gets. Rewards vary from\n// promo to promo and the rest of a tier does not, so a new promo shape means a new reward class.\n//\n// Every reward here is a pricing reward, meaning it sets what the bundle costs. Only one can be in\n// effect at a time, so where several tiers are met we compare their totals and keep the cheapest.\n//\n// The other shape we expect to want is a perk, something a tier throws in without repricing the\n// bundle, such as free shipping or a free item. A perk cannot join that comparison, because it\n// never lowers the total and so would always lose. To fit one in, let a tier carry a pricing reward\n// plus any number of perks, compare the pricing rewards only, and apply the perks of every met tier\n// on top of whichever pricing tier won. A perk would contribute its own discount code, and a free\n// item would also contribute a variant to hand to the cart. Rewards carry a kind so that the split\n// costs one branch when we get there.\n//\n// Nothing here charges anybody. Shopify's discount codes do the real pricing at the cart, and this\n// module only works out what to show the customer beforehand.\n\n/**\n * What the customer pays once a tier is in effect. All amounts are in cents.\n */\ninterface Pricing {\n  /**\n   * One price per bundle item, in the order the item prices were given\n   */\n  linePrices: number[];\n\n  /**\n   * What the whole bundle comes to. This is always the sum of the line prices, so the total and the\n   * lines cannot disagree on screen.\n   */\n  total: number;\n}\n\n/**\n * A reward that sets what the bundle costs\n */\nexport interface PricingReward {\n  /**\n   * Prices the bundle from its item prices in cents\n   */\n  apply(variantPrices: number[]): Pricing;\n\n  /**\n   * Short label for the tier's slot in the bundle strip, e.g. \"20% off\"\n   */\n  getBadgeLabel(): string;\n\n  /**\n   * Names what the tier gives as a noun phrase, for dropping into a sentence such as \"Add 2 more\n   * products to unlock ...\"\n   */\n  getOfferLabel(): string;\n\n  kind: 'pricing';\n}\n\n/**\n * One rung of a promo ladder\n */\nexport interface Tier {\n  /**\n   * The Shopify discount code to send along with the cart while this tier is in effect\n   */\n  discountCode: string;\n\n  /**\n   * What the customer gets once the threshold is reached\n   */\n  reward: PricingReward;\n\n  /**\n   * How many items the bundle needs before this tier is in effect\n   */\n  threshold: number;\n}\n\n/**\n * Takes a percentage off each item in the bundle\n */\nexport class PercentageReward implements PricingReward {\n  readonly kind = 'pricing';\n\n  private declare readonly percentage: number;\n\n  constructor(percentage: number) {\n    this.percentage = percentage;\n  }\n\n  apply(variantPrices: number[]) {\n    const linePrices: number[] = [];\n    let total = 0;\n\n    for (const variantPrice of variantPrices) {\n      const linePrice = Math.round(variantPrice * (1 - this.percentage / 100));\n      linePrices.push(linePrice);\n      total += linePrice;\n    }\n\n    return { linePrices, total };\n  }\n\n  getBadgeLabel() {\n    return this.percentage + '% off';\n  }\n\n  getOfferLabel() {\n    return this.percentage + '% off';\n  }\n}\n\n/**\n * Sets one price for the whole bundle, whatever its items cost on their own. The Shopify discount\n * spreads that price evenly over the lines, so we do the same, and the last line takes whatever\n * cents an uneven split leaves over.\n */\nexport class FixedPriceReward implements PricingReward {\n  readonly kind = 'pricing';\n\n  private declare readonly bundlePrice: number;\n\n  private declare readonly currencySymbol: string;\n\n  private declare readonly itemCount: number;\n\n  constructor(bundlePrice: number, itemCount: number, currencySymbol: string) {\n    this.bundlePrice = bundlePrice;\n    this.currencySymbol = currencySymbol;\n    this.itemCount = itemCount;\n  }\n\n  apply(variantPrices: number[]) {\n    if (variantPrices.length === 0) {\n      return { linePrices: <number[]>[], total: 0 };\n    }\n\n    const linePrices: number[] = [];\n    const share = Math.floor(this.bundlePrice / variantPrices.length);\n    while (linePrices.length < variantPrices.length) {\n      linePrices.push(share);\n    }\n\n    linePrices[linePrices.length - 1] += this.bundlePrice - share * variantPrices.length;\n\n    return { linePrices, total: this.bundlePrice };\n  }\n\n  getBadgeLabel() {\n    return formatAmount(this.bundlePrice, this.currencySymbol);\n  }\n\n  getOfferLabel() {\n    return this.itemCount + ' for ' + formatAmount(this.bundlePrice, this.currencySymbol);\n  }\n}\n\n/**\n * Reads the promo tiers out of the builder's slotted `bundle-tier` elements, lowest threshold\n * first. A tier we cannot make sense of is dropped rather than guessed at, which leaves the\n * customer with no promo, so each drop says on the way out what was wrong with it.\n */\nexport function parseTiers(elements: Iterable<BundleTierElement>, currencySymbol: string) {\n  const tiers: Tier[] = [];\n\n  for (const element of elements) {\n    const discountCode = element.dataset.discountCode;\n    if (!discountCode) {\n      console.warn('Bundle tier has no discount code');\n      continue;\n    }\n\n    const threshold = parseInt(element.dataset.threshold, 10);\n    if (isNaN(threshold)) {\n      console.warn('Bundle tier has an unreadable threshold', element.dataset.threshold);\n      continue;\n    }\n\n    const rewardValue = parseFloat(element.dataset.rewardValue);\n    if (isNaN(rewardValue)) {\n      console.warn('Bundle tier has an unreadable reward value', element.dataset.rewardValue);\n      continue;\n    }\n\n    let reward: PricingReward;\n    if (element.dataset.reward === 'percentage') {\n      reward = new PercentageReward(rewardValue);\n    } else if (element.dataset.reward === 'fixed-price') {\n      reward = new FixedPriceReward(rewardValue, threshold, currencySymbol);\n    } else {\n      console.warn('Bundle tier has an unrecognized reward', element.dataset.reward);\n      continue;\n    }\n\n    tiers.push({ discountCode, reward, threshold });\n  }\n\n  tiers.sort(compareThresholds);\n\n  return tiers;\n}\n\n/**\n * Picks the tier the bundle qualifies for, or nothing when it qualifies for none. Where more than\n * one threshold is met we keep whichever tier leaves the customer paying least, which is well\n * defined however the tiers reward differently from one another.\n */\nexport function selectActiveTier(tiers: Tier[], variantPrices: number[]) {\n  let activeTier: Tier;\n  let lowestTotal = 0;\n\n  for (const tier of tiers) {\n    if (variantPrices.length < tier.threshold) {\n      continue;\n    }\n\n    const pricing = tier.reward.apply(variantPrices);\n    if (!activeTier || pricing.total < lowestTotal) {\n      activeTier = tier;\n      lowestTotal = pricing.total;\n    }\n  }\n\n  return activeTier;\n}\n\n/**\n * Compares two tiers by their threshold\n */\nfunction compareThresholds(a: Tier, b: Tier) {\n  return a.threshold - b.threshold;\n}\n\n/**\n * Renders an amount in cents as price copy, dropping the cents when they are zero so that a round\n * promo price reads \"$99\" rather than \"$99.00\"\n */\nfunction formatAmount(cents: number, currencySymbol: string) {\n  const dollars = Math.round(cents) / 100;\n  if (Number.isInteger(dollars)) {\n    return currencySymbol + dollars.toString();\n  }\n\n  return currencySymbol + dollars.toFixed(2);\n}\n","import { read, remove, write } from '@integrabeauty/cookie';\nimport type { CustomElement } from '@integrabeauty/custom-elements';\nimport { v4 as uuidv4 } from 'uuid';\nimport html from './index.html';\nimport styles from './index.scss';\nimport { parseTiers, selectActiveTier } from './promo.js';\nimport type { Tier } from './promo.js';\n\ntype AddToCartElement = HTMLElementTagNameMap['add-to-cart'];\ntype InstallmentPaymentMessageElement = HTMLElementTagNameMap['installment-payment-message'];\ntype ProductElement = HTMLElementTagNameMap['product-element'];\ntype ProductPriceElement = HTMLElementTagNameMap['product-price'];\ntype VariantElement = HTMLElementTagNameMap['variant-element'];\ntype CartTransactionStartedEvent = WindowEventMap['cart-transaction-started'];\ntype CartUpdatedEvent = GlobalEventHandlersEventMap['cart-updated'];\ntype CartTransactionCompletedEvent = WindowEventMap['cart-transaction-completed'];\ntype CartOpenRequestedEvent = GlobalEventHandlersEventMap['cart-open-requested'];\ntype ModalOpenedEvent = HTMLElementEventMap['modal-opened'];\ntype ModalClosedEvent = HTMLElementEventMap['modal-closed'];\ntype NotifyMeClickedEvent = HTMLElementEventMap['notify-me-clicked'];\n\ntype BundleModalName = 'bundle-details' | 'product-details';\n\ntype BundlePreviewSlot = { kind: 'product'; variant: VariantElement; } |\n  { kind: 'locked'; tier: Tier; } |\n  { kind: 'empty'; };\n\n/**\n * A single product a category offers, extracted from one of its bundle-item children\n */\ninterface BundleCategoryProduct {\n  /**\n   * Product image URL\n   */\n  imageUrl: string;\n\n  /**\n   * Whether the item offering this product is in the bundle from the start\n   */\n  preselected: boolean;\n\n  /**\n   * Identifies this product within this category. It is also the id of the product element it was\n   * read from.\n   */\n  productKey: string;\n\n  /**\n   * The average review value (out of 5 stars)\n   */\n  reviewsAverage: string;\n\n  /**\n   * The number of product reviews\n   */\n  reviewsCount: string;\n\n  /**\n   * Product subtitle, e.g. \"Shampoo\"\n   */\n  subtitle: string;\n\n  /**\n   * Display title (metafields title preferred over Shopify title)\n   */\n  title: string;\n\n  /**\n   * Product detail page URL\n   */\n  url: string;\n\n  /**\n   * Product variants, e.g. different colors or sizes\n   */\n  variants: {\n    /**\n     * Whether the variant is available or out of stock\n     */\n    available: boolean;\n\n    /**\n     * Variant compare-at price in cents - absent when the variant has none\n     */\n    compareAtPrice?: number;\n\n    /**\n     * URL of the variant's image - may be empty\n     */\n    imageSrc: string;\n\n    /**\n     * Variant price in cents\n     */\n    price: number;\n\n    /**\n     * Whether this variant is currently selected in the category\n     */\n    selected: boolean;\n\n    /**\n     * Variant SKU, used to identify the variant in the add-to-cart payload\n     */\n    sku: string;\n\n    /**\n     * Variant title\n     */\n    title: string;\n  }[];\n}\n\n/**\n * A single product in the bundle. Its fields are plain strings so that the bundle can be written to\n * and read back from a cookie.\n */\ninterface BundleItem {\n  /**\n   * Identifies the product this came from, `pk-<category id>-<item id>`\n   */\n  productKey: string;\n\n  /**\n   * Shopify ID of the variant that is in the bundle\n   */\n  variantId: string;\n}\n\n/**\n * Orchestrates a personalized bundle displayed on a bundle product detail page.\n *\n * Reads its categories and the products they offer from its `<bundle-category>`, `<bundle-item>`,\n * and `<product-element>` children and owns all bundle state itself: which variant is selected in\n * each product, which variant is merely previewed in a product's dropdown, the aggregated pseudo-\n * cart across every category, and the promo ladder. `<bundle-category>` is a plain data holder with\n * no behavior of its own (see its ambient type declaration); this element renders its accordion\n * header, product grid, and per-product add/remove and variant-select controls directly into its\n * own shadow root, alongside the bundle drawer, price boxes, and add-to-cart elements. Centralizing\n * all of this here means a change to one product's selection re-renders everything downstream of it\n * in one pass, with nothing to keep in sync across elements.\n *\n * **Price box** — the total price (sum of all selected variant prices) is written back to each\n * internal `product-price` by mutating its first `variant-element` and triggering its own re-render\n * via `data-update`; `installment-payment-message` gets its fields written directly instead, since\n * it has no nested variant to re-render off of.\n *\n * **Add-to-cart** — the first promo step variant becomes the main cart item inside the internal\n * `add-to-cart` element, or the first regular step variant when the bundle holds no promo items;\n * every other variant is appended as an add-on (`data-is-addon=\"true\"`).\n *\n * ## Named slots\n * - `categories` — `<bundle-category>` children marked `slot=\"categories\"`, but there is no\n *   matching `<slot>` in the shadow template, so this element reads and renders them itself\n * - `items` — one `<bundle-item>` per thing a category offers, holding that item's `product` and\n *   `product-images`; none of these has a matching `<slot>` either, so they are read the same way\n * - `tiers` — one `<bundle-tier>` per rung of the promo ladder, projected through a real\n *   `<slot name=\"tiers\">`; `<bundle-tier>` is a pure data holder, never rendered\n */\nclass BundleBuilder extends HTMLElement implements CustomElement {\n  declare readonly dataset: {\n    /**\n     * The value to write into the `_bundle_builder` line item property on every cart line this\n     * bundle adds, from the bundle metaobject. Blank means no property is added.\n     */\n    attributionTagValue: string;\n\n    /**\n     * Id of the bundle metaobject, which names the cookie that saves the shopper's picks. Blank\n     * means nothing is saved or restored.\n     */\n    bundleId: string;\n\n    /**\n     * Currency code\n     */\n    currencyCode: string;\n\n    /**\n     * Currency Symbol (e.g., $)\n     */\n    currencySymbol: string;\n\n    /**\n     * The signed in customer's email, absent when nobody is signed in\n     */\n    customerEmail: string;\n\n    /**\n     * Url for the installment payment afterpay logo asset\n     */\n    installmentAfterpayLogo: string;\n\n    /**\n     * Url for the installment payment Klarna logo asset\n     */\n    installmentKlarnaLogo: string;\n\n    /**\n     * The threshold from which installment payment is possible\n     */\n    installmentThreshold: string;\n  };\n\n  /**\n   * Every variant in the bundle, promo steps and regular steps alike, in document order. This is\n   * what reaches the cart and what the bundle drawer lists.\n   */\n  private variants: VariantElement[] = [];\n\n  /**\n   * The subset of `variants` that came from promo steps, in the same order. The promo ladder counts\n   * these and nothing else, so every threshold, reward, and unlock message reads this rather than\n   * `variants`.\n   */\n  private promoVariants: VariantElement[] = [];\n\n  /**\n   * The subset of `variants` that came from regular steps, in the same order. These are bought at\n   * their own price and move no threshold.\n   */\n  private regularVariants: VariantElement[] = [];\n\n  /**\n   * The promo tiers gathered from the slotted `bundle-tier` elements, guaranteed to be sorted by\n   * their threshold in ascending order\n   */\n  private tiers: Tier[] = [];\n\n  /**\n   * The variant currently shown in each product's image/price preview, keyed by product key. For a\n   * product not in the bundle this is only a preview: choosing an option in the dropdown updates\n   * this map immediately, and it carries into the bundle once the product is added. For a product\n   * already in the bundle, an option that can be bought goes into the bundle at once. An out of\n   * stock option stays a preview and the bundle keeps its variant.\n   */\n  private uiSelectedVariants = new Map<string, VariantElement>();\n\n  /**\n   * What is in the bundle, in the order it was added. This is the authoritative record of the\n   * bundle, and the light DOM's `data-selected-variant-id` and `data-selected` attributes are\n   * written from it on every render. A category that is over its maximum drops its earliest\n   * entries.\n   */\n  private bundle: BundleItem[] = [];\n\n  /**\n   * Whether the bundle reached the cart and is waiting to be cleared.\n   *\n   * `cart-transaction-completed` fires on the window for every cart operation on the page, and it\n   * carries no result, so on its own it says neither that the bundle was added nor that adding\n   * worked. `cart-updated` reaching one of this element's own add to cart elements says both, and\n   * this records it so that the clearing can wait for the later event and let the modal close\n   * first.\n   */\n  private bundleAdded = false;\n\n  private onVariantChangedBound = this.onVariantChanged.bind(this);\n  private onRemoveBundleItemClickedBound = this.onRemoveBundleItemClicked.bind(this);\n  private onViewBundleClickedBound = this.onViewBundleClicked.bind(this);\n  private onAddToBagClickedBound = this.onAddToBagClicked.bind(this);\n  private onModalOpenedBound = this.onModalOpened.bind(this);\n  private onModalClosedBound = this.onModalClosed.bind(this);\n  private onCartTransactionCompletedBound = this.onCartTransactionCompleted.bind(this);\n  private onCartTransactionStartedBound = this.onCartTransactionStarted.bind(this);\n  private onCartOpenRequestedBound = this.onCartOpenRequested.bind(this);\n  private onLearnMoreClickedBound = this.onLearnMoreClicked.bind(this);\n  private onChosenProductClickedBound = this.onChosenProductClicked.bind(this);\n  private onProductModalCtaClickedBound = this.onProductModalCtaClicked.bind(this);\n  private onBundleAddedToCartBound = this.onBundleAddedToCart.bind(this);\n  private onUnfilledSlotClickedBound = this.onUnfilledSlotClicked.bind(this);\n  private onRatingStarsClickedBound = this.onRatingStarsClicked.bind(this);\n  private onNotifyMeClickedBound = this.onNotifyMeClicked.bind(this);\n  private onRowVariantChangedBound = this.onRowVariantChanged.bind(this);\n\n  public connectedCallback() {\n    this.initializeShadowRoot();\n\n    addEventListener('cart-transaction-completed', this.onCartTransactionCompletedBound);\n    addEventListener('cart-transaction-started', this.onCartTransactionStartedBound);\n    this.addEventListener('cart-open-requested', this.onCartOpenRequestedBound);\n    this.shadowRoot.addEventListener('modal-opened', this.onModalOpenedBound);\n    this.shadowRoot.addEventListener('modal-closed', this.onModalClosedBound);\n\n    const stickyBar = this.shadowRoot.querySelector<HTMLElement>('.mobile-sticky-bar');\n    stickyBar.addEventListener('click', this.onViewBundleClickedBound);\n\n    const addToBagButton = this.shadowRoot.querySelector<HTMLButtonElement>(\n      '.mobile-sticky-bar .add-to-bag');\n    addToBagButton.addEventListener('click', this.onAddToBagClickedBound);\n\n    const productModalCta = this.shadowRoot.querySelector<HTMLButtonElement>('.product-modal-cta');\n    productModalCta.addEventListener('click', this.onProductModalCtaClickedBound);\n\n    const ctaRow = this.shadowRoot.querySelector<HTMLElement>('.ctas');\n    ctaRow.addEventListener('notify-me-clicked', this.onNotifyMeClickedBound);\n\n    const variantSelector = this.shadowRoot.querySelector('.variant-selector select');\n    variantSelector.addEventListener('change', this.onVariantChangedBound);\n\n    const itemsContainers = this.shadowRoot.querySelectorAll<HTMLElement>('.bundle .items');\n    for (const itemsContainer of itemsContainers) {\n      itemsContainer.addEventListener('click', this.onUnfilledSlotClickedBound);\n      itemsContainer.addEventListener('change', this.onRowVariantChangedBound);\n    }\n\n    const ratingStars = this.shadowRoot.querySelector<HTMLElement>(\n      '.product-details product-rating-stars');\n    ratingStars.addEventListener('click', this.onRatingStarsClickedBound);\n  }\n\n  public disconnectedCallback() {\n    removeEventListener('cart-transaction-completed', this.onCartTransactionCompletedBound);\n    removeEventListener('cart-transaction-started', this.onCartTransactionStartedBound);\n    this.removeEventListener('cart-open-requested', this.onCartOpenRequestedBound);\n    this.shadowRoot.removeEventListener('modal-opened', this.onModalOpenedBound);\n    this.shadowRoot.removeEventListener('modal-closed', this.onModalClosedBound);\n\n    const stickyBar = this.shadowRoot.querySelector<HTMLElement>('.mobile-sticky-bar');\n    stickyBar?.removeEventListener('click', this.onViewBundleClickedBound);\n\n    const addToBagButton = this.shadowRoot.querySelector<HTMLButtonElement>(\n      '.mobile-sticky-bar .add-to-bag');\n    addToBagButton?.removeEventListener('click', this.onAddToBagClickedBound);\n\n    const productModalCta = this.shadowRoot.querySelector<HTMLButtonElement>('.product-modal-cta');\n    productModalCta?.removeEventListener('click', this.onProductModalCtaClickedBound);\n\n    const ctaRow = this.shadowRoot.querySelector<HTMLElement>('.ctas');\n    ctaRow?.removeEventListener('notify-me-clicked', this.onNotifyMeClickedBound);\n\n    const variantSelector = this.shadowRoot.querySelector('.variant-selector select');\n    variantSelector?.removeEventListener('change', this.onVariantChangedBound);\n\n    const itemsContainers = this.shadowRoot.querySelectorAll<HTMLElement>('.bundle .items');\n    for (const itemsContainer of itemsContainers) {\n      itemsContainer.removeEventListener('click', this.onUnfilledSlotClickedBound);\n      itemsContainer.removeEventListener('change', this.onRowVariantChangedBound);\n    }\n\n    const ratingStars = this.shadowRoot.querySelector<HTMLElement>(\n      '.product-details product-rating-stars');\n    ratingStars?.removeEventListener('click', this.onRatingStarsClickedBound);\n  }\n\n  private initializeShadowRoot() {\n    if (!this.shadowRoot) {\n      this.attachShadow({ mode: 'open' });\n      this.shadowRoot.innerHTML = `<style>${styles}</style>${html}`;\n\n      // the bundle-details markup is duplicated into both the always-visible desktop drawer and the\n      // mobile \"View Bundle\" modal, so each gets its own independent copy\n      const bundleDetailsContent = this.shadowRoot.querySelector('#bundle-details-template');\n      const bundleDetailsContainers = this.shadowRoot.querySelectorAll('.bundle');\n      for (const bundleDetailsContainer of bundleDetailsContainers) {\n        bundleDetailsContainer.innerHTML = '';\n        if (bundleDetailsContent instanceof HTMLTemplateElement) {\n          const content = document.importNode(bundleDetailsContent.content, true);\n          bundleDetailsContainer.appendChild(content);\n        }\n      }\n\n      this.initializeCategories();\n    }\n  }\n\n  /**\n   * Builds the `.category` card for every `<bundle-category>` child, wires up its accordion header,\n   * and seeds a starting variant selection for each of its products.\n   */\n  private initializeCategories() {\n    const categoriesContainer = this.shadowRoot.querySelector('.categories');\n    const categoryTemplate = this.shadowRoot.querySelector('#category-template');\n    if (!categoriesContainer || !(categoryTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    const categories = this.getCategoryElements();\n    for (const category of categories) {\n      const content = document.importNode(categoryTemplate.content, true);\n      const categoryCard = content.querySelector('.category');\n      if (!(categoryCard instanceof HTMLElement)) {\n        continue;\n      }\n\n      categoryCard.dataset.categoryIndex = category.dataset.index;\n\n      // every category but the first starts collapsed. The state is set before the card is appended\n      // so the collapse does not animate on load.\n      categoryCard.dataset.open = category === categories[0] ? 'true' : 'false';\n\n      const bodyId = 'category-body-' + category.dataset.index;\n      const body = categoryCard.querySelector('.body');\n      body.id = bodyId;\n\n      const header = categoryCard.querySelector<HTMLButtonElement>('.header');\n      header.setAttribute('aria-controls', bodyId);\n      header.addEventListener('click', onCategoryHeaderClicked);\n\n      categoriesContainer.appendChild(categoryCard);\n\n      const itemElements = getCategoryItemElements(category);\n      for (const itemElement of itemElements) {\n        const productElement = getItemProductElement(itemElement);\n        if (productElement) {\n          productElement.id = buildProductKey(category, itemElement);\n        }\n      }\n\n      this.addPreselectedProducts(category);\n\n      for (const itemElement of itemElements) {\n        const productElement = getItemProductElement(itemElement);\n        if (productElement) {\n          this.updateUiSelectedVariant(productElement);\n        }\n      }\n    }\n\n    this.restoreSavedBundle();\n\n    this.gatherData();\n    this.render();\n\n    // a first step that loads full locks and closes in that render, which would leave every step\n    // closed, so the customer starts at the first step that still has room\n    const startingCategory = this.findCategoryWithRoom();\n    if (!startingCategory) {\n      return;\n    }\n\n    const startingCategoryCard = this.getCategoryCard(startingCategory);\n    if (startingCategoryCard) {\n      setCategoryOpenState(startingCategoryCard, true);\n    }\n  }\n\n  /**\n   * Sets the product's UI-previewed variant to its bundled variant when it is in the bundle,\n   * otherwise the first available one, otherwise the first variant at all. The builder relies on\n   * there always being one so it has something to show a price and image for even when nothing is\n   * added to the bundle yet.\n   */\n  private updateUiSelectedVariant(productElement: ProductElement) {\n    const productKey = productElement.id;\n    if (!productKey) {\n      return;\n    }\n\n    let variantElement: VariantElement;\n\n    const item = this.findBundleItem(productKey);\n    if (item) {\n      variantElement = productElement.querySelector<VariantElement>(\n        `:scope > variant-element[data-id=\"${item.variantId}\"]`);\n    }\n\n    if (!variantElement) {\n      variantElement = productElement.querySelector<VariantElement>(\n        ':scope > variant-element[data-available=\"true\"]');\n    }\n\n    if (!variantElement) {\n      variantElement = productElement.querySelector<VariantElement>(':scope > variant-element');\n    }\n\n    this.uiSelectedVariants.set(productKey, variantElement);\n  }\n\n  /**\n   * Puts a product into the bundle. When its category is already at its maximum, whichever of the\n   * category's products entered the bundle first is dropped to make room, except that a required\n   * product is never dropped. When only required products are left to drop, the new product is the\n   * one that does not stay.\n   */\n  private addProductToBundle(productElement: ProductElement, variantId?: string) {\n    const variantElement = findAvailableVariant(productElement, variantId);\n\n    // nothing is added when the product has no variant available to buy\n    if (!variantElement) {\n      return;\n    }\n\n    const addedItem = {\n      productKey: productElement.id,\n      variantId: variantElement.dataset.id\n    };\n    this.bundle.push(addedItem);\n\n    const category = productElement.closest('bundle-category');\n    if (!category) {\n      return;\n    }\n\n    // an unset maximum makes the overflow negative, which drops nothing\n    const items = this.getCategoryItems(category);\n    let overflow = items.length - getCategoryLimits(category).maxItems;\n    for (const item of items) {\n      if (overflow < 1) {\n        break;\n      }\n\n      if (item === addedItem) {\n        continue;\n      }\n\n      if (isProductRequired(this.findProductElement(item.productKey))) {\n        continue;\n      }\n\n      this.removeItemFromBundle(item);\n      overflow--;\n    }\n\n    if (overflow > 0) {\n      this.removeItemFromBundle(addedItem);\n    }\n  }\n\n  /**\n   * Swaps the variant of a product already in the bundle for another one. The item keeps its place\n   * in the bundle, so the main product and the order of the add-ons do not change. A variant that\n   * cannot be bought is refused, since everything in the bundle goes to the cart.\n   */\n  private switchBundleItemVariant(productElement: ProductElement, variantId: string) {\n    const item = this.findBundleItem(productElement.id);\n\n    // a product not in the bundle has nothing to switch, so callers need not check first\n    if (!item) {\n      return;\n    }\n\n    // an empty id would match the first available variant, which is not the one picked\n    if (!variantId) {\n      return;\n    }\n\n    if (!findAvailableVariant(productElement, variantId)) {\n      return;\n    }\n\n    item.variantId = variantId;\n    this.updateUiSelectedVariant(productElement);\n    this.gatherData();\n  }\n\n  /**\n   * Puts a category's preselected products into the bundle. The bundle says what is selected rather\n   * than the markup, so they go in through the same path a click takes, which applies the\n   * category's maximum to them.\n   */\n  private addPreselectedProducts(category: BundleCategoryElement) {\n    const itemElements = getCategoryItemElements(category);\n    for (const itemElement of itemElements) {\n      const productElement = getItemProductElement(itemElement);\n      if (productElement && isItemPreselected(itemElement)) {\n        this.addProductToBundle(productElement);\n      }\n    }\n  }\n\n  /**\n   * Takes a product out of the bundle. The product's UI-previewed variant is deliberately left\n   * alone so that removing a product does not throw away the option the visitor picked for it.\n   */\n  private removeProductFromBundle(productKey: string) {\n    for (let index = this.bundle.length - 1; index > -1; index--) {\n      if (this.bundle[index].productKey === productKey) {\n        this.bundle.splice(index, 1);\n      }\n    }\n  }\n\n  /**\n   * Takes one particular entry out of the bundle\n   */\n  private removeItemFromBundle(item: BundleItem) {\n    const index = this.bundle.indexOf(item);\n    if (index > -1) {\n      this.bundle.splice(index, 1);\n    }\n  }\n\n  /**\n   * Puts the bundle back to its preselected products and reopens every step, so that a visitor who\n   * adds a bundle to the cart and carries on browsing starts the next one with only those in it.\n   *\n   * A product that is back in the bundle shows the variant the bundle holds. Any other product\n   * keeps the UI-previewed variant the visitor picked for it, the same way removing a single\n   * product leaves it.\n   */\n  private resetBundle() {\n    this.bundle.length = 0;\n\n    const categories = this.getCategoryElements();\n    for (const category of categories) {\n      const categoryCard = this.getCategoryCard(category);\n      if (categoryCard) {\n        setCategoryOpenState(categoryCard, true);\n      }\n\n      this.addPreselectedProducts(category);\n    }\n\n    // a preselected product goes back in as its first available variant, which can differ from the\n    // one the visitor had swapped it to\n    for (const item of this.bundle) {\n      this.updateUiSelectedVariant(this.findProductElement(item.productKey));\n    }\n\n    this.gatherData();\n    this.render();\n  }\n\n  /**\n   * Writes the bundle to its cookie when the shopper's last action changed it. An action that left\n   * the bundle alone, such as picking a variant that can't be bought, writes nothing.\n   */\n  private saveBundleIfChanged(valueBefore: string) {\n    const bundleId = this.dataset.bundleId;\n    if (!bundleId) {\n      return;\n    }\n\n    const value = serializeBundle(this.bundle);\n    if (value === valueBefore) {\n      return;\n    }\n\n    // the cookie lasts 7 days from each save\n    const expires = new Date();\n    expires.setDate(expires.getDate() + 7);\n\n    try {\n      write({\n        expires,\n        name: buildBundleCookieName(bundleId),\n        path: '/',\n        same_site: 'Lax',\n        secure: true,\n        value\n      });\n    } catch (error) {\n      console.debug('Failed to save the bundle', error);\n    }\n  }\n\n  /**\n   * Removes the saved picks, once the bundle has gone to the cart\n   */\n  private clearSavedBundle() {\n    const bundleId = this.dataset.bundleId;\n    if (!bundleId) {\n      return;\n    }\n\n    try {\n      remove({\n        name: buildBundleCookieName(bundleId),\n        path: '/',\n        same_site: 'Lax',\n        secure: true\n      });\n    } catch (error) {\n      console.debug('Failed to clear the saved bundle', error);\n    }\n  }\n\n  /**\n   * Puts back the picks saved on an earlier visit. A saved pick can be out of date, with its\n   * product removed or its variant sold out, so each goes in through the same path a click takes. A\n   * sold out variant is swapped for the product's first available one, and a removed product is\n   * skipped. A step where none of its saved picks came back keeps its defaults rather than going\n   * empty. When no pick fits anywhere, every default stays as it is.\n   */\n  private restoreSavedBundle() {\n    const bundleId = this.dataset.bundleId;\n    if (!bundleId) {\n      return;\n    }\n\n    let value = '';\n    try {\n      value = read(buildBundleCookieName(bundleId));\n    } catch (error) {\n      console.debug('Failed to read the saved bundle', error);\n    }\n\n    if (!value) {\n      return;\n    }\n\n    const savedPicks = parseSavedBundle(value);\n    const picks: BundleItem[] = [];\n    for (const savedPick of savedPicks) {\n      const productElement = this.findProductElement(savedPick.productKey);\n      if (!productElement) {\n        continue;\n      }\n\n      // The saved variant can sell out between visits, and skipping the product would leave its\n      // step short. We use the product's first available variant instead, the way a default does.\n      let variantElement = findAvailableVariant(productElement, savedPick.variantId);\n      if (!variantElement) {\n        variantElement = findAvailableVariant(productElement);\n      }\n\n      if (!variantElement) {\n        continue;\n      }\n\n      picks.push({ productKey: savedPick.productKey, variantId: variantElement.dataset.id });\n    }\n\n    if (picks.length === 0) {\n      return;\n    }\n\n    // Clearing every default would leave a step empty when none of its saved picks came back, and\n    // an empty step under its minimum stops the bundle going to the bag. So we find those steps\n    // first and leave their defaults alone.\n    const keptPrefixes: string[] = [];\n    for (const category of this.getCategoryElements()) {\n      const prefix = buildCategoryKeyPrefix(category);\n\n      let wasSaved = false;\n      for (const savedPick of savedPicks) {\n        if (savedPick.productKey.startsWith(prefix)) {\n          wasSaved = true;\n        }\n      }\n\n      let wasRestored = false;\n      for (const pick of picks) {\n        if (pick.productKey.startsWith(prefix)) {\n          wasRestored = true;\n        }\n      }\n\n      if (wasSaved && !wasRestored) {\n        keptPrefixes.push(prefix);\n      }\n    }\n\n    // the saved picks replace the defaults, except a required product and a kept step's defaults\n    for (let index = this.bundle.length - 1; index > -1; index--) {\n      const productKey = this.bundle[index].productKey;\n      const productElement = this.findProductElement(productKey);\n      if (isProductRequired(productElement)) {\n        continue;\n      }\n\n      let isKept = false;\n      for (const prefix of keptPrefixes) {\n        if (productKey.startsWith(prefix)) {\n          isKept = true;\n        }\n      }\n\n      if (isKept) {\n        continue;\n      }\n\n      this.bundle.splice(index, 1);\n    }\n\n    for (const pick of picks) {\n      const productElement = this.findProductElement(pick.productKey);\n      if (this.isInBundle(pick.productKey)) {\n        this.switchBundleItemVariant(productElement, pick.variantId);\n      } else {\n        this.addProductToBundle(productElement, pick.variantId);\n      }\n\n      this.updateUiSelectedVariant(productElement);\n    }\n  }\n\n  /**\n   * Returns the bundle entry a product contributed, if the product is in the bundle\n   */\n  private findBundleItem(productKey: string) {\n    for (const item of this.bundle) {\n      if (item.productKey === productKey) {\n        return item;\n      }\n    }\n\n    return undefined;\n  }\n\n  private isInBundle(productKey: string) {\n    return this.findBundleItem(productKey) ? true : false;\n  }\n\n  /**\n   * Returns the product element a product key was assigned to\n   */\n  private findProductElement(productKey: string) {\n    return this.querySelector<ProductElement>(\n      `bundle-category > bundle-item > product-element#${productKey}`);\n  }\n\n  /**\n   * Returns the category elements, in document order\n   */\n  private getCategoryElements() {\n    return this.querySelectorAll<BundleCategoryElement>('bundle-category[slot=\"categories\"]');\n  }\n\n  /**\n   * Whether the bundle authors any step whose products count toward the promo ladder. This reads\n   * the steps rather than what the customer has picked so far, so the slots and the headings hold\n   * still while they add and remove products.\n   */\n  private hasPromoSteps() {\n    for (const category of this.getCategoryElements()) {\n      if (isPromoCategory(category)) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * Returns the bundle entries that came from a category, in the order they were added\n   */\n  private getCategoryItems(category: BundleCategoryElement) {\n    const items: BundleItem[] = [];\n    const prefix = buildCategoryKeyPrefix(category);\n    for (const item of this.bundle) {\n      if (item.productKey.startsWith(prefix)) {\n        items.push(item);\n      }\n    }\n\n    return items;\n  }\n\n  /**\n   * Returns true when a category holds as many products as its maximum allows\n   */\n  private isCategoryFull(category: BundleCategoryElement) {\n    return this.getCategoryItems(category).length >= getCategoryLimits(category).maxItems;\n  }\n\n  /**\n   * Returns true when a category holds at least the minimum number of products it requires\n   */\n  private isCategoryMinimumMet(category: BundleCategoryElement) {\n    return this.getCategoryItems(category).length >= getCategoryLimits(category).minItems;\n  }\n\n  /**\n   * Compares a category's minimum-met status before and after some change to it, and dispatches\n   * `bundle-step-completed` or `bundle-step-undone` when it crossed. Reports nothing when the\n   * status did not change.\n   */\n  private reportCategoryMinimumTransition(category: BundleCategoryElement, wasMinimumMet: boolean) {\n    const isMinimumMet = this.isCategoryMinimumMet(category);\n    if (isMinimumMet === wasMinimumMet) {\n      return;\n    }\n\n    const detail = {\n      attribution_tag_value: this.dataset.attributionTagValue,\n      event_id: uuidv4(),\n      promo: isPromoCategory(category),\n      step_id: category.dataset.id,\n      step_label: category.dataset.label,\n      step_no: category.dataset.index\n    };\n\n    if (isMinimumMet) {\n      const stepCompleted = new CustomEvent<BundleStepCompletedEvent['detail']>(\n        'bundle-step-completed', { bubbles: true, composed: true, detail });\n      this.dispatchEvent(stepCompleted);\n    } else {\n      const stepUndone = new CustomEvent<BundleStepUndoneEvent['detail']>('bundle-step-undone',\n        { bubbles: true, composed: true, detail });\n      this.dispatchEvent(stepUndone);\n    }\n  }\n\n  /**\n   * Reports that a shopper opened a product's full details from the bundle builder, e.g. from a\n   * category's product grid. Modeled on the product-list-viewed/product-variant-viewed events.\n   */\n  private reportProductViewed(productElement: ProductElement) {\n    const variant = this.uiSelectedVariants.get(productElement.id);\n\n    const detail: BundleProductViewedEvent['detail'] = {\n      attribution_tag_value: this.dataset.attributionTagValue,\n      compare_at_price: variant?.dataset.compareAtPrice ?? '',\n      event_id: uuidv4(),\n      main_image: productElement.dataset.mainImage,\n      price: variant?.dataset.price ?? '',\n      product_id: productElement.dataset.id,\n      product_title: productElement.dataset.title,\n      sku: variant?.dataset.sku ?? '',\n      tags: productElement.dataset.tags,\n      type: productElement.dataset.type,\n      url: productElement.dataset.url,\n      variant_id: variant?.dataset.id ?? '',\n      variant_title: variant?.dataset.title ?? '',\n      yotpo_average: productElement.dataset.reviewsAverage,\n      yotpo_count: productElement.dataset.reviewsCount\n    };\n\n    const productViewed = new CustomEvent<BundleProductViewedEvent['detail']>(\n      'bundle-product-viewed', { bubbles: true, composed: true, detail });\n    this.dispatchEvent(productViewed);\n  }\n\n  /**\n   * Returns whether adding one more product to this category would leave no category with room\n   * anywhere in the bundle. The product modal reads this to label its CTA \"Add to Bag\" rather than\n   * \"Add to Bundle\", since picking the product completes the bundle and sends it straight to the\n   * cart instead of opening another step.\n   */\n  private wouldCompleteBundle(category: BundleCategoryElement) {\n    if (this.getCategoryItems(category).length + 1 < getCategoryLimits(category).maxItems) {\n      return false;\n    }\n\n    for (const otherCategory of this.getCategoryElements()) {\n      if (otherCategory !== category && !this.isCategoryFull(otherCategory)) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Writes the bundle into the light DOM, which is what makes the nodes cloned out of it carry the\n   * selection. The `product-price` and `add-to-cart` elements read it from those clones.\n   */\n  private projectBundleIntoDom() {\n    const productElements = this.querySelectorAll<ProductElement>(\n      'bundle-category[slot=\"categories\"] > bundle-item > [slot=\"product\"]');\n    for (const productElement of productElements) {\n      deselectAllVariants(productElement);\n    }\n\n    for (const item of this.bundle) {\n      const productElement = this.findProductElement(item.productKey);\n      if (productElement) {\n        selectVariant(productElement, item.variantId);\n      }\n    }\n  }\n\n  /**\n   * Opens the next category with room left once a category has just filled up. The filled category\n   * has already locked and closed itself in the render that followed the add. When no category has\n   * room left, every step is filled, so the bundle goes straight to the cart instead, the same way\n   * the add-to-bag button does.\n   */\n  private advancePastFullCategory(category: BundleCategoryElement) {\n    const nextCategory = this.findCategoryWithRoom();\n    if (!nextCategory) {\n      this.addBundleToCart();\n      return;\n    }\n\n    const nextCategoryCard = this.getCategoryCard(nextCategory);\n    if (nextCategoryCard) {\n      setCategoryOpenState(nextCategoryCard, true);\n    }\n\n    this.scrollToOpenedCategory(category, nextCategory);\n  }\n\n  /**\n   * Brings the step that just opened up to the top of the viewport, so that the customer lands on\n   * its first product.\n   *\n   * Collapsing the filled step takes its list out of the flow above everything below it, and the\n   * browser leaves the scroll position where it is, so the next step's list slides up under a\n   * viewport that has not moved. A customer who picked from the bottom of a long list lands part\n   * way down the next one with the earlier products above them, and because two promo steps often\n   * offer the same products, little on screen says the step changed.\n   *\n   * The scroll is measured from whichever of the two steps comes first. The collapsing body always\n   * sits below that step's header, so that header is in the same place before and after the\n   * collapse, while the later step's header is still animating towards its own final position when\n   * this runs. Anchoring on the earlier step also leaves its collapsed header on screen just above\n   * the one that opened, so the step numbers say which list the customer is on.\n   */\n  private scrollToOpenedCategory(category: BundleCategoryElement,\n    nextCategory: BundleCategoryElement) {\n    const collapsedIndex = parseInt(category.dataset.index, 10);\n    const openedIndex = parseInt(nextCategory.dataset.index, 10);\n    const anchorCategory = openedIndex < collapsedIndex ? nextCategory : category;\n\n    this.scrollToCategoryHeader(anchorCategory);\n  }\n\n  /**\n   * Scrolls the page so that the header of a step sits just below the site header\n   */\n  private scrollToCategoryHeader(category: BundleCategoryElement) {\n    const categoryCard = this.getCategoryCard(category);\n    const header = categoryCard?.querySelector('.header');\n    if (!header) {\n      return;\n    }\n\n    const rect = header.getBoundingClientRect();\n\n    // The header script measures the sticky site header and publishes the viewport y of its bottom\n    // edge as --content-position, so reading it puts the step header just below the site header at\n    // whatever height that header currently has. The fallback covers a page that renders no header\n    // section, where the variable is absent and parseFloat returns NaN.\n    const headerOffset = parseFloat(\n      getComputedStyle(document.body).getPropertyValue('--content-position')) || 80;\n\n    document.documentElement.scrollTop = scrollY + rect.top - headerOffset;\n  }\n\n  /**\n   * Reopens a category that no longer holds its minimum number of products, so that the shortfall\n   * is visible rather than hidden behind a collapsed header\n   */\n  private reopenCategoryBelowMinimum(category: BundleCategoryElement) {\n    if (this.isCategoryMinimumMet(category)) {\n      return;\n    }\n\n    const categoryCard = this.getCategoryCard(category);\n    if (categoryCard) {\n      setCategoryOpenState(categoryCard, true);\n    }\n  }\n\n  /**\n   * Returns the first category in document order that has not reached its maximum\n   */\n  private findCategoryWithRoom() {\n    const categories = this.getCategoryElements();\n    for (const category of categories) {\n      if (!this.isCategoryFull(category)) {\n        return category;\n      }\n    }\n\n    return undefined;\n  }\n\n  /**\n   * Returns the step to send the customer to. That is the first step that has not reached its\n   * minimum, or when every minimum is met, the first step that has not reached its maximum.\n   */\n  private suggestedStep() {\n    const categories = this.getCategoryElements();\n    for (const category of categories) {\n      if (!this.isCategoryMinimumMet(category)) {\n        return category;\n      }\n    }\n\n    return this.findCategoryWithRoom();\n  }\n\n  /**\n   * Shows the suggested step. The bundle details close if they are showing as a modal, a collapsed\n   * step opens, and the page scrolls to the step's header.\n   */\n  private showSuggestedStep() {\n    const category = this.suggestedStep();\n    if (!category) {\n      return;\n    }\n\n    if (this.getModal('bundle-details')?.dataset.modalState === 'open') {\n      this.closeModal();\n    }\n\n    const categoryCard = this.getCategoryCard(category);\n    if (categoryCard?.dataset.open === 'false') {\n      setCategoryOpenState(categoryCard, true);\n    }\n\n    this.scrollToCategoryHeader(category);\n  }\n\n  /**\n   * Returns true when every category holds at least its minimum number of products, which is what\n   * the bundle needs before it can be added to the cart\n   */\n  private areCategoryMinimumsMet() {\n    const categories = this.getCategoryElements();\n    for (const category of categories) {\n      if (!this.isCategoryMinimumMet(category)) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Returns the shadow DOM card rendered for a category\n   */\n  private getCategoryCard(category: BundleCategoryElement) {\n    return this.shadowRoot.querySelector<HTMLElement>(\n      `.category[data-category-index=\"${category.dataset.index}\"]`);\n  }\n\n  /**\n   * Gathers the bundled variant of every product in the bundle and stores them in the `variants`\n   * property, in document order rather than in the order they were added, splitting them into the\n   * promo and regular subsets on the way\n   */\n  private gatherVariantData() {\n    const variants: VariantElement[] = [];\n    const promoVariants: VariantElement[] = [];\n    const regularVariants: VariantElement[] = [];\n    const productElements = this.querySelectorAll<ProductElement>(\n      'bundle-category[slot=\"categories\"] > bundle-item > [slot=\"product\"]');\n    for (const productElement of productElements) {\n      const item = this.findBundleItem(productElement.id);\n      if (!item) {\n        continue;\n      }\n\n      const variantElement = productElement.querySelector<VariantElement>(\n        `:scope > variant-element[data-id=\"${item.variantId}\"]`);\n      if (!variantElement) {\n        continue;\n      }\n\n      variants.push(variantElement);\n\n      // the selector above only matches a product inside a category, so there is always one to read\n      const category = productElement.closest('bundle-category');\n      if (isPromoCategory(category)) {\n        promoVariants.push(variantElement);\n      } else {\n        regularVariants.push(variantElement);\n      }\n    }\n\n    this.variants = variants;\n    this.promoVariants = promoVariants;\n    this.regularVariants = regularVariants;\n  }\n\n  /**\n   * Gathers the promo tiers from the slotted `bundle-tier` elements and stores them in the `tiers`\n   * property, sorted by their threshold in ascending order\n   */\n  private gatherTierData() {\n    const tierElements = this.querySelectorAll<BundleTierElement>('[slot=\"tiers\"]');\n    this.tiers = parseTiers(tierElements, this.dataset.currencySymbol);\n  }\n\n  private gatherData() {\n    this.gatherVariantData();\n    this.gatherTierData();\n  }\n\n  private render() {\n    this.projectBundleIntoDom();\n    this.renderCategories();\n    this.renderStickyBar();\n    this.renderBundleItems();\n    this.renderPriceBoxes();\n    this.renderAddToCartElements();\n  }\n\n  private renderCategories() {\n    const categories = this.getCategoryElements();\n    for (const category of categories) {\n      const categoryCard = this.getCategoryCard(category);\n      if (!categoryCard) {\n        continue;\n      }\n\n      renderCategoryHeader(categoryCard, category);\n      this.renderCategoryChosen(categoryCard, category);\n      this.renderCategoryProducts(categoryCard, category);\n    }\n  }\n\n  /**\n   * Locks a step that has reached its maximum. We close it, stop its header from opening it again,\n   * and list the products it holds under the title, a card to each with the product's name, a\n   * button that opens its details and, unless the product is required, a button that takes it back\n   * out. Whether a step is locked comes from the bundle on every render rather than from anything\n   * we remember, so a product leaving the bundle by any route unlocks the step and opens it.\n   *\n   * A product keeps its card from one render to the next while the step stays locked. A render can\n   * run with the product's details open, and focus goes back to the card's button when they close.\n   */\n  private renderCategoryChosen(categoryCard: HTMLElement, category: BundleCategoryElement) {\n    const chosenItemTemplate = this.shadowRoot.querySelector('#chosen-item-template');\n    if (!(chosenItemTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    const header = categoryCard.querySelector<HTMLButtonElement>('.header');\n    const chosen = categoryCard.querySelector<HTMLElement>('.chosen');\n    const list = chosen.querySelector('ul');\n\n    const wasLocked = header.disabled;\n\n    // emptying the row drops the button that had focus, so a keyboard user would lose their place.\n    // We note it here and hand focus to the header once the step opens.\n    const focusWasInRow = chosen.contains(this.shadowRoot.activeElement);\n\n    if (!this.isCategoryFull(category)) {\n      list.innerHTML = '';\n      chosen.hidden = true;\n\n      // a disabled button cannot take focus, so the header has to be enabled before it gets it\n      header.disabled = false;\n\n      if (wasLocked) {\n        setCategoryOpenState(categoryCard, true);\n\n        if (focusWasInRow) {\n          header.focus();\n        }\n      }\n\n      return;\n    }\n\n    const keyPrefix = buildCategoryKeyPrefix(category);\n    const items: Element[] = [];\n    for (const variant of this.variants) {\n      const productElement = variant.closest('product-element');\n      if (!productElement.id.startsWith(keyPrefix)) {\n        continue;\n      }\n\n      const item =\n        list.querySelector(`li[data-product-key=\"${productElement.id}\"]`) ||\n        this.createChosenItem(chosenItemTemplate, productElement.id);\n\n      const image = item.querySelector('img');\n      image.src = variant.dataset.imageSrc || productElement.dataset.mainImage || '';\n\n      const title = productElement.dataset.metafieldsTitle || productElement.dataset.title || '';\n      const titleElement = item.querySelector('.title');\n      titleElement.textContent = title;\n\n      const subtitleElement = item.querySelector('.subtitle');\n      subtitleElement.textContent = productElement.dataset.metafieldsSubtitle || '';\n\n      const removeButton = item.querySelector('.remove');\n      if (!(removeButton instanceof HTMLButtonElement)) {\n        return;\n      }\n\n      removeButton.setAttribute('aria-label', 'Remove ' + title);\n      removeButton.hidden = isProductRequired(productElement);\n\n      items.push(item);\n    }\n\n    // a card already in its place is left alone, so only a product entering or leaving the step\n    // moves anything\n    for (let index = 0; index < items.length; index += 1) {\n      if (list.children[index] !== items[index]) {\n        list.insertBefore(items[index], list.children[index]);\n      }\n    }\n\n    while (list.children.length > items.length) {\n      list.lastElementChild.remove();\n    }\n\n    const caption = chosen.querySelector('.caption');\n    if (items.length === 1) {\n      caption.textContent = 'Selected item:';\n    } else {\n      caption.textContent = 'Selected items:';\n    }\n\n    chosen.hidden = false;\n    header.disabled = true;\n    setCategoryOpenState(categoryCard, false);\n  }\n\n  /**\n   * Builds the card for one product in a locked step. The card carries the product's key so a later\n   * render finds it again, and so do its buttons, so a click knows which product it is for.\n   */\n  private createChosenItem(template: HTMLTemplateElement, productKey: string) {\n    const fragment = document.importNode(template.content, true);\n\n    const item = fragment.querySelector('li');\n    item.dataset.productKey = productKey;\n\n    const detailsButton = item.querySelector<HTMLButtonElement>('.details');\n    detailsButton.dataset.productKey = productKey;\n    detailsButton.addEventListener('click', this.onChosenProductClickedBound);\n\n    const removeButton = item.querySelector<HTMLButtonElement>('.remove');\n    removeButton.dataset.productKey = productKey;\n    removeButton.addEventListener('click', this.onRemoveBundleItemClickedBound);\n\n    return item;\n  }\n\n  /**\n   * Generate a DOM node for a single product in the category based on the product data. Whether the\n   * product's step counts toward the promo ladder decides how the card prices it.\n   */\n  private renderProductCard(productCard: HTMLElement, product: BundleCategoryProduct,\n    promoStep: boolean) {\n    let imageUrl = product.imageUrl;\n    const uiSelectedVariant = this.uiSelectedVariants.get(product.productKey);\n    if (uiSelectedVariant.dataset.imageSrc) {\n      imageUrl = uiSelectedVariant.dataset.imageSrc;\n    }\n\n    const productImage = productCard.querySelector<HTMLImageElement>('.image');\n    // image alt is intentionally left empty as per a11y guidelines (the product title is already\n    // displayed as text in the card)\n    productImage.src = imageUrl;\n\n    const productTitle = productCard.querySelector('.title');\n    productTitle.textContent = product.title;\n\n    const productSubtitle = productCard.querySelector('.subtitle');\n    productSubtitle.textContent = product.subtitle;\n\n    const rating = productCard.querySelector('product-rating-stars');\n    rating.dataset.average = product.reviewsAverage;\n    rating.dataset.count = product.reviewsCount;\n\n    const variants = product.variants;\n    const availableVariants = variants.filter(filterAvailable);\n\n    if (availableVariants.length === 0) {\n      productCard.dataset.outOfStock = 'true';\n      const outOfStockBadge = productCard.querySelector<HTMLElement>(\n        '.badge[data-badge-type=\"out-of-stock\"]');\n      outOfStockBadge.hidden = false;\n\n      // the modal the button opens offers Notify Me rather than an add, so the label says so. The\n      // plus icon is left as is.\n      const addLabel = productCard.querySelector('.action-button .add .large');\n      addLabel.textContent = 'Notify me';\n    }\n\n    if (product.preselected) {\n      const bestForYouBadge = productCard.querySelector<HTMLElement>(\n        '.badge[data-badge-type=\"best-for-you\"]');\n      bestForYouBadge.hidden = false;\n    }\n\n    // the button opens the details modal rather than adding anything, so this picks which label\n    // shows rather than recording a pressed state. aria-pressed would say the button is a toggle,\n    // which it is not.\n    const actionButton = productCard.querySelector<HTMLElement>('.action-button');\n    if (this.isInBundle(product.productKey)) {\n      actionButton.dataset.inBundle = 'true';\n      productCard.classList.add('selected');\n    } else {\n      actionButton.dataset.inBundle = 'false';\n      productCard.classList.remove('selected');\n    }\n\n    // a promo product is repriced by the tier rather than by anything it carries on its own, so its\n    // card shows the plain price of the selected (or first) variant and the message below names the\n    // tier price. A regular product is bought at the price on its card, so that card shows the\n    // compare at price too. A bundle price the item carries is left to the message below, so the\n    // card names what the product costs on its own either way. product-price renders the gap\n    // between the two prices as a \"% OFF\" badge, which is left off because the discount message\n    // below already carries one.\n    const productPrice = productCard.querySelector('product-price');\n    productPrice.dataset.currencyCode = this.dataset.currencyCode;\n    productPrice.dataset.currencySymbol = this.dataset.currencySymbol;\n    const priceVariantElement = productPrice.querySelector<VariantElement>('variant-element');\n    priceVariantElement.dataset.price = uiSelectedVariant.dataset.price;\n    if (promoStep) {\n      priceVariantElement.dataset.compareAtPrice = '';\n    } else {\n      priceVariantElement.dataset.compareAtPrice = uiSelectedVariant.dataset.compareAtPrice ?? '';\n    }\n\n    productPrice.dataset.discountPercentage = 'false';\n\n    this.renderProductOffer(productCard, uiSelectedVariant, promoStep);\n\n    const backorderNote = productCard.querySelector<HTMLElement>('.backorder');\n    renderBackorderNote(backorderNote, uiSelectedVariant);\n\n    // under some circumstances, the product-price is updated twice in close succession and that\n    // causes a race condition if we only used the timestamp, so we add a random number to ensure\n    // that the product-price always re-renders with the correct price and discount\n    productPrice.dataset.update = Date.now().toString() + Math.random().toString();\n  }\n\n  /**\n   * Writes the offer a product carries on its own into the `product-discount-message` inside\n   * `container`, which is a category product card, a bundle list row, or the product details modal.\n   * A promo step's product is repriced by the tier instead of by its own offer, so it gets no code,\n   * though a message set per bundle item still shows. An item the bundle reprices names its bundle\n   * price instead, since the price above the message is what that product costs on its own. For a\n   * promo item that is the price its tier works out for it once it is picked. A list row sets\n   * `priceShowsBundlePrice` where its own price already shows what the bundle charges for the item,\n   * and the message then stays empty rather than say it twice.\n   */\n  private renderProductOffer(container: ParentNode, variant: VariantElement, promoStep: boolean,\n    priceShowsBundlePrice = false) {\n    const discountMessage = container.querySelector('product-discount-message');\n\n    // the currency code is not one of the element's observed attributes, so it goes on first,\n    // before an observed attribute triggers the render that reads it\n    discountMessage.dataset.currencyCode = this.dataset.currencyCode;\n    discountMessage.dataset.currencySymbol = this.dataset.currencySymbol;\n\n    const productElement = variant?.closest('product-element');\n\n    // an item can carry a message of its own, set per bundle item in the metaobject. The empty\n    // string is still written when it carries none, because the stylesheet hides the message when\n    // it and the code are both empty. An item the bundle reprices shows what it costs on its own\n    // above, so its message names the bundle price instead, laid out the way the element lays out\n    // the message it builds itself.\n    let messageOverride = productElement?.dataset.discountOverride ?? '';\n\n    // a regular item carries its bundle price. A promo item is repriced by its tier, so its bundle\n    // price is the one the tier works out for it, unless it carries a message of its own. A product\n    // the tier leaves at its own price has no bundle price and so no message.\n    let bundlePrice = '';\n    if (!promoStep) {\n      bundlePrice = getBundleItemPrice(variant);\n    } else if (!messageOverride && productElement) {\n      const promoPrice = this.getPromoPriceInBundle(productElement, variant);\n      if (promoPrice < parseInt(variant.dataset.price, 10)) {\n        bundlePrice = promoPrice.toString();\n      }\n    }\n\n    // a list row can show the bundle price in its own price, and a message naming it again reads as\n    // a repeat. We leave the message empty then, along with the item's own offer, which a bundle\n    // price replaces on a card as well.\n    const repeatsPrice = priceShowsBundlePrice && bundlePrice !== '';\n\n    if (repeatsPrice) {\n      messageOverride = '';\n    } else if (bundlePrice) {\n      // the saving is worked out the way product-discount-message works out its own, against the\n      // compare at price where the variant carries one and against its price where it does not\n      let compareAtPrice = parseInt(variant.dataset.compareAtPrice, 10);\n      if (!Number.isInteger(compareAtPrice)) {\n        compareAtPrice = parseInt(variant.dataset.price, 10);\n      }\n\n      const savings = 100 - Math.round(parseInt(bundlePrice, 10) / compareAtPrice * 100);\n      messageOverride = `<div>\n        <span class=\"price\">\n          <price-element\n            data-currency-code=\"${this.dataset.currencyCode}\"\n            data-currency-symbol=\"${this.dataset.currencySymbol}\"\n            data-subunits=\"${bundlePrice}\">\n          </price-element>\n        </span>\n        in bundle\n        <span class=\"badge\">${savings}% OFF</span>\n      </div>`;\n    }\n\n    discountMessage.dataset.messageOverride = messageOverride;\n    discountMessage.dataset.price = variant?.dataset.price ?? '';\n    discountMessage.dataset.compareAtPrice = variant?.dataset.compareAtPrice ?? '';\n\n    if (promoStep || !productElement || repeatsPrice) {\n      discountMessage.dataset.discountCode = '';\n      discountMessage.dataset.discountPercentage = '';\n    } else {\n      discountMessage.dataset.discountCode = productElement.dataset.discountCode ?? '';\n      discountMessage.dataset.discountPercentage = productElement.dataset.discountPercentage ?? '';\n    }\n  }\n\n  /**\n   * Returns a modal by name\n   */\n  private getModal(name: BundleModalName) {\n    return this.shadowRoot.querySelector<HTMLElement>('.' + name);\n  }\n\n  private showModal(name: BundleModalName) {\n    const modal = this.getModal(name);\n    if (modal) {\n      modal.dataset.open = 'true';\n    }\n  }\n\n  private onLearnMoreClicked(event: MouseEvent) {\n    if (!(event.currentTarget instanceof HTMLElement)) {\n      return;\n    }\n\n    const productElement = this.findProductElement(event.currentTarget.id);\n\n    // the card is not focusable, so focus comes back to the button that opens the modal. Pushing\n    // the card instead would hand the focus stack an element it cannot focus, and the restore would\n    // silently fall through to whatever opened an earlier modal.\n    const actionButton = event.currentTarget.querySelector('.action-button');\n    this.openProductDetails(productElement, actionButton);\n  }\n\n  private onChosenProductClicked(event: MouseEvent) {\n    if (event.currentTarget instanceof HTMLButtonElement) {\n      const productElement = this.findProductElement(event.currentTarget.dataset.productKey);\n      this.openProductDetails(productElement, event.currentTarget);\n    }\n  }\n\n  /**\n   * Opens the details of a product. Focus goes back to the opener when they close, so it has to be\n   * an element that can take focus.\n   */\n  private openProductDetails(productElement: ProductElement, opener: Element) {\n    this.renderProductDetailsModal(productElement);\n    this.reportProductViewed(productElement);\n\n    const focusEvent = new Event('focus-stack-push-requested', { bubbles: true, composed: true });\n    opener.dispatchEvent(focusEvent);\n\n    this.showModal('product-details');\n  }\n\n  /**\n   * Populates the product-details modal for a given product: its image carousel, variant selector,\n   * description, price, and Add/Remove CTA\n   */\n  private renderProductDetailsModal(productElement: ProductElement) {\n    const modal = this.getModal('product-details');\n    if (!(modal instanceof HTMLElement)) {\n      return;\n    }\n\n    const productKey = productElement.id;\n\n    const gallery = modal.querySelector('.media');\n    const galleryTemplate = this.shadowRoot.querySelector('#gallery-template');\n    if (!(galleryTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    // Each product gets a new carousel rather than reusing the last one, since the carousel only\n    // picks up its slides when it first connects. A new one also starts on the first slide.\n    const fragment = document.importNode(galleryTemplate.content, true);\n    const carousel = fragment.querySelector('carousel-element');\n\n    // the gallery hangs off the item rather than the product, so one product offered by two\n    // categories shows only the images belonging to the item that was opened\n    const itemElement = productElement.closest('bundle-item');\n    const images = itemElement.querySelectorAll(':scope > [slot=\"product-images\"] img');\n\n    const variantsSlide = document.createElement('div');\n    variantsSlide.dataset.carouselSlide = '';\n\n    for (const image of images) {\n      const clone = image.cloneNode(true);\n      if (!(clone instanceof HTMLImageElement)) {\n        return;\n      }\n\n      // the seed is lazy only so the page does not fetch it, and the gallery wants its images now\n      clone.loading = 'eager';\n\n      if (clone.dataset.variantId) {\n        if (variantsSlide.childNodes.length > 0) {\n          clone.hidden = true;\n        }\n\n        variantsSlide.appendChild(clone);\n      } else {\n        const slide = document.createElement('div');\n        slide.dataset.carouselSlide = '';\n        slide.appendChild(clone);\n        carousel.appendChild(slide);\n      }\n    }\n\n    if (variantsSlide.childNodes.length > 0) {\n      carousel.insertBefore(variantsSlide, carousel.firstChild);\n    }\n\n    // A lone slide has nowhere to move, so it gets no arrows and no drag bar\n    const slideCount = carousel.querySelectorAll(':scope > [data-carousel-slide]').length;\n    if (slideCount === 1) {\n      carousel.dataset.arrows = 'false';\n      carousel.dataset.slidebar = 'false';\n    }\n\n    gallery.innerHTML = '';\n    gallery.appendChild(fragment);\n\n    const uiSelectedVariant = this.uiSelectedVariants.get(productKey);\n    if (uiSelectedVariant) {\n      this.showVariantImage(uiSelectedVariant.dataset.id);\n    }\n\n    const variantSelector = modal.querySelector('.variant-selector select');\n    if (!(variantSelector instanceof HTMLSelectElement)) {\n      return;\n    }\n\n    // a sold-out variant stays selectable here, since the modal is where Notify Me lives\n    variantSelector.dataset.productKey = productKey;\n    const variantCount = renderVariantOptions(variantSelector, productElement,\n      uiSelectedVariant?.dataset.id, false);\n    variantSelector.parentElement.hidden = variantCount < 2;\n\n    const title = modal.querySelector('.title');\n    title.textContent = productElement.dataset.metafieldsTitle || '';\n\n    const subtitle = modal.querySelector('.subtitle');\n    subtitle.textContent = productElement.dataset.metafieldsSubtitle || '';\n\n    const description = modal.querySelector('.description');\n    description.textContent = productElement.dataset.shortDescription || '';\n\n    renderProductDetailsSections(modal, itemElement);\n\n    const rating = modal.querySelector('product-rating-stars');\n    // the stars skip drawing when a value is blank, so a product with no review data would keep\n    // showing the last product's rating. we fall back to zero, which draws empty stars\n    rating.dataset.average = productElement.dataset.reviewsAverage || '0';\n    rating.dataset.count = productElement.dataset.reviewsCount || '0';\n\n    this.renderProductModalPrice(modal, productElement);\n    this.renderProductModalCta(modal, productElement);\n  }\n\n  /**\n   * Sets the product details price, offer and installment estimate for the variant being previewed.\n   * Variants can have different prices, so this runs again whenever the shopper picks another one.\n   */\n  private renderProductModalPrice(modal: HTMLElement, productElement: ProductElement) {\n    const uiSelectedVariant = this.uiSelectedVariants.get(productElement.id);\n    const category = productElement.closest('bundle-category');\n\n    // the modal prices the product the same way its card does: a promo product plainly, with the\n    // tier price in its message, and a regular product against its compare at price\n    const promoStep = isPromoCategory(category);\n    const price = parseFloat(uiSelectedVariant?.dataset.price || '0');\n\n    const productPriceElement = modal.querySelector('product-price');\n    const productPriceVariant = productPriceElement.querySelector('variant-element');\n    productPriceVariant.dataset.price = price.toString();\n    if (promoStep) {\n      productPriceVariant.dataset.compareAtPrice = '';\n    } else {\n      productPriceVariant.dataset.compareAtPrice = uiSelectedVariant?.dataset.compareAtPrice ?? '';\n    }\n\n    productPriceElement.dataset.currencyCode = this.dataset.currencyCode;\n    productPriceElement.dataset.currencySymbol = this.dataset.currencySymbol;\n    productPriceElement.dataset.discountPercentage = 'false';\n\n    this.renderProductOffer(modal, uiSelectedVariant, promoStep);\n\n    // trigger re-render of the product price\n    productPriceElement.dataset.update = Date.now().toString();\n\n    const installmentPaymentMessage = modal.querySelector('installment-payment-message');\n    if (installmentPaymentMessage) {\n      installmentPaymentMessage.dataset.currencyCode = this.dataset.currencyCode;\n      installmentPaymentMessage.dataset.currencySymbol = this.dataset.currencySymbol;\n      installmentPaymentMessage.dataset.logoUrlAfterpay = this.dataset.installmentAfterpayLogo;\n      installmentPaymentMessage.dataset.logoUrlKlarna = this.dataset.installmentKlarnaLogo;\n      installmentPaymentMessage.dataset.threshold = this.dataset.installmentThreshold;\n\n      // the estimate is of what the customer pays, so an item the bundle reprices is estimated at\n      // its bundle price rather than at the price shown above\n      installmentPaymentMessage.dataset.estimatedTotal =\n        getBundleItemPrice(uiSelectedVariant) || price.toString();\n    }\n  }\n\n  /**\n   * Sets the product details CTA for the variant being previewed. An out of stock variant cannot go\n   * in the bundle, so we show a Notify Me button. When the product is already in the bundle, the\n   * CTA that removes it stays, with a line saying which variant the bundle holds. A variant on\n   * backorder shows its ship date above the CTA.\n   *\n   * The button builds its aria-label once, when it connects, so we make a fresh one each time\n   * rather than update the one already there.\n   */\n  private renderProductModalCta(modal: HTMLElement, productElement: ProductElement) {\n    const cta = modal.querySelector<HTMLButtonElement>('.product-modal-cta');\n    if (!(cta instanceof HTMLButtonElement)) {\n      return;\n    }\n\n    const productKey = productElement.id;\n    cta.dataset.productKey = productKey;\n\n    modal.querySelector('add-to-cart-notify-me-button')?.remove();\n\n    const backorderNote = modal.querySelector<HTMLElement>('.backorder');\n    const bundleNote = modal.querySelector('.ctas .note');\n    if (!(bundleNote instanceof HTMLElement)) {\n      return;\n    }\n\n    bundleNote.hidden = true;\n\n    const uiSelectedVariant = this.uiSelectedVariants.get(productKey);\n    if (uiSelectedVariant && uiSelectedVariant.dataset.available !== 'true') {\n      // a variant the customer cannot add shows no ship date\n      backorderNote.hidden = true;\n\n      // the bundle keeps the variant it has, so a product in it keeps the button that takes it out\n      // and a line naming that variant, since it is not the one on show\n      const bundleItem = this.findBundleItem(productKey);\n      if (bundleItem) {\n        const bundleVariant = productElement.querySelector(\n          `:scope > variant-element[data-id=\"${bundleItem.variantId}\"]`);\n        if (!(bundleVariant instanceof HTMLElement)) {\n          return;\n        }\n\n        bundleNote.textContent = `In your bundle: ${bundleVariant.dataset.title}`;\n        bundleNote.hidden = false;\n\n        cta.textContent = 'Remove from Bundle';\n        cta.setAttribute('aria-pressed', 'true');\n        cta.hidden = isProductRequired(productElement);\n      } else {\n        cta.hidden = true;\n      }\n\n      const notifyMeButton = document.createElement('add-to-cart-notify-me-button');\n\n      // if we know the customer's email, the signup form opens with it filled in\n      if (this.dataset.customerEmail) {\n        notifyMeButton.dataset.email = this.dataset.customerEmail;\n      }\n\n      notifyMeButton.dataset.full = 'true';\n      notifyMeButton.dataset.productUrl = productElement.dataset.url;\n      notifyMeButton.dataset.productId = productElement.dataset.id;\n      notifyMeButton.dataset.productTitle = productElement.dataset.title;\n      notifyMeButton.dataset.sku = uiSelectedVariant.dataset.sku;\n      notifyMeButton.dataset.variantId = uiSelectedVariant.dataset.id;\n      notifyMeButton.dataset.variantTitle = uiSelectedVariant.dataset.title;\n      cta.after(notifyMeButton);\n      return;\n    }\n\n    cta.hidden = false;\n    renderBackorderNote(backorderNote, uiSelectedVariant);\n\n    const productCategory = productElement.closest('bundle-category');\n\n    if (this.isInBundle(productKey)) {\n      cta.textContent = 'Remove from Bundle';\n      cta.setAttribute('aria-pressed', 'true');\n\n      // a required product stays in the bundle, so the button that would take it out is hidden\n      cta.hidden = isProductRequired(productElement);\n    } else if (this.wouldCompleteBundle(productCategory)) {\n      cta.textContent = 'Add to Bag';\n      cta.setAttribute('aria-pressed', 'false');\n    } else {\n      cta.textContent = 'Add to Bundle';\n      cta.setAttribute('aria-pressed', 'false');\n    }\n  }\n\n  /**\n   * Scrolls the product details modal down to the AI summary. A product without a summary still\n   * shows its heading and a line saying so, so the stars always have somewhere to land.\n   */\n  private onRatingStarsClicked(event: MouseEvent) {\n    const modal = this.getModal('product-details');\n\n    // The stars' `data-href` makes them a link and does no scrolling. The browser scrolls when it\n    // follows a link, but it does not look for the target inside shadow roots. The summary sits in\n    // one, so following the link here would only change the URL hash. We keep `data-href` so the\n    // stars still render as a link, cancel the jump, and scroll the modal ourselves.\n    event.preventDefault();\n\n    // We scroll until the summary sits at the top of the part of the modal that scrolls. The\n    // behavior is passed here instead of set in the stylesheet because a modal that always scrolled\n    // smoothly would also animate its return to the top each time it opens.\n    const summary = modal.querySelector<HTMLElement>('.ai-summary');\n    const scroller = modal.shadowRoot.querySelector('slot:not([name])');\n    const distance = summary.getBoundingClientRect().top - scroller.getBoundingClientRect().top;\n    const behavior = matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth';\n    scroller.scrollTo({ top: scroller.scrollTop + distance, behavior: behavior });\n\n    // Keyboard activation leaves focus on the stars, above the summary, so the next Tab would\n    // scroll the modal back up. We move focus to the summary, without letting it scroll.\n    summary.focus({ preventScroll: true });\n  }\n\n  /**\n   * Builds the promo side of the bundle preview: one slot per promo product, a locked slot for each\n   * tier still out of reach, and empty slots for the rest. A bundle that authors no promo step has\n   * no promo to fill, so it gets no slots and its regular items stand on their own.\n   */\n  private buildBundleSlots() {\n    const slots: BundlePreviewSlot[] = [];\n\n    if (!this.hasPromoSteps()) {\n      return slots;\n    }\n\n    const lockedTiers = this.getLockedTiers();\n\n    let highestThreshold = 0;\n    if (lockedTiers.length > 0) {\n      highestThreshold = lockedTiers[lockedTiers.length - 1].threshold;\n    }\n\n    // two is the floor rather than one so that a bundle with nothing in it still reads as a bundle,\n    // and so that a two item promo has somewhere to show its locked slot\n    const length = Math.max(this.promoVariants.length, highestThreshold, 2);\n\n    // prefill with empty slots\n    for (let index = 0; index < length; index++) {\n      slots.push({ kind: 'empty' });\n    }\n\n    // fill promo tiers\n    for (const tier of lockedTiers) {\n      slots[tier.threshold - 1] = { kind: 'locked', tier };\n    }\n\n    // fill product slots\n    for (let index = 0; index < this.promoVariants.length; index++) {\n      slots[index] = { kind: 'product', variant: this.promoVariants[index] };\n    }\n\n    return slots;\n  }\n\n  private renderCategoryProducts(categoryCard: HTMLElement, category: BundleCategoryElement) {\n    const list = categoryCard.querySelector('.products');\n    if (!list) {\n      return;\n    }\n\n    const products = gatherCategoryProducts(category);\n    for (const product of products) {\n      let productCard = list.querySelector<HTMLElement>(`.product#${product.productKey}`);\n\n      if (!productCard) {\n        const template = this.shadowRoot.querySelector('#product-template');\n        if (!(template instanceof HTMLTemplateElement)) {\n          return;\n        }\n\n        const fragment = document.importNode(template.content, true);\n\n        productCard = fragment.querySelector('.product');\n        if (!(productCard instanceof HTMLElement)) {\n          return;\n        }\n\n        productCard.id = product.productKey;\n\n        // the button is the card's only control, so every card would otherwise contribute an\n        // identical \"Add to bundle\" to a screen reader's list of controls. Listing its own id first\n        // keeps the visible label at the front of the computed name.\n        const titleId = `${product.productKey}-title`;\n        const actionId = `${product.productKey}-action`;\n        productCard.querySelector('.title').id = titleId;\n        const actionButton = productCard.querySelector('.action-button');\n        actionButton.id = actionId;\n        actionButton.setAttribute('aria-labelledby', `${actionId} ${titleId}`);\n\n        productCard.addEventListener('click', this.onLearnMoreClickedBound);\n\n        list.appendChild(productCard);\n      }\n\n      this.renderProductCard(productCard, product, isPromoCategory(category));\n    }\n  }\n\n  private onVariantChanged(event: Event) {\n    if (!(event.currentTarget instanceof HTMLSelectElement)) {\n      return;\n    }\n\n    const productKey = event.currentTarget.dataset.productKey;\n    const variantId = event.currentTarget.value;\n\n    const productElement = this.findProductElement(productKey);\n    const variantElement = productElement.querySelector<VariantElement>(\n      `:scope > variant-element[data-id=\"${variantId}\"]`);\n\n    this.uiSelectedVariants.set(productKey, variantElement);\n\n    const valueBefore = serializeBundle(this.bundle);\n\n    // a product already in the bundle takes an option it can buy at once, and an option it cannot\n    // buy stays a preview\n    this.switchBundleItemVariant(productElement, variantId);\n    this.saveBundleIfChanged(valueBefore);\n\n    this.showVariantImage(variantId);\n    const productModal = this.getModal('product-details');\n    this.renderProductModalPrice(productModal, productElement);\n    this.renderProductModalCta(productModal, productElement);\n\n    this.render();\n  }\n\n  /**\n   * Return the promo tier the bundle currently qualifies for, or nothing when it qualifies for none\n   */\n  private getActiveTier() {\n    return selectActiveTier(this.tiers, getVariantPrices(this.promoVariants));\n  }\n\n  /**\n   * Return all promo tiers that aren't unlocked yet, sorted by their threshold in ascending order\n   */\n  private getLockedTiers() {\n    const lockedTiers: Tier[] = [];\n    for (const tier of this.tiers) {\n      if (this.promoVariants.length < tier.threshold) {\n        lockedTiers.push(tier);\n      }\n    }\n\n    return lockedTiers;\n  }\n\n  /**\n   * Returns the price in cents the promo tier gives a product once it is picked, or the product's\n   * own price when no tier covers the bundle it would make\n   */\n  private getPromoPriceInBundle(productElement: ProductElement, variant: VariantElement) {\n    const prices = this.getPromoPricesAfterPick(productElement, variant);\n    const tier = selectActiveTier(this.tiers, prices);\n    if (!tier) {\n      return parseInt(variant.dataset.price, 10);\n    }\n\n    // the product comes first in the list, so its price is the first line\n    return tier.reward.apply(prices).linePrices[0];\n  }\n\n  /**\n   * Returns the price in cents of every product the promo bundle would hold once the given product\n   * is picked, with the given product first. A step already at its maximum drops its oldest pick to\n   * make room, the way `addProductToBundle` does. A bundle that always ends at one size counts at\n   * that size, with the places still empty priced like the given product.\n   */\n  private getPromoPricesAfterPick(productElement: ProductElement, variant: VariantElement) {\n    const category = productElement.closest('bundle-category');\n\n    // the product is first in the list, so it is left out of the others whether or not it is in the\n    // bundle already\n    const leaving = new Set<string>([productElement.id]);\n\n    const stepPicks: BundleItem[] = [];\n    for (const item of this.getCategoryItems(category)) {\n      if (item.productKey !== productElement.id) {\n        stepPicks.push(item);\n      }\n    }\n\n    // an unset maximum makes the overflow negative, which drops nothing\n    let overflow = stepPicks.length + 1 - getCategoryLimits(category).maxItems;\n    for (const item of stepPicks) {\n      if (overflow > 0) {\n        leaving.add(item.productKey);\n        overflow--;\n      }\n    }\n\n    const variants = [variant];\n    for (const promoVariant of this.promoVariants) {\n      if (!leaving.has(promoVariant.closest('product-element').id)) {\n        variants.push(promoVariant);\n      }\n    }\n\n    const prices = getVariantPrices(variants);\n\n    // the places still empty count at the product's price, since the bundle ends up that size\n    const fixedSize = this.getFixedPromoSize();\n    for (let count = prices.length; count < fixedSize; count++) {\n      prices.push(prices[0]);\n    }\n\n    return prices;\n  }\n\n  /**\n   * Returns how many products the promo steps add up to when each one asks for exactly as many as\n   * it allows, or 0 when any of them leaves room to choose\n   */\n  private getFixedPromoSize() {\n    let size = 0;\n    for (const category of this.getCategoryElements()) {\n      if (isPromoCategory(category)) {\n        const limits = getCategoryLimits(category);\n        if (limits.minItems !== limits.maxItems) {\n          return 0;\n        }\n\n        size += limits.maxItems;\n      }\n    }\n\n    return size;\n  }\n\n  /**\n   * Renders the mobile sticky bar: the row of bundle slot previews (products, locked promo tiers,\n   * and empty slots) plus the \"View Bundle\" CTA\n   */\n  private renderStickyBar() {\n    const stickyBar = this.shadowRoot.querySelector('.mobile-sticky-bar');\n    if (!stickyBar) {\n      return;\n    }\n\n    const bundleSlotsContainer = stickyBar.querySelector('.slots');\n    const productSlotTemplate = this.shadowRoot.querySelector('#product-slot-template');\n    const promoSlotTemplate = this.shadowRoot.querySelector('#promo-slot-template');\n    const emptySlotTemplate = this.shadowRoot.querySelector('#empty-slot-template');\n    const ellipsisTemplate = this.shadowRoot.querySelector('#ellipsis-template');\n\n    if (!(bundleSlotsContainer instanceof HTMLElement) ||\n      !(productSlotTemplate instanceof HTMLTemplateElement) ||\n      !(promoSlotTemplate instanceof HTMLTemplateElement) ||\n      !(emptySlotTemplate instanceof HTMLTemplateElement) ||\n      !(ellipsisTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    const message = stickyBar.querySelector('.message');\n    message.textContent = this.getCTAMessage();\n\n    bundleSlotsContainer.innerHTML = '';\n\n    const promoSlots = this.buildBundleSlots();\n\n    // with no promo step authored there is nothing for the regular items to stand beside, so they\n    // take the strip over and get the framed treatment themselves rather than sitting as tiles\n    // against an empty row\n    let slots = promoSlots;\n    if (promoSlots.length === 0) {\n      slots = this.regularVariants.map((variant): BundlePreviewSlot =>\n        ({ kind: 'product', variant }));\n    }\n\n    // the stylesheet spaces the strip differently when it holds only a couple of slots\n    bundleSlotsContainer.dataset.slotCount = slots.length.toString();\n\n    // matches the .visible-from-* breakpoints in this section's SCSS: 3 slots show by default, 5\n    // from 400px, and 7 from 570px. The regular items stand alongside them and take about one\n    // slot's room, so the promo slots give one up whenever they are there\n    let capacities = [3, 5, 7];\n    if (promoSlots.length > 0 && this.regularVariants.length > 0) {\n      capacities = [2, 4, 6];\n    }\n\n    let index = 0;\n    for (const slot of slots) {\n      let fragment;\n      if (slot.kind === 'product') {\n        fragment = document.importNode(productSlotTemplate.content, true);\n        const image = fragment.querySelector('img');\n        const product = slot.variant.closest('product-element');\n\n        if (image) {\n          image.src = slot.variant.dataset.imageSrc || product.dataset.mainImage || '';\n          image.alt = product.dataset.metafieldsTitle || product.dataset.title || '';\n        }\n      } else if (slot.kind === 'locked') {\n        fragment = document.importNode(promoSlotTemplate.content, true);\n        const label = fragment.querySelector('.label');\n        if (label) {\n          label.textContent = slot.tier.reward.getBadgeLabel();\n        }\n      } else {\n        fragment = document.importNode(emptySlotTemplate.content, true);\n      }\n\n      const item = fragment.querySelector('.slot');\n\n      let visibleFrom = -1;\n\n      for (const capacity of capacities) {\n        if (slots.length <= capacity || index < capacity - 1) {\n          visibleFrom = capacity;\n          break;\n        }\n      }\n\n      if (visibleFrom === -1) {\n        item.classList.add('is-hidden');\n      } else if (visibleFrom > 0) {\n        item.classList.add('visible-from-' + visibleFrom);\n      }\n\n      index += 1;\n\n      bundleSlotsContainer.appendChild(fragment);\n    }\n\n    const ellipsisFragment = document.importNode(ellipsisTemplate.content, true);\n    const ellipsisElement = ellipsisFragment.firstElementChild;\n    if (ellipsisElement) {\n      if (slots.length > capacities[0]) {\n        ellipsisElement.classList.add('is-visible');\n\n        for (const capacity of capacities) {\n          if (slots.length <= capacity) {\n            ellipsisElement.classList.add('hidden-from-' + capacity);\n            break;\n          }\n        }\n      }\n    }\n\n    bundleSlotsContainer.appendChild(ellipsisFragment);\n\n    if (promoSlots.length > 0) {\n      this.renderStickyBarRegularItems(bundleSlotsContainer);\n    }\n\n    // the bundle cannot be bought until every category holds its minimum number of products, the\n    // same condition renderAddToCartElements and addBundleToCart use\n    const complete = this.variants.length > 0 && this.areCategoryMinimumsMet();\n\n    const addToBagButton = stickyBar.querySelector<HTMLButtonElement>('.add-to-bag');\n    addToBagButton.disabled = !complete;\n  }\n\n  /**\n   * Appends the regular items to the sticky bar's slot strip, beside the promo slots. The promo\n   * slots are framed boxes because a frame reads as a place the bundle still has to fill, and a\n   * regular item fills none of them, so they sit apart from the slots as small unframed tiles under\n   * their own caption. This is only for a strip that has promo slots in it; without them the\n   * regular items are the strip and take the framed treatment themselves.\n   */\n  private renderStickyBarRegularItems(bundleSlotsContainer: HTMLElement) {\n    if (this.regularVariants.length === 0) {\n      return;\n    }\n\n    const regularItemsTemplate = this.shadowRoot.querySelector('#regular-items-template');\n    const tileTemplate = this.shadowRoot.querySelector('#regular-tile-template');\n    const overflowTemplate = this.shadowRoot.querySelector('#regular-overflow-template');\n\n    if (!(regularItemsTemplate instanceof HTMLTemplateElement) ||\n      !(tileTemplate instanceof HTMLTemplateElement) ||\n      !(overflowTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    const regularItemsFragment = document.importNode(regularItemsTemplate.content, true);\n\n    const tiles = regularItemsFragment.querySelector('.tiles');\n\n    // the strip has room for two tiles beside the promo slots, so a third one collapses the group\n    // down to one tile and a count of the rest\n    const tileCount = this.regularVariants.length > 2 ? 1 : this.regularVariants.length;\n\n    for (let index = 0; index < tileCount; index++) {\n      const variant = this.regularVariants[index];\n      const product = variant.closest('product-element');\n\n      const tileFragment = document.importNode(tileTemplate.content, true);\n      const image = tileFragment.querySelector('img');\n      image.src = variant.dataset.imageSrc || product.dataset.mainImage || '';\n\n      tiles.appendChild(tileFragment);\n    }\n\n    if (this.regularVariants.length > tileCount) {\n      const overflowFragment = document.importNode(overflowTemplate.content, true);\n      const overflow = overflowFragment.querySelector('.overflow');\n      overflow.textContent = '+' + (this.regularVariants.length - tileCount);\n\n      tiles.appendChild(overflowFragment);\n    }\n\n    bundleSlotsContainer.appendChild(regularItemsFragment);\n  }\n\n  private getCTAMessage(): string {\n    const lockedTiers = this.getLockedTiers();\n    const activeTier = this.getActiveTier();\n\n    if (lockedTiers.length === 0) {\n      if (!activeTier) {\n        return 'Add products to the bundle';\n      }\n\n      return 'You\\'ve unlocked ' + activeTier.reward.getOfferLabel();\n    }\n\n    if (this.promoVariants.length === 0) {\n      const highestTier = lockedTiers[lockedTiers.length - 1];\n\n      return 'Add products to unlock ' + highestTier.reward.getOfferLabel();\n    }\n\n    const nextTier = lockedTiers[0];\n\n    return this.getUnlockMessage(nextTier);\n  }\n\n  /**\n   * Says what the bundle still needs before a tier unlocks. The CTA and the locked rows in the\n   * bundle list both use it, so the two always word it the same.\n   */\n  private getUnlockMessage(tier: Tier) {\n    const remaining = tier.threshold - this.promoVariants.length;\n\n    return 'Add ' + remaining + ' more product' + (remaining === 1 ? '' : 's') +\n      ' to unlock ' + tier.reward.getOfferLabel();\n  }\n\n  /**\n   * Renders the bundle contents list: one row per selected product (with its price and a remove\n   * button), promo rows for locked tiers, and empty-slot placeholders\n   */\n  private renderBundleItems() {\n    const itemTemplate = this.shadowRoot.querySelector('#bundle-item-template');\n    const promoTemplate = this.shadowRoot.querySelector('#promo-template');\n    const emptyTemplate = this.shadowRoot.querySelector('#empty-template');\n    if (!(itemTemplate instanceof HTMLTemplateElement) ||\n      !(promoTemplate instanceof HTMLTemplateElement) ||\n      !(emptyTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    const messages = this.shadowRoot.querySelectorAll('.bundle .message');\n    for (const message of messages) {\n      message.textContent = this.getCTAMessage();\n    }\n\n    const slots = this.buildBundleSlots();\n\n    // the active tier reprices every line at once, so we price the whole bundle up front and then\n    // read each row's share out of the result\n    const activeTier = this.getActiveTier();\n    let linePrices: number[] = [];\n    if (activeTier) {\n      linePrices = activeTier.reward.apply(getVariantPrices(this.promoVariants)).linePrices;\n    }\n\n    const itemsContainers = this.shadowRoot.querySelectorAll('.bundle .items');\n    for (const itemsContainer of itemsContainers) {\n      itemsContainer.innerHTML = '';\n\n      for (const slot of slots) {\n        if (slot.kind === 'product') {\n          const variant = slot.variant;\n          const productElement = variant.closest('product-element');\n          if (!productElement) {\n            continue;\n          }\n\n          const productData = {\n            imageUrl: variant.dataset.imageSrc || productElement.dataset.mainImage || '',\n            subtitle: productElement.dataset.metafieldsSubtitle || '',\n            title: productElement.dataset.title || ''\n          };\n\n          const item = document.importNode(itemTemplate.content, true);\n\n          const titleElement = item.querySelector('.name');\n          titleElement.textContent = productData.title;\n\n          const imageElement = item.querySelector<HTMLImageElement>('.image');\n          imageElement.src = productData.imageUrl;\n\n          const subtitleElement = item.querySelector('.subtitle');\n          subtitleElement.textContent = productData.subtitle;\n\n          const productPriceElement = item.querySelector('product-price');\n          productPriceElement.dataset.currencyCode = this.dataset.currencyCode;\n          productPriceElement.dataset.currencySymbol = this.dataset.currencySymbol;\n          const productCopy = <ProductElement>productElement.cloneNode(true);\n\n          const selectedVariant = productCopy.querySelector<VariantElement>(\n            `:scope > variant-element[data-id=\"${variant.dataset.id}\"]`);\n          const linePrice = linePrices[this.promoVariants.indexOf(variant)];\n          if (linePrice === undefined) {\n            productPriceElement.dataset.discountPercentage = 'false';\n          } else {\n            const price = parseInt(selectedVariant.dataset.price, 10);\n            selectedVariant.dataset.compareAtPrice = selectedVariant.dataset.price;\n            selectedVariant.dataset.price = linePrice.toString();\n\n            // product-price renders the gap between the two prices as a \"% OFF\" badge, so we only\n            // ask for one where the line actually came down. A fixed price bundle splits its price\n            // evenly, which can push a cheap item's line above what that item costs on its own.\n            if (linePrice < price) {\n              productPriceElement.dataset.discountPercentage = 'true';\n            } else {\n              productPriceElement.dataset.discountPercentage = 'false';\n            }\n          }\n\n          productPriceElement.appendChild(productCopy);\n\n          // the row names the same offer as the product's card, unless its price already shows it\n          const priceShowsBundlePrice = productPriceElement.dataset.discountPercentage === 'true';\n          this.renderProductOffer(item, variant, true, priceShowsBundlePrice);\n          renderBackorderNote(item.querySelector<HTMLElement>('.backorder'), variant);\n\n          const removeButton = item.querySelector<HTMLButtonElement>('.remove');\n          removeButton.dataset.productKey = productElement.id;\n          removeButton.hidden = isProductRequired(productElement);\n          removeButton.addEventListener('click', this.onRemoveBundleItemClickedBound);\n\n          renderRowVariantChooser(item, productElement, variant.dataset.id);\n\n          itemsContainer.appendChild(item);\n        } else if (slot.kind === 'locked') {\n          const item = document.importNode(promoTemplate.content, true);\n          const promoTitleElement = item.querySelector('.label');\n          promoTitleElement.textContent = this.getUnlockMessage(slot.tier);\n\n          itemsContainer.appendChild(item);\n        } else if (slot.kind === 'empty') {\n          const item = document.importNode(emptyTemplate.content, true);\n          itemsContainer.appendChild(item);\n        }\n      }\n\n      this.renderBundleRegularItems(itemsContainer);\n    }\n  }\n\n  /**\n   * Appends one row per regular item to a bundle contents list, under a heading separating them\n   * from the slots above. A regular item is bought at its own price, so its row prices it on its\n   * own and names the offer it carries the way a product card does.\n   */\n  private renderBundleRegularItems(itemsContainer: Element) {\n    if (this.regularVariants.length === 0) {\n      return;\n    }\n\n    const headingTemplate = this.shadowRoot.querySelector('#regular-heading-template');\n    const itemTemplate = this.shadowRoot.querySelector('#bundle-item-template');\n\n    if (!(headingTemplate instanceof HTMLTemplateElement) ||\n      !(itemTemplate instanceof HTMLTemplateElement)) {\n      return;\n    }\n\n    // with no promo step authored these rows are the whole bundle, and the bundle's own title\n    // already names them\n    if (this.hasPromoSteps()) {\n      const heading = document.importNode(headingTemplate.content, true);\n      itemsContainer.appendChild(heading);\n    }\n\n    for (const variant of this.regularVariants) {\n      const productElement = variant.closest('product-element');\n      if (!productElement) {\n        continue;\n      }\n\n      const item = document.importNode(itemTemplate.content, true);\n\n      const titleElement = item.querySelector('.name');\n      titleElement.textContent = productElement.dataset.title || '';\n\n      const imageElement = item.querySelector<HTMLImageElement>('.image');\n      imageElement.src = variant.dataset.imageSrc || productElement.dataset.mainImage || '';\n\n      const subtitleElement = item.querySelector('.subtitle');\n      subtitleElement.textContent = productElement.dataset.metafieldsSubtitle || '';\n\n      // no tier reaches this line, so it shows the variant's own price with no badge against it. An\n      // item the bundle reprices is bought at that price here, with what it costs on its own struck\n      // through, the same way a tier repriced promo row shows its line price.\n      const bundlePrice = getBundleItemPrice(variant);\n      const productCopy = <ProductElement>productElement.cloneNode(true);\n      if (bundlePrice) {\n        const variantCopy = productCopy.querySelector<VariantElement>(\n          `:scope > variant-element[data-id=\"${variant.dataset.id}\"]`);\n        variantCopy.dataset.compareAtPrice = variant.dataset.price;\n        variantCopy.dataset.price = bundlePrice;\n      }\n\n      const productPriceElement = item.querySelector('product-price');\n      productPriceElement.dataset.currencyCode = this.dataset.currencyCode;\n      productPriceElement.dataset.currencySymbol = this.dataset.currencySymbol;\n      productPriceElement.dataset.discountPercentage = 'false';\n      productPriceElement.appendChild(productCopy);\n\n      // the row names the same offer as the product's card, unless its price already shows it. An\n      // item with a bundle price shows that price here.\n      this.renderProductOffer(item, variant, false, true);\n      renderBackorderNote(item.querySelector<HTMLElement>('.backorder'), variant);\n\n      const removeButton = item.querySelector<HTMLButtonElement>('.remove');\n      removeButton.dataset.productKey = productElement.id;\n      removeButton.hidden = isProductRequired(productElement);\n      removeButton.addEventListener('click', this.onRemoveBundleItemClickedBound);\n\n      renderRowVariantChooser(item, productElement, variant.dataset.id);\n\n      itemsContainer.appendChild(item);\n    }\n  }\n\n  /**\n   * Switches a bundle row to the variant picked in its dropdown. The rows are rebuilt by the\n   * render, so the dropdown the shopper was on is a new one and takes the focus back. A pick the\n   * bundle refuses is redrawn too, which puts the dropdown back on the variant the bundle holds.\n   */\n  private onRowVariantChanged(event: Event) {\n    if (!(event.target instanceof HTMLSelectElement)) {\n      return;\n    }\n\n    if (!(event.currentTarget instanceof HTMLElement)) {\n      return;\n    }\n\n    const productKey = event.target.dataset.productKey;\n    const productElement = this.findProductElement(productKey);\n    const valueBefore = serializeBundle(this.bundle);\n    this.switchBundleItemVariant(productElement, event.target.value);\n    this.saveBundleIfChanged(valueBefore);\n    this.render();\n\n    const chooser = event.currentTarget.querySelector(`select[data-product-key=\"${productKey}\"]`);\n    if (!(chooser instanceof HTMLSelectElement)) {\n      return;\n    }\n\n    chooser.focus();\n  }\n\n  private onRemoveBundleItemClicked(event: MouseEvent) {\n    if (!(event.currentTarget instanceof HTMLButtonElement)) {\n      return;\n    }\n\n    const productKey = event.currentTarget.dataset.productKey;\n    const productElement = this.findProductElement(productKey);\n    if (!productElement) {\n      return;\n    }\n\n    const category = productElement.closest('bundle-category');\n    const wasMinimumMet = this.isCategoryMinimumMet(category);\n\n    const valueBefore = serializeBundle(this.bundle);\n    this.removeProductFromBundle(productKey);\n    this.saveBundleIfChanged(valueBefore);\n    this.updateUiSelectedVariant(productElement);\n    this.reopenCategoryBelowMinimum(category);\n\n    this.gatherData();\n    this.render();\n    this.reportCategoryMinimumTransition(category, wasMinimumMet);\n  }\n\n  private renderPriceBoxes() {\n    const promoPrices = getVariantPrices(this.promoVariants);\n    const regularPrices = getVariantPrices(this.regularVariants);\n\n    let promoTotal = 0;\n    for (const price of promoPrices) {\n      promoTotal += price;\n    }\n\n    let regularTotal = 0;\n    for (const price of regularPrices) {\n      regularTotal += price;\n    }\n\n    const totalCompareAtPrice = promoTotal + regularTotal;\n\n    // the tier reprices the promo steps' products and nothing else, so the regular items are added\n    // back at their own price. One may still come down at the cart under whatever offer it carries\n    // on its own, which its row shows rather than this total.\n    const activeTier = this.getActiveTier();\n    if (activeTier) {\n      promoTotal = activeTier.reward.apply(promoPrices).total;\n    }\n\n    const totalPrice = promoTotal + regularTotal;\n\n    const productPrices = this.shadowRoot.querySelectorAll<ProductPriceElement>(\n      '.bundle .price product-price');\n    for (const productPrice of productPrices) {\n      productPrice.dataset.currencyCode = this.dataset.currencyCode;\n      productPrice.dataset.currencySymbol = this.dataset.currencySymbol;\n      renderPriceBox(productPrice, totalPrice, totalCompareAtPrice);\n    }\n\n    const installmentPaymentMessages = this.shadowRoot.querySelectorAll\n    <InstallmentPaymentMessageElement>('.bundle installment-payment-message');\n    for (const installmentPaymentMessage of installmentPaymentMessages) {\n      installmentPaymentMessage.dataset.currencyCode = this.dataset.currencyCode;\n      installmentPaymentMessage.dataset.currencySymbol = this.dataset.currencySymbol;\n      installmentPaymentMessage.dataset.logoUrlAfterpay = this.dataset.installmentAfterpayLogo;\n      installmentPaymentMessage.dataset.logoUrlKlarna = this.dataset.installmentKlarnaLogo;\n      installmentPaymentMessage.dataset.threshold = this.dataset.installmentThreshold;\n\n      // last, since the total is the only attribute the message re-renders on\n      installmentPaymentMessage.dataset.estimatedTotal = totalPrice.toString();\n    }\n\n    const priceContainers = this.shadowRoot.querySelectorAll<HTMLElement>('.bundle .price');\n    for (const priceContainer of priceContainers) {\n      if (this.variants.length === 0) {\n        priceContainer.hidden = true;\n      } else {\n        priceContainer.hidden = false;\n      }\n    }\n  }\n\n  /**\n   * Loads one add-to-cart with the bundle\n   */\n  private renderAddToCartElement(addToCart: AddToCartElement) {\n    // the add to cart element outlives each render, so this registers once and later renders pass\n    // the same bound listener, which does nothing\n    addToCart.addEventListener('cart-updated', this.onBundleAddedToCartBound);\n\n    // a promo step's product leads, so the main cart line is never a regular item while the bundle\n    // holds something the promo covers\n    const [mainVariant, ...bundleVariants] = [...this.promoVariants, ...this.regularVariants];\n    if (!mainVariant) {\n      return;\n    }\n\n    addToCart.innerHTML = '';\n\n    // AddToCart uses product and variant data from a slotted product element; we need to clone the\n    // variant nodes from the categories and append them to that product element with some custom\n    // attributes\n    const mainProduct = mainVariant.closest('product-element');\n    const mainProductClone = <ProductElement>mainProduct.cloneNode(true);\n    mainProductClone.slot = 'products';\n\n    // this copy sits under the option groups, which carry none of the variant's backorder data, so\n    // the data comes from the variant the builder tracks\n    const mainVariantClone = mainProductClone.querySelector<VariantElement>(\n      `variant-element[data-id=\"${mainVariant.dataset.id}\"]`);\n    setBackorderAttributes(mainVariantClone, mainVariant);\n\n    if (this.dataset.attributionTagValue) {\n      setCustomAttribute(mainVariantClone, '_bundle_builder', this.dataset.attributionTagValue);\n    }\n\n    addToCart.appendChild(mainProductClone);\n\n    for (const variant of bundleVariants) {\n      const addon = <VariantElement>variant.cloneNode(true);\n      // AddToCart expects a single product but it allows \"addons\"; we set an add-on flag on all\n      // subsequent variants\n      addon.slot = 'products';\n      addon.dataset.isAddon = 'true';\n\n      setBackorderAttributes(addon, variant);\n\n      if (this.dataset.attributionTagValue) {\n        setCustomAttribute(addon, '_bundle_builder', this.dataset.attributionTagValue);\n      }\n\n      addToCart.appendChild(addon);\n    }\n\n    const activeTier = this.getActiveTier();\n    if (activeTier) {\n      addToCart.dataset.discountCode = activeTier.discountCode;\n    } else {\n      delete addToCart.dataset.discountCode;\n    }\n\n    // trigger re-render of the add-to-cart\n    addToCart.dataset.update = Date.now().toString();\n  }\n\n  private renderAddToCartElements() {\n    const bundleAddToCartElements = this.shadowRoot.querySelectorAll<AddToCartElement>(\n      '.bundle add-to-cart');\n    for (const addToCart of bundleAddToCartElements) {\n      this.renderAddToCartElement(addToCart);\n    }\n\n    // the bundle cannot be bought until every category holds its minimum number of products\n    const complete = this.variants.length > 0 && this.areCategoryMinimumsMet();\n\n    const addToCartContainers = this.shadowRoot.querySelectorAll<HTMLElement>('.add-to-cart');\n    for (const addToCartContainer of addToCartContainers) {\n      addToCartContainer.hidden = !complete;\n    }\n  }\n\n  /**\n   * Handles a click on the mobile sticky bar. A locked or empty slot sends the customer to the step\n   * that needs products next. Any other click opens the bundle details.\n   */\n  private onViewBundleClicked(event: MouseEvent) {\n    if (event.target instanceof Element) {\n      if (event.target.closest('.slot.locked, .slot.empty')) {\n        this.showSuggestedStep();\n        return;\n      }\n    }\n\n    this.openBundleDetails();\n  }\n\n  /**\n   * Handles a click in a bundle details list. Locked and empty slots send the customer to the step\n   * that needs products next, and the product rows in the same list are left alone.\n   */\n  private onUnfilledSlotClicked(event: MouseEvent) {\n    if (!(event.target instanceof Element)) {\n      return;\n    }\n\n    if (!event.target.closest('.locked')) {\n      return;\n    }\n\n    this.showSuggestedStep();\n  }\n\n  /**\n   * The add-to-bag button sits inside the sticky bar that opens bundle details on click, so its own\n   * click is stopped here before it bubbles into that bar-level listener.\n   */\n  private onAddToBagClicked(event: MouseEvent) {\n    event.stopPropagation();\n    this.addBundleToCart();\n  }\n\n  /**\n   * Adds the bundle's current selection to the cart by forwarding the click through to the bundle's\n   * own add-to-cart element. That element already carries the right variants, discount code, and\n   * cart-transaction wiring.\n   */\n  private addBundleToCart() {\n    // the bundle cannot be bought until every category holds its minimum number of products, the\n    // same condition renderAddToCartElements hides the button's container on\n    if (this.variants.length === 0 || !this.areCategoryMinimumsMet()) {\n      return;\n    }\n\n    const addToCart = this.shadowRoot.querySelector<AddToCartElement>('.bundle .buy add-to-cart');\n    if (!addToCart || !addToCart.shadowRoot) {\n      return;\n    }\n\n    const addToCartButton = addToCart.shadowRoot.querySelector('add-to-cart-button');\n    if (!addToCartButton || !addToCartButton.shadowRoot) {\n      return;\n    }\n\n    const button = addToCartButton.shadowRoot.querySelector('button');\n    if (!button) {\n      return;\n    }\n\n    button.click();\n  }\n\n  /**\n   * Opens the bundle details modal\n   */\n  private openBundleDetails() {\n    const opener = this.shadowRoot.querySelector<HTMLElement>('.mobile-sticky-bar .add-to-bag');\n    if (!opener) {\n      return;\n    }\n\n    if (this.variants.length === 0) {\n      return;\n    }\n\n    const focusEvent = new Event('focus-stack-push-requested', { bubbles: true, composed: true });\n    opener.dispatchEvent(focusEvent);\n\n    this.showModal('bundle-details');\n  }\n\n  /**\n   * Closes whichever modal is open. Only one is ever open at a time.\n   */\n  private closeModal() {\n    const modal = this.shadowRoot.querySelector<HTMLElement>(\n      'modal-element[data-modal-state=\"open\"]');\n    if (modal) {\n      delete modal.dataset.open;\n    }\n  }\n\n  /**\n   * Starts a modal that just opened scrolled to the top, and makes the product grid and the sticky\n   * bar inert behind it.\n   */\n  private onModalOpened(event: ModalOpenedEvent) {\n    // a modal holds the scroll position it had when it was last closed, so without this a second\n    // product's details open part way down instead of at the gallery. The part that scrolls is the\n    // main slot in modal-element's shadow root.\n    if (event.target instanceof HTMLElement) {\n      const scroller = event.target.shadowRoot?.querySelector('slot:not([name])');\n      if (scroller) {\n        scroller.scrollTop = 0;\n      }\n    }\n\n    const interactiveAreas = this.shadowRoot.querySelectorAll(\n      '.product-selector, .mobile-sticky-bar');\n    for (const interactiveArea of interactiveAreas) {\n      if (interactiveArea instanceof HTMLElement) {\n        interactiveArea.inert = true;\n      }\n    }\n  }\n\n  /**\n   * Undoes what opening a modal did here. The modal manager restores focus only after this runs, so\n   * the grid is no longer inert by then.\n   */\n  private onModalClosed(event: ModalClosedEvent) {\n    const interactiveAreas = this.shadowRoot.querySelectorAll(\n      '.product-selector, .mobile-sticky-bar');\n    for (const interactiveArea of interactiveAreas) {\n      if (interactiveArea instanceof HTMLElement) {\n        interactiveArea.inert = false;\n      }\n    }\n\n    const productDetails = this.getModal('product-details');\n    if (productDetails && event.target === productDetails) {\n      this.resetPreviewToBundledVariant(productDetails);\n    }\n  }\n\n  /**\n   * Puts a product that is in the bundle back to showing the variant the bundle holds, once its\n   * details close. Picking an out of stock option leaves the bundle as it was and only previews\n   * that option, so without this the card, and the next time the details open, would keep showing\n   * it. A product not in the bundle keeps the option the visitor picked.\n   */\n  private resetPreviewToBundledVariant(modal: HTMLElement) {\n    const variantSelector = modal.querySelector('.variant-selector select');\n    if (!(variantSelector instanceof HTMLSelectElement)) {\n      return;\n    }\n\n    const productKey = variantSelector.dataset.productKey;\n\n    const item = this.findBundleItem(productKey);\n    if (!item) {\n      return;\n    }\n\n    const uiSelectedVariant = this.uiSelectedVariants.get(productKey);\n    if (uiSelectedVariant.dataset.id === item.variantId) {\n      return;\n    }\n\n    this.updateUiSelectedVariant(this.findProductElement(productKey));\n\n    // the bundle did not change, so there is nothing to gather\n    this.render();\n  }\n\n  /**\n   * Closes the product details when the Notify Me button is clicked, so the back in stock signup\n   * can open in its place. The signup opens from a listener on window. If we closed after that, the\n   * close would lower the backdrop and clear the inert flags the signup just set. So we listen on\n   * the button row, which runs before window, and close first.\n   */\n  private onNotifyMeClicked(_event: NotifyMeClickedEvent) {\n    this.closeModal();\n  }\n\n  private onCartTransactionStarted(_event: CartTransactionStartedEvent) {\n    const interactiveAreas = this.shadowRoot.querySelectorAll('.bundle');\n    for (const interactiveArea of interactiveAreas) {\n      if (interactiveArea instanceof HTMLElement) {\n        interactiveArea.inert = true;\n      }\n    }\n  }\n\n  /**\n   * Runs when the cart changes because of one of this element's own add to cart elements, which is\n   * the bundle being added. The button dispatches from inside its own shadow tree with `composed`\n   * set, so the event crosses into this element's tree on the way up to the window.\n   */\n  private onBundleAddedToCart(_event: CartUpdatedEvent) {\n    this.bundleAdded = true;\n  }\n\n  private onCartTransactionCompleted(_event: CartTransactionCompletedEvent) {\n    const interactiveAreas = this.shadowRoot.querySelectorAll('.bundle');\n    for (const interactiveArea of interactiveAreas) {\n      if (interactiveArea instanceof HTMLElement) {\n        interactiveArea.inert = false;\n      }\n    }\n\n    this.closeModal();\n\n    if (this.bundleAdded) {\n      this.bundleAdded = false;\n      this.resetBundle();\n      this.clearSavedBundle();\n    }\n  }\n\n  /**\n   * Close the open modal when an add to cart inside this element asks the cart drawer to open,\n   * which happens at click time, before the add finishes. The request bubbles up through this\n   * element before it reaches the window, where the drawer control listens, so the modal closes\n   * before the drawer opens. Closing after it would have the modal manager tear down the backdrop,\n   * the inert background, and the scroll lock out from under the open drawer.\n   */\n  private onCartOpenRequested(_event: CartOpenRequestedEvent) {\n    this.closeModal();\n  }\n\n  private showVariantImage(variantId: string) {\n    const allVariantImages =\n      this.shadowRoot.querySelectorAll<HTMLElement>('.media img[data-variant-id]');\n    for (const image of allVariantImages) {\n      image.hidden = true;\n    }\n\n    let current = this.shadowRoot.querySelector<HTMLElement>(\n      '.media img[data-variant-id=\"' + variantId + '\"]');\n    if (!current) {\n      current = this.shadowRoot.querySelector<HTMLElement>('.media img[data-variant-id]');\n    }\n\n    if (current) {\n      current.hidden = false;\n    }\n\n    const carousel = this.shadowRoot.querySelector('carousel-element');\n    if (carousel) {\n      carousel.dataset.go = '0';\n      carousel.dataset.refresh = '';\n    }\n  }\n\n  private onProductModalCtaClicked(event: MouseEvent) {\n    if (!(event.currentTarget instanceof HTMLButtonElement)) {\n      return;\n    }\n\n    const productKey = event.currentTarget.dataset.productKey;\n    const productElement = this.findProductElement(productKey);\n    if (!productElement) {\n      return;\n    }\n\n    const category = productElement.closest('bundle-category');\n    const wasMinimumMet = this.isCategoryMinimumMet(category);\n\n    const valueBefore = serializeBundle(this.bundle);\n    const wasInBundle = this.isInBundle(productKey);\n    if (wasInBundle) {\n      this.removeProductFromBundle(productKey);\n    } else {\n      const uiSelectedVariant = this.uiSelectedVariants.get(productKey);\n      this.addProductToBundle(productElement, uiSelectedVariant.dataset.id);\n    }\n\n    this.saveBundleIfChanged(valueBefore);\n    this.closeModal();\n\n    this.gatherData();\n    this.render();\n    this.reportCategoryMinimumTransition(category, wasMinimumMet);\n\n    if (wasInBundle) {\n      this.reopenCategoryBelowMinimum(category);\n    } else if (this.isCategoryFull(category)) {\n      this.advancePastFullCategory(category);\n    }\n  }\n}\n\n/**\n * Returns the `<bundle-item>` children of a category, one per thing the category offers.\n *\n * These are not the same as the category's bundle entries, which `getCategoryItems` returns. An\n * item here is offered whether or not the visitor took it.\n */\nfunction getCategoryItemElements(category: BundleCategoryElement) {\n  return category.querySelectorAll<BundleItemElement>(':scope > bundle-item');\n}\n\n/**\n * Returns the product an item offers. Everything an item holds hangs off the item rather than off\n * the category, so that the item's other parts can be found the same way.\n */\nfunction getItemProductElement(itemElement: BundleItemElement) {\n  return itemElement.querySelector<ProductElement>(':scope > [slot=\"product\"]');\n}\n\n/**\n * Returns whether an item is in the bundle from the start, which is also what marks it as picked\n * out for the visitor\n */\nfunction isItemPreselected(itemElement: BundleItemElement) {\n  return itemElement.dataset.selection === 'recommended' ||\n    itemElement.dataset.selection === 'required';\n}\n\n/**\n * Returns whether the product is locked into the bundle, so nothing offers the visitor a way to\n * take it out and a category trimmed to its maximum never drops it\n */\nfunction isProductRequired(productElement: ProductElement) {\n  return productElement.closest('bundle-item').dataset.selection === 'required';\n}\n\n/**\n * Builds a category's product list from the `<bundle-item>` children offering them\n */\nfunction gatherCategoryProducts(category: BundleCategoryElement) {\n  const products: BundleCategoryProduct[] = [];\n  for (const itemElement of getCategoryItemElements(category)) {\n    const productElement = getItemProductElement(itemElement);\n    if (!productElement) {\n      continue;\n    }\n\n    const product = <BundleCategoryProduct>{\n      imageUrl: productElement.dataset.mainImage ?? '',\n      preselected: isItemPreselected(itemElement),\n      productKey: productElement.id ?? '',\n      reviewsAverage: productElement.dataset.reviewsAverage ?? '',\n      reviewsCount: productElement.dataset.reviewsCount ?? '',\n      title: productElement.dataset.metafieldsTitle ?? productElement.dataset.title ?? '',\n      subtitle: productElement.dataset.metafieldsSubtitle ?? '',\n      url: productElement.dataset.url ?? '',\n      variants: []\n    };\n\n    const variantElements = productElement.querySelectorAll<HTMLElement>(\n      ':scope > variant-element');\n    type StepVariant = BundleCategoryProduct['variants'][number];\n    for (const variantElement of variantElements) {\n      const variant: StepVariant = {\n        available: variantElement.dataset.available === 'true',\n        imageSrc: variantElement.dataset.imageSrc ?? '',\n        price: parseInt(variantElement.dataset.price ?? '0', 10),\n        selected: variantElement.dataset.selected === 'true',\n        sku: variantElement.dataset.sku ?? '',\n        title: variantElement.dataset.title ?? ''\n      };\n\n      if (variantElement.dataset.compareAtPrice) {\n        const compareAtPrice = parseInt(variantElement.dataset.compareAtPrice, 10);\n        if (!isNaN(compareAtPrice)) {\n          variant.compareAtPrice = compareAtPrice;\n        }\n      }\n\n      product.variants.push(variant);\n    }\n\n    products.push(product);\n  }\n\n  return products;\n}\n\n/**\n * Renders a category card's index, label, and description text, and its open/closed state\n */\nfunction renderCategoryHeader(categoryCard: HTMLElement, category: BundleCategoryElement) {\n  const index = categoryCard.querySelector('.title .index');\n  index.textContent = category.dataset.index;\n\n  const title = categoryCard.querySelector('.title .label');\n  title.textContent = category.dataset.label;\n\n  const description = categoryCard.querySelector('.description');\n  description.textContent = category.dataset.description;\n\n  renderCategoryOpenState(categoryCard);\n}\n\n/**\n * Reflects a category card's open/closed state into its aria attributes and inert body\n */\nfunction renderCategoryOpenState(categoryCard: HTMLElement) {\n  const isOpen = categoryCard.dataset.open !== 'false';\n  const header = categoryCard.querySelector<HTMLButtonElement>('.header');\n  const body = categoryCard.querySelector<HTMLElement>('.body');\n\n  if (isOpen) {\n    header.setAttribute('aria-expanded', 'true');\n    body.inert = false;\n  } else {\n    header.setAttribute('aria-expanded', 'false');\n    body.inert = true;\n  }\n}\n\n/**\n * Opens or closes a category card and reflects the change into the DOM\n */\nfunction setCategoryOpenState(categoryCard: HTMLElement, open: boolean) {\n  categoryCard.dataset.open = open ? 'true' : 'false';\n  renderCategoryOpenState(categoryCard);\n}\n\n/**\n * Return what the given variant's item costs inside the bundle, in cents, or the empty string where\n * the bundle does not reprice it. The price is set per bundle item in the metaobject and sits on\n * the `bundle-item`, so the variant goes on carrying what the product costs on its own.\n *\n * A variant that has been cloned out of the light dom is no longer inside its item, so a caller\n * working on a copy reads this off the original.\n */\nfunction getBundleItemPrice(variant: VariantElement) {\n  // the annotation is what types the item. Naming the type as a type argument to `closest` instead\n  // picks the tag name map's own overload and fails against it, leaving the result error typed.\n  const item = variant?.closest('bundle-item');\n  let discountPrice = '';\n  if (item?.dataset.discountPrice) {\n    discountPrice = item.dataset.discountPrice;\n  }\n\n  return discountPrice;\n}\n\n/**\n * Return the price of each of the given variants, in cents, in the order they were given.\n *\n * A bundle item can set its own price in the metaobject. On a promo step that price is what feeds\n * the tier ladder here, so an item priced this way counts toward the tier at the price it was given\n * rather than its own.\n */\nfunction getVariantPrices(variants: VariantElement[]) {\n  const prices: number[] = [];\n  for (const variant of variants) {\n    const price = parseInt(getBundleItemPrice(variant) || variant.dataset.price, 10);\n    if (isNaN(price)) {\n      prices.push(0);\n    } else {\n      prices.push(price);\n    }\n  }\n\n  return prices;\n}\n\n/**\n * Returns true when a category's products count toward the promo ladder. A category that does not\n * say which kind it is counts, so a bundle authored before regular steps existed behaves as it did.\n */\nfunction isPromoCategory(category: BundleCategoryElement) {\n  return category.dataset.kind !== 'regular';\n}\n\n/**\n * Reads how many products a category needs and how many it allows. A limit that is missing or\n * unreadable means no limit, so the minimum falls back to none required and the maximum to no\n * ceiling.\n */\nfunction getCategoryLimits(category: BundleCategoryElement) {\n  const maxItems = parseInt(category.dataset.maxItems, 10);\n  const minItems = parseInt(category.dataset.minItems, 10);\n\n  return {\n    maxItems: isNaN(maxItems) ? Infinity : maxItems,\n    minItems: isNaN(minItems) ? 0 : minItems\n  };\n}\n\n/**\n * Builds the leading part of a product key that every product in a category shares. Ids hold no\n * dashes, so the trailing dash keeps category 12 from matching category 123's keys.\n */\nfunction buildCategoryKeyPrefix(category: BundleCategoryElement) {\n  return 'pk-' + category.dataset.id + '-';\n}\n\n/**\n * Builds the key identifying one of a category's items, which is also the id given to that item's\n * product element. The same product can be offered by more than one item, and by items in more than\n * one category, and both ids are part of the key so that acting on one leaves the rest alone.\n */\nfunction buildProductKey(category: BundleCategoryElement, itemElement: BundleItemElement) {\n  return buildCategoryKeyPrefix(category) + itemElement.dataset.id;\n}\n\n/**\n * Builds the name of the cookie that saves one bundle's picks\n */\nfunction buildBundleCookieName(bundleId: string) {\n  return 'bb_' + bundleId;\n}\n\n/**\n * Turns the bundle into the cookie's value. Each pick is its product key without the `pk-` prefix,\n * then its variant id, and the picks are joined by semicolons in the order they were added.\n */\nfunction serializeBundle(bundle: BundleItem[]) {\n  const picks: string[] = [];\n  for (const item of bundle) {\n    picks.push(item.productKey.replace('pk-', '') + '-' + item.variantId);\n  }\n\n  return picks.join(';');\n}\n\n/**\n * Turns the cookie's value back into picks. A piece that is not three ids is skipped, which also\n * keeps a hand edited cookie out of the id selector the product lookup builds.\n */\nfunction parseSavedBundle(value: string) {\n  const bundle: BundleItem[] = [];\n  for (const pick of value.split(';')) {\n    if (!/^\\d+-\\d+-\\d+$/.test(pick)) {\n      continue;\n    }\n\n    const dash = pick.lastIndexOf('-');\n    bundle.push({\n      productKey: 'pk-' + pick.slice(0, dash),\n      variantId: pick.slice(dash + 1)\n    });\n  }\n\n  return bundle;\n}\n\n/**\n * Toggles a category card's open/closed state and re-renders it\n */\nfunction onCategoryHeaderClicked(event: MouseEvent) {\n  if (!(event.currentTarget instanceof HTMLButtonElement)) {\n    return;\n  }\n\n  const categoryCard = event.currentTarget.closest('.category');\n  if (!(categoryCard instanceof HTMLElement)) {\n    return;\n  }\n\n  setCategoryOpenState(categoryCard, categoryCard.dataset.open === 'false');\n}\n\n/**\n * Applies a price, and a compare-at price if it's discounted, to a product price element\n */\nfunction renderPriceBox(productPrice: ProductPriceElement, price: number, compareAtPrice: number) {\n  const productElement = productPrice.querySelector<ProductElement>(':scope > product-element');\n  const firstVariant = productElement?.querySelector('variant-element');\n\n  // We can end up here before the browser has finished putting the price box's children on the\n  // page, and then there is nothing to write the price to, so we skip this box.\n  if (!firstVariant) {\n    return;\n  }\n\n  firstVariant.dataset.price = price.toString();\n\n  if (compareAtPrice > price) {\n    firstVariant.dataset.compareAtPrice = compareAtPrice.toString();\n    productPrice.dataset.discountPercentage = 'true';\n  } else {\n    firstVariant.dataset.compareAtPrice = '';\n    productPrice.dataset.discountPercentage = 'false';\n  }\n\n  // trigger re-render of the product price\n  productPrice.dataset.update = Date.now().toString();\n}\n\n/**\n * Clear the selected variant for the given product\n */\nfunction deselectAllVariants(product: ProductElement) {\n  const variantElements = product.querySelectorAll<VariantElement>(':scope > variant-element');\n  for (const variantElement of variantElements) {\n    variantElement.dataset.selected = 'false';\n  }\n\n  delete product.dataset.selectedVariantId;\n}\n\n/**\n * Returns the variant the given id names when that variant is available to buy, or the product's\n * first available variant when no id is given. Returns nothing when neither is available.\n */\nfunction findAvailableVariant(product: ProductElement, variantId?: string) {\n  if (variantId) {\n    return product.querySelector<VariantElement>(\n      `:scope > variant-element[data-id=\"${variantId}\"][data-available=\"true\"]`);\n  }\n\n  return product.querySelector<VariantElement>(':scope > variant-element[data-available=\"true\"]');\n}\n\n/**\n * Sets a custom attribute on a variant element, finding its existing `<custom-attribute>` child by\n * key first so this is safe to call again on every re-render without duplicating it.\n */\nfunction setCustomAttribute(variant: VariantElement, key: string, value: string) {\n  type CustomAttribute = HTMLElementTagNameMap['custom-attribute'];\n  let customAttribute = variant.querySelector<CustomAttribute>(\n    `custom-attribute[data-key=\"${key}\"]`);\n  if (!customAttribute) {\n    customAttribute = document.createElement('custom-attribute');\n    customAttribute.dataset.key = key;\n    variant.appendChild(customAttribute);\n  }\n\n  customAttribute.dataset.value = value;\n}\n\n/**\n * Sets the custom attributes the cart reads a variant's backorder from. The message and the pre-\n * order plan are checked independently, the same way a product page's add-ons do it. `source` is\n * the copy of the variant that carries the backorder data, and `target` is the copy the cart reads,\n * which can be a different one.\n */\nfunction setBackorderAttributes(target: VariantElement, source: VariantElement) {\n  if (source.dataset.backorder) {\n    setCustomAttribute(target, '_backorder_message', source.dataset.backorder);\n  }\n\n  if (source.dataset.backorderSellingPlanId) {\n    setCustomAttribute(target, 'selling_plan', source.dataset.backorderSellingPlanId);\n  }\n}\n\n/**\n * Fills a backorder note with the message a variant carries, and hides it for a variant that\n * carries none\n */\nfunction renderBackorderNote(note: HTMLElement, variant: VariantElement) {\n  const backorder = variant?.dataset.backorder;\n  note.textContent = backorder || '';\n  note.hidden = !backorder;\n}\n\n/**\n * Fills a variant dropdown with one option per variant of a product and selects the given one. An\n * unavailable variant is labelled, and it is also disabled when the dropdown must not let it be\n * picked. Returns how many variants the product has, so the caller can hide a dropdown that has\n * nothing to choose from.\n */\nfunction renderVariantOptions(select: HTMLSelectElement, productElement: ProductElement,\n  selectedVariantId: string, disableUnavailable: boolean) {\n  select.innerHTML = '';\n  const variants = productElement.querySelectorAll<VariantElement>(':scope > variant-element');\n  for (const variant of variants) {\n    const option = document.createElement('option');\n    option.value = variant.dataset.id;\n    option.textContent = variant.dataset.title;\n\n    if (variant.dataset.available !== 'true') {\n      option.textContent += ' (Out of Stock)';\n      option.disabled = disableUnavailable;\n    }\n\n    if (variant.dataset.id === selectedVariantId) {\n      option.selected = true;\n    }\n\n    select.appendChild(option);\n  }\n\n  return variants.length;\n}\n\n/**\n * Sets up the variant dropdown of a bundle row, with the product's current variant selected. The\n * row's dropdown disables unavailable variants, since a pick goes straight into the bundle.\n */\nfunction renderRowVariantChooser(row: DocumentFragment, productElement: ProductElement,\n  variantId: string) {\n  const chooser = row.querySelector('select');\n  chooser.dataset.productKey = productElement.id;\n  chooser.setAttribute('aria-label', `Variant of ${productElement.dataset.title}`);\n\n  const variantCount = renderVariantOptions(chooser, productElement, variantId, true);\n  chooser.hidden = variantCount < 2;\n}\n\n/**\n * Fills the product details modal's promise icons, selling points, details accordion and reviews\n * summary from the templates the item seeded. They stay inert inside their template until here, so\n * the icons are fetched and the elements upgraded only for a product somebody actually opens.\n */\nfunction renderProductDetailsSections(modal: HTMLElement, itemElement: Element) {\n  const promiseIcons = modal.querySelector<HTMLElement>('.promise-icons');\n  const promiseIconsSeed = itemElement.querySelector<HTMLTemplateElement>(\n    ':scope > template[data-promise-icons]');\n\n  promiseIcons.innerHTML = '';\n  if (promiseIconsSeed) {\n    promiseIcons.appendChild(promiseIconsSeed.content.cloneNode(true));\n  }\n\n  // a product with no promise icons seeds no template, so there is nothing to show\n  promiseIcons.hidden = !promiseIconsSeed;\n\n  const sellingPoints = modal.querySelector<HTMLElement>('.selling-points');\n  const sellingPointsSeed = itemElement.querySelector<HTMLTemplateElement>(\n    ':scope > template[data-selling-points]');\n\n  sellingPoints.innerHTML = '';\n  if (sellingPointsSeed) {\n    sellingPoints.appendChild(sellingPointsSeed.content.cloneNode(true));\n  }\n\n  // a product with too few selling points seeds no template, so there is nothing to show\n  sellingPoints.hidden = !sellingPointsSeed;\n\n  const detailsAccordion = modal.querySelector<HTMLElement>('.details-accordion');\n  const detailsSeed = itemElement.querySelector<HTMLTemplateElement>(\n    ':scope > template[data-product-details]');\n\n  // only the accordion travels. The snippet's heading above it leans on a document level utility\n  // class to stay invisible, and this shadow root does not have that class.\n  const accordion = detailsSeed?.content.querySelector('accordion-element');\n\n  // the snippet renders an accordion either way, so an empty one means the product filled in none\n  // of the detail metafields\n  const hasDetails = !!accordion?.querySelector('accordion-item');\n\n  detailsAccordion.innerHTML = '';\n  if (hasDetails) {\n    detailsAccordion.appendChild(accordion.cloneNode(true));\n  }\n\n  detailsAccordion.hidden = !hasDetails;\n\n  const aiSummary = modal.querySelector<HTMLElement>('.ai-summary');\n  const aiSummarySeed = itemElement.querySelector<HTMLTemplateElement>(\n    ':scope > template[data-ai-summary]');\n\n  aiSummary.innerHTML = '';\n  if (aiSummarySeed) {\n    aiSummary.appendChild(aiSummarySeed.content.cloneNode(true));\n  }\n}\n\n/**\n * Modify the DOM of the product element based on the selected variant id. If the id is not\n * provided, the first available variant will be selected.\n */\nfunction selectVariant(product: ProductElement, variantId?: string) {\n  deselectAllVariants(product);\n\n  const variantToSelect = findAvailableVariant(product, variantId);\n  if (variantToSelect) {\n    variantToSelect.dataset.selected = 'true';\n    product.dataset.selectedVariantId = variantToSelect.dataset.id;\n  }\n}\n\n/**\n * Return true if the variant is available for purchase, false if it's out of stock\n */\nfunction filterAvailable(variant: BundleCategoryProduct['variants'][number]) {\n  return variant.available;\n}\n\n/**\n * Reports that a category crossed from below its required minimum up to meeting it. We fire this\n * once per crossing, not once per add, so adding another product to a category that already meets\n * its minimum reports nothing.\n */\ntype BundleStepCompletedEvent = CustomEvent<{\n  /**\n   * The bundle's attribution_tag_value metaobject field\n   */\n  attribution_tag_value: string;\n\n  /**\n   * Identifies this occurrence so downstream pixels can deduplicate it\n   */\n  event_id: string;\n\n  /**\n   * Whether the step's products count toward the promo ladder\n   */\n  promo: boolean;\n\n  /**\n   * The step metaobject's numeric id\n   */\n  step_id: string;\n\n  /**\n   * The step's display label, e.g. \"Care\"\n   */\n  step_label: string;\n\n  /**\n   * The step's display index, e.g. \"1\", \"2\", \"3\"\n   */\n  step_no: string;\n}>;\n\n/**\n * Reports that a category fell from meeting its required minimum back below it. The bulk reset\n * after a successful cart add empties every category without firing this, since that's a fresh\n * start rather than the visitor backing out of one.\n */\ntype BundleStepUndoneEvent = CustomEvent<{\n  /**\n   * The bundle's attribution_tag_value metaobject field\n   */\n  attribution_tag_value: string;\n\n  /**\n   * Identifies this occurrence so downstream pixels can deduplicate it\n   */\n  event_id: string;\n\n  /**\n   * Whether the step's products count toward the promo ladder\n   */\n  promo: boolean;\n\n  /**\n   * The step metaobject's numeric id\n   */\n  step_id: string;\n\n  /**\n   * The step's display label, e.g. \"Care\"\n   */\n  step_label: string;\n\n  /**\n   * The step's display index, e.g. \"1\", \"2\", \"3\"\n   */\n  step_no: string;\n}>;\n\n/**\n * Reports that a shopper opened a product's full details from the bundle builder, e.g. from a\n * category's product grid. Modeled on product-list-viewed and product-variant-viewed.\n */\ntype BundleProductViewedEvent = CustomEvent<{\n  /**\n   * The bundle's attribution_tag_value metaobject field\n   */\n  attribution_tag_value: string;\n\n  /**\n   * The selected variant's compare-at price, empty when the product has no selected variant\n   */\n  compare_at_price: string;\n\n  /**\n   * Unique id for this view\n   */\n  event_id: string;\n\n  /**\n   * The product's main image url\n   */\n  main_image: string;\n\n  /**\n   * The selected variant's price, empty when the product has no selected variant\n   */\n  price: string;\n\n  /**\n   * The product metaobject's numeric id\n   */\n  product_id: string;\n\n  /**\n   * The product's title\n   */\n  product_title: string;\n\n  /**\n   * The selected variant's SKU, empty when the product has no selected variant\n   */\n  sku: string;\n\n  /**\n   * The product's tags\n   */\n  tags: string;\n\n  /**\n   * The product's type\n   */\n  type: string;\n\n  /**\n   * The product's url\n   */\n  url: string;\n\n  /**\n   * The selected variant's numeric id, empty when the product has no selected variant\n   */\n  variant_id: string;\n\n  /**\n   * The selected variant's title, empty when the product has no selected variant\n   */\n  variant_title: string;\n\n  /**\n   * Yotpo's average review rating for the product\n   */\n  yotpo_average: string;\n\n  /**\n   * Yotpo's review count for the product\n   */\n  yotpo_count: string;\n}>;\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'bundle-builder': BundleBuilder;\n  }\n\n  interface GlobalEventHandlersEventMap {\n    'bundle-product-viewed': BundleProductViewedEvent;\n    'bundle-step-completed': BundleStepCompletedEvent;\n    'bundle-step-undone': BundleStepUndoneEvent;\n  }\n}\n\nif (!customElements.get('bundle-builder')) {\n  customElements.define('bundle-builder', BundleBuilder);\n}\n"],"names":["assert","expression","message","AssertionError","Error","constructor","super","this","name","decorateError","error","key","value","assignmentError","reason","console","log","tag","Object","prototype","toString","call","YotpoAiSummarySimple","HTMLElement","fetchStarted","connectedCallback","initializeShadowRoot","startFetching","catch","warn","render","shadowRoot","attachShadow","mode","innerHTML","dataset","yotpoAppKey","productId","parseInt","response","async","input","app_key","Number","isInteger","product_id","path","fetch","ok","status","code","url","responseText","body","text","JSON","parse","fetchReviewsSummary","paragraphSummary","summaryTopics","summaryHighlights","topics","highlights","copy","querySelector","textContent","hidden","topicsList","topic","title","document","createElement","displayTopic","summary","mentioned","classList","add","coverage","li","appendChild","length","highlightsList","highlight","blockquote","content","safeDecode","decodeURIComponent","read","cookie","split","map","parts","_parts$slice","index","indexOf","encodedValue","slice","trim","undefined","filter","readAll","shift","write","push","encodeURIComponent","domain","expires","getTime","toUTCString","same_site","secure","join","serialize","customElements","get","define","rnds8","Uint8Array","byteToHex","i","unsafeStringify","arr","offset","toLowerCase","dist_v4","options","buf","crypto","randomUUID","_ref","_options$random","rnds","random","rng","getRandomValues","RangeError","_v4","PercentageReward","kind","percentage","apply","variantPrices","linePrices","total","variantPrice","linePrice","Math","round","getBadgeLabel","getOfferLabel","FixedPriceReward","bundlePrice","itemCount","currencySymbol","share","floor","formatAmount","selectActiveTier","tiers","activeTier","lowestTotal","tier","threshold","pricing","reward","compareThresholds","a","b","cents","dollars","toFixed","BundleBuilder","variants","promoVariants","regularVariants","uiSelectedVariants","Map","bundle","bundleAdded","onVariantChangedBound","onVariantChanged","bind","onRemoveBundleItemClickedBound","onRemoveBundleItemClicked","onViewBundleClickedBound","onViewBundleClicked","onAddToBagClickedBound","onAddToBagClicked","onModalOpenedBound","onModalOpened","onModalClosedBound","onModalClosed","onCartTransactionCompletedBound","onCartTransactionCompleted","onCartTransactionStartedBound","onCartTransactionStarted","onCartOpenRequestedBound","onCartOpenRequested","onLearnMoreClickedBound","onLearnMoreClicked","onChosenProductClickedBound","onChosenProductClicked","onProductModalCtaClickedBound","onProductModalCtaClicked","onBundleAddedToCartBound","onBundleAddedToCart","onUnfilledSlotClickedBound","onUnfilledSlotClicked","onRatingStarsClickedBound","onRatingStarsClicked","onNotifyMeClickedBound","onNotifyMeClicked","onRowVariantChangedBound","onRowVariantChanged","addEventListener","itemsContainers","querySelectorAll","itemsContainer","disconnectedCallback","removeEventListener","stickyBar","addToBagButton","productModalCta","ctaRow","variantSelector","ratingStars","bundleDetailsContent","bundleDetailsContainers","bundleDetailsContainer","HTMLTemplateElement","importNode","initializeCategories","categoriesContainer","categoryTemplate","categories","getCategoryElements","category","categoryCard","categoryIndex","open","bodyId","id","header","setAttribute","onCategoryHeaderClicked","itemElements","getCategoryItemElements","itemElement","productElement","getItemProductElement","buildProductKey","addPreselectedProducts","updateUiSelectedVariant","restoreSavedBundle","gatherData","startingCategory","findCategoryWithRoom","startingCategoryCard","getCategoryCard","setCategoryOpenState","productKey","variantElement","item","findBundleItem","variantId","set","addProductToBundle","findAvailableVariant","addedItem","closest","items","getCategoryItems","overflow","getCategoryLimits","maxItems","isProductRequired","findProductElement","removeItemFromBundle","switchBundleItemVariant","isItemPreselected","removeProductFromBundle","splice","resetBundle","saveBundleIfChanged","valueBefore","bundleId","serializeBundle","Date","setDate","getDate","buildBundleCookieName","debug","clearSavedBundle","_extends","savedPicks","pick","test","dash","lastIndexOf","parseSavedBundle","picks","savedPick","keptPrefixes","prefix","buildCategoryKeyPrefix","wasSaved","startsWith","wasRestored","isKept","isInBundle","hasPromoSteps","isPromoCategory","isCategoryFull","isCategoryMinimumMet","minItems","reportCategoryMinimumTransition","wasMinimumMet","isMinimumMet","detail","attribution_tag_value","attributionTagValue","event_id","promo","step_id","step_label","label","step_no","stepCompleted","CustomEvent","bubbles","composed","dispatchEvent","stepUndone","reportProductViewed","_variant$dataset$comp","_variant$dataset$pric","_variant$dataset$sku","_variant$dataset$id","_variant$dataset$titl","variant","compare_at_price","compareAtPrice","main_image","mainImage","price","product_title","sku","tags","type","variant_id","variant_title","yotpo_average","reviewsAverage","yotpo_count","reviewsCount","productViewed","wouldCompleteBundle","otherCategory","projectBundleIntoDom","productElements","deselectAllVariants","selectVariant","advancePastFullCategory","nextCategory","addBundleToCart","nextCategoryCard","scrollToOpenedCategory","collapsedIndex","anchorCategory","scrollToCategoryHeader","rect","getBoundingClientRect","headerOffset","parseFloat","getComputedStyle","getPropertyValue","documentElement","scrollTop","scrollY","top","reopenCategoryBelowMinimum","suggestedStep","showSuggestedStep","_this$getModal","getModal","modalState","closeModal","areCategoryMinimumsMet","gatherVariantData","gatherTierData","tierElements","elements","element","discountCode","isNaN","rewardValue","sort","parseTiers","renderCategories","renderStickyBar","renderBundleItems","renderPriceBoxes","renderAddToCartElements","renderCategoryHeader","renderCategoryChosen","renderCategoryProducts","chosenItemTemplate","chosen","list","wasLocked","disabled","focusWasInRow","contains","activeElement","focus","keyPrefix","createChosenItem","src","imageSrc","metafieldsTitle","metafieldsSubtitle","removeButton","HTMLButtonElement","children","insertBefore","lastElementChild","remove","caption","template","detailsButton","renderProductCard","productCard","product","promoStep","imageUrl","uiSelectedVariant","subtitle","rating","average","count","filterAvailable","outOfStock","preselected","actionButton","inBundle","productPrice","currencyCode","priceVariantElement","_uiSelectedVariant$da","discountPercentage","renderProductOffer","renderBackorderNote","update","now","container","priceShowsBundlePrice","_productElement$datas","_variant$dataset$pric2","_variant$dataset$comp2","discountMessage","messageOverride","discountOverride","promoPrice","getPromoPriceInBundle","getBundleItemPrice","repeatsPrice","savings","_productElement$datas2","_productElement$datas3","showModal","modal","event","currentTarget","openProductDetails","opener","renderProductDetailsModal","focusEvent","Event","gallery","galleryTemplate","fragment","carousel","images","variantsSlide","carouselSlide","image","clone","cloneNode","HTMLImageElement","loading","childNodes","slide","firstChild","arrows","slidebar","showVariantImage","HTMLSelectElement","variantCount","renderVariantOptions","parentElement","shortDescription","promiseIcons","promiseIconsSeed","sellingPoints","sellingPointsSeed","detailsAccordion","detailsSeed","accordion","hasDetails","aiSummary","aiSummarySeed","renderProductDetailsSections","renderProductModalPrice","renderProductModalCta","productPriceElement","productPriceVariant","_uiSelectedVariant$da2","installmentPaymentMessage","logoUrlAfterpay","installmentAfterpayLogo","logoUrlKlarna","installmentKlarnaLogo","installmentThreshold","estimatedTotal","_modal$querySelector","cta","backorderNote","bundleNote","available","bundleItem","bundleVariant","notifyMeButton","customerEmail","email","full","productUrl","productTitle","variantTitle","after","productCategory","preventDefault","scroller","distance","behavior","matchMedia","matches","scrollTo","preventScroll","buildBundleSlots","slots","lockedTiers","getLockedTiers","highestThreshold","max","products","_productElement$datas4","_productElement$id","_productElement$datas5","_productElement$datas6","_productElement$datas7","_productElement$datas8","_productElement$datas9","variantElements","_variantElement$datas","_variantElement$datas2","_variantElement$datas3","_variantElement$datas4","selected","gatherCategoryProducts","titleId","actionId","productModal","getActiveTier","getVariantPrices","prices","getPromoPricesAfterPick","leaving","Set","stepPicks","promoVariant","has","fixedSize","getFixedPromoSize","size","limits","bundleSlotsContainer","productSlotTemplate","promoSlotTemplate","emptySlotTemplate","ellipsisTemplate","getCTAMessage","promoSlots","slotCount","capacities","slot","alt","visibleFrom","capacity","ellipsisFragment","ellipsisElement","firstElementChild","renderStickyBarRegularItems","complete","regularItemsTemplate","tileTemplate","overflowTemplate","regularItemsFragment","tiles","tileCount","tileFragment","overflowFragment","nextTier","getUnlockMessage","remaining","itemTemplate","promoTemplate","emptyTemplate","messages","productData","productCopy","selectedVariant","renderRowVariantChooser","renderBundleRegularItems","headingTemplate","heading","variantCopy","target","chooser","promoPrices","regularPrices","promoTotal","regularTotal","totalCompareAtPrice","totalPrice","productPrices","renderPriceBox","installmentPaymentMessages","priceContainers","priceContainer","renderAddToCartElement","addToCart","mainVariant","bundleVariants","mainProductClone","mainVariantClone","setBackorderAttributes","setCustomAttribute","addon","isAddon","bundleAddToCartElements","addToCartContainers","addToCartContainer","Element","openBundleDetails","stopPropagation","addToCartButton","button","click","_event$target$shadowR","interactiveAreas","interactiveArea","inert","productDetails","resetPreviewToBundledVariant","_event","allVariantImages","current","go","refresh","wasInBundle","selection","description","renderCategoryOpenState","isOpen","discountPrice","Infinity","replace","firstVariant","selectedVariantId","customAttribute","source","backorder","backorderSellingPlanId","note","select","disableUnavailable","option","row","variantToSelect"],"sourceRoot":""}