{% assign bundle_product_id = 7853598048340 %}
{% if product and product.id == bundle_product_id %}
<style>
  .sofa-bundle {
    margin: 18px 0 20px;
    font-family: var(--font-body-family, inherit);
    color: var(--color-foreground, #111);
  }

  .sofa-bundle,
  .sofa-bundle button,
  .sofa-bundle div,
  .sofa-bundle li,
  .sofa-bundle span {
    font-family: inherit;
  }

  .sofa-bundle__intro {
    margin: 0 0 10px;
    font-size: 0.88rem;
    line-height: 1.4;
    color: rgb(from var(--color-foreground, #111) r g b / 70%);
  }

  .sofa-bundle__mode {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 12px;
    padding: 4px;
    border: 1px solid rgba(17, 17, 17, 0.1);
    border-radius: 10px;
    background: rgba(17, 17, 17, 0.035);
  }

  .sofa-bundle__mode-btn,
  .sofa-bundle__btn {
    width: 100%;
    min-height: 44px;
    border: 1px solid rgba(17, 17, 17, 0.12);
    background: #fff;
    color: inherit;
    border-radius: 8px;
    font-size: 0.92rem;
    font-weight: 500;
    line-height: 1.2;
    cursor: pointer;
    transition: border-color 0.15s ease, background-color 0.15s ease, box-shadow 0.15s ease;
  }

  .sofa-bundle__mode-btn {
    border-color: transparent;
    background: transparent;
  }

  .sofa-bundle__mode-btn.is-active,
  .sofa-bundle__btn.is-active {
    border-color: var(--color-foreground, #111);
    background: #fff;
    box-shadow: 0 0 0 1px var(--color-foreground, #111) inset;
  }

  .sofa-bundle__mode-btn:hover,
  .sofa-bundle__btn:hover {
    border-color: rgba(17, 17, 17, 0.3);
  }

  .sofa-bundle__heading {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin: 16px 0 10px;
    font-size: 0.86rem;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }

  .sofa-bundle__save-pill {
    display: inline-flex;
    align-items: center;
    min-height: 22px;
    padding: 2px 9px;
    border-radius: 999px;
    background: #2f7d32;
    color: #fff;
    font-size: 0.72rem;
    font-weight: 600;
    letter-spacing: 0;
    text-transform: none;
    white-space: nowrap;
  }

  .sofa-bundle__options {
    display: grid;
    gap: 10px;
  }

  .sofa-bundle__btn {
    padding: 12px 16px;
    text-align: center;
  }

  .sofa-bundle__details {
    display: none;
    margin-top: 12px;
    padding: 14px;
    border: 1px solid rgba(17, 17, 17, 0.08);
    border-radius: 8px;
    background: rgba(17, 17, 17, 0.035);
  }

  .sofa-bundle__details.is-visible {
    display: block;
  }

  .sofa-bundle__details-title {
    margin-bottom: 8px;
    font-size: 0.92rem;
    font-weight: 600;
  }

  .sofa-bundle__details ul {
    margin: 0;
    padding-left: 18px;
  }

  .sofa-bundle__details li {
    margin-bottom: 4px;
    font-size: 0.9rem;
    line-height: 1.35;
  }

  .sofa-bundle__pricing {
    margin-top: 12px;
    padding-top: 10px;
    border-top: 1px solid rgba(17, 17, 17, 0.08);
  }

  .sofa-bundle__price-original {
    font-size: 0.84rem;
    color: rgb(from var(--color-foreground, #111) r g b / 55%);
    text-decoration: line-through;
  }

  .sofa-bundle__price-discounted {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 4px;
    font-size: 1rem;
    font-weight: 600;
    color: #2f7d32;
  }

  .sofa-bundle__cta {
    display: none;
    width: 100%;
    margin-top: 12px;
    padding: 14px 18px;
    border: none;
    border-radius: var(--buttons-radius, 8px);
    background: var(--color-button, #111);
    color: var(--color-button-text, #fff);
    font-size: 0.92rem;
    font-weight: 600;
    cursor: pointer;
    transition: opacity 0.15s ease;
  }

  .sofa-bundle__cta.is-visible {
    display: block;
  }

  .sofa-bundle__cta:hover {
    opacity: 0.88;
  }

  .sofa-bundle__cta:disabled {
    opacity: 0.55;
    cursor: not-allowed;
  }

  .sofa-bundle__feedback {
    display: none;
    margin-top: 10px;
    font-size: 0.84rem;
    line-height: 1.35;
  }

  .sofa-bundle__feedback.is-visible {
    display: block;
  }

  .sofa-bundle__feedback--success {
    color: #2f7d32;
  }

  .sofa-bundle__feedback--error {
    color: #b42318;
  }

  body.sofa-bundle-mode-active .sofa-single-purchase-hidden {
    display: none !important;
  }
</style>

<div class="sofa-bundle" id="sofa-bundle-wrap" style="display:none">
  <p class="sofa-bundle__intro">Choose one cover by specification, or switch to a ready-made bundle. Select colour first for both options.</p>

  <div class="sofa-bundle__mode" role="group" aria-label="Purchase option">
    <button class="sofa-bundle__mode-btn is-active" data-purchase-mode="single" type="button">Single cover</button>
    <button class="sofa-bundle__mode-btn" data-purchase-mode="bundle" type="button">Bundle &amp; save 5%</button>
  </div>

  <div class="sofa-bundle__panel" id="sofa-bundle-panel" hidden>
    <div class="sofa-bundle__heading">
      <span>Bundle &amp; Save 5%</span>
      <span class="sofa-bundle__save-pill">5% off</span>
    </div>

    <div class="sofa-bundle__options">
      <button class="sofa-bundle__btn" data-bundle="one-seater" type="button">One Seater Bundle</button>
      <button class="sofa-bundle__btn" data-bundle="two-seater" type="button">Two Seater Bundle</button>
      <button class="sofa-bundle__btn" data-bundle="three-seater" type="button">Three Seater Bundle</button>
      <button class="sofa-bundle__btn" data-bundle="l-shaped" type="button">L-Shaped Bundle</button>
    </div>

    <div class="sofa-bundle__details" id="sofa-bundle-details">
      <div class="sofa-bundle__details-title" id="sofa-bundle-dtitle"></div>
      <ul id="sofa-bundle-dlist"></ul>
      <div class="sofa-bundle__pricing" id="sofa-bundle-pricing" style="display:none">
        <div class="sofa-bundle__price-original" id="sofa-bundle-original"></div>
        <div class="sofa-bundle__price-discounted">
          <span id="sofa-bundle-discounted"></span>
          <span class="sofa-bundle__save-pill">Applied with BUNDLE5</span>
        </div>
      </div>
    </div>

    <button class="sofa-bundle__cta" id="sofa-bundle-cta" type="button">Add bundle to cart - save 5%</button>
    <div class="sofa-bundle__feedback" id="sofa-bundle-fb"></div>
  </div>
</div>

<script type="module">
  import { CartAddEvent, DiscountUpdateEvent } from '@theme/events';

  (function () {
    const DISCOUNT_CODE = 'BUNDLE5';
    const DISCOUNT_PCT = 0.05;
    const PRODUCT_ID = {{ product.id | json }};
    const BUNDLE_SCRIPT_VERSION = "bundle-reattach-v15";

    const BUNDLES = {
      'one-seater': {
        label: 'One Seater Bundle',
        items: [
          { size: '90x90cm', qty: 2, label: '2 x Cushion Cover 90x90cm' },
          { size: '90x70cm', qty: 2, label: '2 x Cushion Cover 90x70cm' }
        ]
      },
      'two-seater': {
        label: 'Two Seater Bundle',
        items: [
          { size: '90x90cm', qty: 2, label: '2 x Cushion Cover 90x90cm' },
          { size: '90x70cm', qty: 2, label: '2 x Cushion Cover 90x70cm' },
          { size: '90x160cm', qty: 1, label: '1 x Seat Cover 90x160cm' }
        ]
      },
      'three-seater': {
        label: 'Three Seater Bundle',
        items: [
          { size: '90x90cm', qty: 3, label: '3 x Cushion Cover 90x90cm' },
          { size: '90x70cm', qty: 2, label: '2 x Cushion Cover 90x70cm' },
          { size: '90x240cm', qty: 1, label: '1 x Seat Cover 90x240cm' }
        ]
      },
      'l-shaped': {
        label: 'L-Shaped Bundle',
        items: [
          { size: '90x90cm', qty: 3, label: '3 x Cushion Cover 90x90cm' },
          { size: '90x70cm', qty: 3, label: '3 x Cushion Cover 90x70cm' },
          { size: '90x240cm', qty: 1, label: '1 x Seat Cover 90x240cm' },
          { size: '90x160cm', qty: 1, label: '1 x L-Shape Cover 90x160cm' }
        ]
      }
    };

    const VARIANTS = [
      {% for variant in product.variants %}
        {
          id: {{ variant.id }},
          color: {{ variant.option1 | json }},
          size: {{ variant.option2 | json }},
          price: {{ variant.price | json }},
          available: {{ variant.available | json }}
        }{% unless forloop.last %},{% endunless %}
      {% endfor %}
    ];

    const wrap = document.getElementById('sofa-bundle-wrap');
    if (!wrap) return;

    const modeButtons = wrap.querySelectorAll('[data-purchase-mode]');
    const bundleButtons = wrap.querySelectorAll('.sofa-bundle__btn');
    const panel = document.getElementById('sofa-bundle-panel');
    const details = document.getElementById('sofa-bundle-details');
    const detailTitle = document.getElementById('sofa-bundle-dtitle');
    const detailList = document.getElementById('sofa-bundle-dlist');
    const pricing = document.getElementById('sofa-bundle-pricing');
    const originalPrice = document.getElementById('sofa-bundle-original');
    const discountedPrice = document.getElementById('sofa-bundle-discounted');
    const cta = document.getElementById('sofa-bundle-cta');
    const feedback = document.getElementById('sofa-bundle-fb');

    let activeBundle = null;
    let currentPurchaseMode = 'single';
    let singleAddInFlight = false;

    function normalizeValue(value) {
      return String(value || '')
        .toLowerCase()
        .replace(/×/g, 'x')
        .replace(/grey/g, 'gray')
        .replace(/\s+/g, '')
        .trim();
    }

    function sameValue(left, right) {
      return normalizeValue(left) === normalizeValue(right);
    }

    function getOptionGroups() {
      return Array.from(document.querySelectorAll('variant-picker .variant-option'));
    }

    function getColorGroup() {
      return getOptionGroups().find((group) => {
        const select = group.querySelector('select');
        const label = group.querySelector('label');
        const text = ((label && label.textContent) || (select && select.name) || '').toLowerCase();
        return text.indexOf('color') > -1 || text.indexOf('colour') > -1;
      });
    }

    function getSpecificationGroup() {
      return getOptionGroups().find((group) => {
        const select = group.querySelector('select');
        const label = group.querySelector('label');
        const text = ((label && label.textContent) || (select && select.name) || '').toLowerCase();
        return text.indexOf('specification') > -1 || text.indexOf('size') > -1;
      });
    }

    function markSinglePurchaseControls() {
      const specificationGroup = getSpecificationGroup();
      if (specificationGroup) {
        specificationGroup.classList.add('sofa-single-purchase-hidden');
      }

      document.querySelectorAll(
        'quantity-selector-component, add-to-cart-component, .accelerated-checkout-block, .shopify-payment-button, .product-form-text__error'
      ).forEach((element) => {
        element.classList.add('sofa-single-purchase-hidden');
      });
    }

    function positionAndShow() {
      const colorGroup = getColorGroup();
      const specificationGroup = getSpecificationGroup();

      if (colorGroup && colorGroup.parentNode) {
        colorGroup.parentNode.insertBefore(wrap, colorGroup.nextSibling);
      } else if (specificationGroup && specificationGroup.parentNode) {
        specificationGroup.parentNode.insertBefore(wrap, specificationGroup);
      } else {
        const buyTarget = document.querySelector('product-form-component, .product-form-buttons, form[action="/cart/add"]');
        if (buyTarget && buyTarget.parentNode) {
          buyTarget.parentNode.insertBefore(wrap, buyTarget);
        }
      }

      markSinglePurchaseControls();
      setPurchaseMode(currentPurchaseMode);
      wrap.style.display = '';
    }

    function getColor() {
      const colorGroup = getColorGroup();
      const colorSelect = colorGroup ? colorGroup.querySelector('select') : null;
      if (colorSelect && colorSelect.value) {
        return colorSelect.value;
      }

      const checkedColor = colorGroup ? colorGroup.querySelector('input[type="radio"]:checked') : null;
      if (checkedColor && checkedColor.value) {
        return checkedColor.value;
      }

      const masterSelect = document.querySelector('select[name="id"], form[action*="/cart/add"] [name="id"]');
      if (masterSelect && masterSelect.value) {
        const selectedId = parseInt(masterSelect.value, 10);
        const matchedVariant = VARIANTS.find((variant) => variant.id === selectedId);
        if (matchedVariant) return matchedVariant.color;
      }

      return VARIANTS.length ? VARIANTS[0].color : null;
    }

    function getSpecification() {
      const specificationGroup = getSpecificationGroup();
      const specificationSelect = specificationGroup ? specificationGroup.querySelector('select') : null;
      if (specificationSelect && specificationSelect.value) {
        return specificationSelect.value;
      }

      const checkedSpecification = specificationGroup ? specificationGroup.querySelector('input[type="radio"]:checked') : null;
      if (checkedSpecification && checkedSpecification.value) {
        return checkedSpecification.value;
      }

      const variantInput = document.querySelector('form[action*="/cart/add"] [name="id"]');
      if (variantInput && variantInput.value) {
        const selectedId = parseInt(variantInput.value, 10);
        const matchedVariant = VARIANTS.find((variant) => variant.id === selectedId);
        if (matchedVariant) return matchedVariant.size;
      }

      return VARIANTS.length ? VARIANTS[0].size : null;
    }

    function getSelectedSingleVariant() {
      const color = getColor();
      const size = getSpecification();
      if (!color || !size) return null;

      return VARIANTS.find((variant) => {
        return sameValue(variant.color, color) && sameValue(variant.size, size);
      }) || null;
    }

    function getSingleProductForms() {
      return Array.from(document.querySelectorAll(
        'product-form-component[data-product-id="' + PRODUCT_ID + '"] form[action*="/cart/add"], form.shopify-product-form[action*="/cart/add"]'
      ));
    }

    function setSingleAddButtonsDisabled(disabled) {
      getSingleProductForms().forEach((form) => {
        const button = form.querySelector('button[name="add"], add-to-cart-component button');
        if (!button) return;

        if (disabled) {
          button.setAttribute('disabled', 'true');
          return;
        }

        button.removeAttribute('disabled');
      });
    }

    function syncSingleVariantSelection() {
      const variant = getSelectedSingleVariant();
      if (!variant) {
        setSingleAddButtonsDisabled(true);
        return null;
      }

      getSingleProductForms().forEach((form) => {
        form.querySelectorAll('[name="id"]').forEach((input) => {
          if ('value' in input) {
            input.value = String(variant.id);
          }
        });
      });

      setSingleAddButtonsDisabled(!variant.available);
      return variant;
    }

    function scheduleSingleVariantSync() {
      window.setTimeout(syncSingleVariantSelection, 0);
      window.setTimeout(syncSingleVariantSelection, 250);
    }

    function scheduleBundlePosition() {
      window.setTimeout(positionAndShow, 80);
      window.setTimeout(positionAndShow, 320);
      window.setTimeout(positionAndShow, 800);
    }

    function getSingleFormFromTarget(target) {
      if (!(target instanceof HTMLElement)) return null;

      const form = target.closest('form[action*="/cart/add"]');
      if (!(form instanceof HTMLFormElement)) return null;

      const productForm = form.closest('product-form-component');
      if (productForm instanceof HTMLElement && productForm.dataset.productId && productForm.dataset.productId !== String(PRODUCT_ID)) {
        return null;
      }

      return form;
    }

    function getAddButtonFromForm(form) {
      return form.querySelector('button[name="add"], add-to-cart-component button[type="submit"]');
    }

    function getQuantityFromForm(form) {
      const quantityInput = form.querySelector('[name="quantity"]');
      const quantity = parseInt(quantityInput && quantityInput.value ? quantityInput.value : '1', 10);
      return Number.isFinite(quantity) && quantity > 0 ? quantity : 1;
    }

    function setAddButtonText(button, text) {
      if (!(button instanceof HTMLElement)) return;

      const label = button.querySelector('.add-to-cart-text__content');
      if (label) {
        if (!button.dataset.sofaOriginalText) {
          button.dataset.sofaOriginalText = label.textContent || 'Add to cart';
        }
        label.textContent = text;
        return;
      }

      if (!button.dataset.sofaOriginalText) {
        button.dataset.sofaOriginalText = button.textContent || 'Add to cart';
      }
      button.textContent = text;
    }

    function restoreAddButtonText(button) {
      if (!(button instanceof HTMLElement) || !button.dataset.sofaOriginalText) return;

      const label = button.querySelector('.add-to-cart-text__content');
      if (label) {
        label.textContent = button.dataset.sofaOriginalText;
      } else {
        button.textContent = button.dataset.sofaOriginalText;
      }
    }

    function isVariantPickerControl(target) {
      if (!(target instanceof HTMLElement) || !target.closest('variant-picker')) return false;

      const name = String(target.getAttribute('name') || target.id || '').toLowerCase();
      return name.indexOf('options[') > -1 || name.indexOf('color') > -1 || name.indexOf('colour') > -1 || name.indexOf('specification') > -1 || name.indexOf('size') > -1;
    }

    function resolveBundle(bundleKey, color) {
      const bundle = BUNDLES[bundleKey];
      if (!bundle) return null;

      const resolved = [];
      const missing = [];

      bundle.items.forEach((item) => {
        const matchedVariant = VARIANTS.find((variant) => {
          return variant.available && sameValue(variant.color, color) && sameValue(variant.size, item.size);
        });

        if (!matchedVariant) {
          missing.push(item.size);
          return;
        }

        resolved.push({
          variantId: matchedVariant.id,
          quantity: item.qty,
          label: item.label,
          price: matchedVariant.price
        });
      });

      return missing.length ? null : resolved;
    }

    function formatMoney(cents) {
      return (cents / 100).toLocaleString('en-AU', { style: 'currency', currency: 'USD' });
    }

    function updatePricing(items) {
      if (!items || !items.length) {
        pricing.style.display = 'none';
        return;
      }

      const total = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
      const discounted = items.reduce((sum, item) => sum + (Math.round(item.price * (1 - DISCOUNT_PCT)) * item.quantity), 0);

      originalPrice.textContent = 'Was ' + formatMoney(total);
      discountedPrice.textContent = formatMoney(discounted);
      pricing.style.display = '';
    }

    function resetFeedback() {
      feedback.textContent = '';
      feedback.className = 'sofa-bundle__feedback';
    }

    function setFeedback(message, type) {
      feedback.textContent = message;
      feedback.className = 'sofa-bundle__feedback is-visible sofa-bundle__feedback--' + type;
    }

    function setPurchaseMode(mode) {
      currentPurchaseMode = mode === 'bundle' ? 'bundle' : 'single';
      const isBundleMode = currentPurchaseMode === 'bundle';

      document.body.classList.toggle('sofa-bundle-mode-active', isBundleMode);
      panel.hidden = !isBundleMode;

      modeButtons.forEach((button) => {
        button.classList.toggle('is-active', button.getAttribute('data-purchase-mode') === currentPurchaseMode);
      });

      if (isBundleMode && !activeBundle) {
        renderBundle('one-seater');
      }

      if (!isBundleMode) {
        resetFeedback();
        syncSingleVariantSelection();
      }
    }

    function getCartSectionIds() {
      const ids = new Set();

      document.querySelectorAll('cart-items-component[data-section-id], cart-discount-component[data-section-id]').forEach((element) => {
        if (element instanceof HTMLElement && element.dataset.sectionId) {
          ids.add(element.dataset.sectionId);
        }
      });

      return Array.from(ids);
    }

    function getExistingDiscountCodes() {
      const codes = [];
      document.querySelectorAll('.cart-discount__pill[data-discount-code]').forEach((element) => {
        if (element instanceof HTMLElement && element.dataset.discountCode) {
          codes.push(element.dataset.discountCode);
        }
      });
      return codes;
    }

    async function addBundleToCart(items) {
      const response = await fetch('/cart/add.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          items: items.map((item) => ({ id: item.variantId, quantity: item.quantity }))
        })
      });

      const data = await response.json();
      if (!response.ok || data.status) {
        throw new Error(data.description || data.message || 'Could not add the bundle to cart.');
      }

      return data;
    }

    async function addSingleItemToCart(variant, quantity) {
      const sectionIds = getCartSectionIds();
      const payload = {
        id: variant.id,
        quantity: quantity
      };

      if (sectionIds.length) {
        payload.sections = sectionIds.join(',');
      }

      const response = await fetch('/cart/add.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();
      if (!response.ok || data.status) {
        throw new Error(data.description || data.message || 'Could not add this item to the cart.');
      }

      return data;
    }

    async function applyDiscountCode(code) {
      const existingCodes = getExistingDiscountCodes();
      const discountCodes = Array.from(new Set(existingCodes.concat(code)));
      const sectionIds = getCartSectionIds();
      const payload = { discount: discountCodes.join(',') };

      if (sectionIds.length) {
        payload.sections = sectionIds.join(',');
      }

      const response = await fetch('/cart/update.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error('Could not apply the bundle discount.');
      }

      const applied = Array.isArray(data.discount_codes) && data.discount_codes.some((discount) => {
        return discount.code === code && discount.applicable === true;
      });

      if (!applied) {
        throw new Error('Bundle items were added, but the 5% discount code did not apply.');
      }

      return data;
    }

    function openCartDrawer() {
      const drawer = document.querySelector('cart-drawer-component');
      if (drawer && typeof drawer.open === 'function') {
        drawer.open();
        return;
      }

      const toggle = document.querySelector('[aria-label="Open cart drawer"]');
      if (toggle instanceof HTMLElement) {
        toggle.click();
      }
    }

    function dispatchCartEvents(updateData, itemCount) {
      document.dispatchEvent(new CartAddEvent(updateData, 'sofa-bundle-cta', {
        source: 'product-form-component',
        itemCount: itemCount,
        productId: String(PRODUCT_ID),
        sections: updateData && updateData.sections ? updateData.sections : {}
      }));

      document.dispatchEvent(new DiscountUpdateEvent(updateData, 'sofa-bundle-cta'));
    }

    function dispatchSingleCartEvent(updateData, variant, itemCount) {
      document.dispatchEvent(new CartAddEvent(updateData, String(variant.id), {
        source: 'product-form-component',
        itemCount: itemCount,
        productId: String(PRODUCT_ID),
        sections: updateData && updateData.sections ? updateData.sections : {}
      }));
    }

    async function handleSingleAdd(event, form) {
      if (document.body.classList.contains('sofa-bundle-mode-active')) return;
      if (singleAddInFlight) {
        event.preventDefault();
        event.stopImmediatePropagation();
        return;
      }

      const variant = syncSingleVariantSelection();
      if (!variant || !variant.available) return;

      event.preventDefault();
      event.stopImmediatePropagation();

      const quantity = getQuantityFromForm(form);
      const button = getAddButtonFromForm(form);
      const wasDisabled = button instanceof HTMLButtonElement && button.hasAttribute('disabled');

      singleAddInFlight = true;
      if (button instanceof HTMLButtonElement) {
        button.setAttribute('disabled', 'true');
        setAddButtonText(button, 'Adding...');
      }

      try {
        const data = await addSingleItemToCart(variant, quantity);
        dispatchSingleCartEvent(data, variant, quantity);
        openCartDrawer();
      } catch (error) {
        console.error(error);
        if (button instanceof HTMLButtonElement) {
          setAddButtonText(button, 'Could not add');
        }
      } finally {
        window.setTimeout(function () {
          if (button instanceof HTMLButtonElement) {
            restoreAddButtonText(button);
            if (!wasDisabled) {
              button.removeAttribute('disabled');
            }
          }
          singleAddInFlight = false;
        }, 250);
      }
    }

    function renderBundle(bundleKey) {
      const bundle = BUNDLES[bundleKey];
      if (!bundle) return;

      activeBundle = bundleKey;
      bundleButtons.forEach((button) => {
        button.classList.toggle('is-active', button.getAttribute('data-bundle') === bundleKey);
      });

      detailTitle.textContent = bundle.label + ' includes:';
      detailList.innerHTML = bundle.items.map((item) => '<li>' + item.label + '</li>').join('');
      details.classList.add('is-visible');
      cta.classList.add('is-visible');
      resetFeedback();

      const color = getColor();
      updatePricing(color ? resolveBundle(bundleKey, color) : null);
    }

    modeButtons.forEach((button) => {
      button.addEventListener('click', function () {
        setPurchaseMode(button.getAttribute('data-purchase-mode'));
      });
    });

    bundleButtons.forEach((button) => {
      button.addEventListener('click', function () {
        renderBundle(button.getAttribute('data-bundle'));
      });
    });

    document.addEventListener('change', function (event) {
      const target = event.target;

      if (isVariantPickerControl(target)) {
        scheduleSingleVariantSync();
        scheduleBundlePosition();
      }

      if (!activeBundle || !document.body.classList.contains('sofa-bundle-mode-active')) return;
      if (!(target instanceof HTMLElement)) return;

      const name = String(target.getAttribute('name') || target.id || '').toLowerCase();
      if (name.indexOf('color') > -1 || name.indexOf('colour') > -1 || name === 'option0' || name.indexOf('option-0') > -1 || name === 'id') {
        resetFeedback();
        updatePricing(resolveBundle(activeBundle, getColor()));
      }
    });

    document.addEventListener('submit', function (event) {
      if (document.body.classList.contains('sofa-bundle-mode-active')) return;

      const form = event.target;
      if (form instanceof HTMLFormElement && form.matches('form[action*="/cart/add"]')) {
        handleSingleAdd(event, form);
      }
    }, true);

    document.addEventListener('click', function (event) {
      if (document.body.classList.contains('sofa-bundle-mode-active')) return;

      const target = event.target;
      if (!(target instanceof HTMLElement)) return;
      if (target.closest('button[name="add"], add-to-cart-component')) {
        const form = getSingleFormFromTarget(target);
        if (form) {
          handleSingleAdd(event, form);
        }
      }
    }, true);

    document.addEventListener('variant:update', function (event) {
      const detail = event.detail || {};
      const data = detail.data || {};
      if (data.productId && data.productId !== String(PRODUCT_ID)) return;

      scheduleSingleVariantSync();
      scheduleBundlePosition();
    });

    cta.addEventListener('click', async function () {
      if (!activeBundle) return;

      const color = getColor();
      if (!color) {
        setFeedback('Please select a colour first.', 'error');
        return;
      }

      const items = resolveBundle(activeBundle, color);
      if (!items) {
        setFeedback('Some bundle sizes are unavailable in this colour. Please choose another colour.', 'error');
        return;
      }

      cta.disabled = true;
      cta.textContent = 'Adding...';
      resetFeedback();

      try {
        await addBundleToCart(items);
        const discountData = await applyDiscountCode(DISCOUNT_CODE);
        const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);

        dispatchCartEvents(discountData, itemCount);
        openCartDrawer();

        cta.textContent = 'Add bundle to cart - save 5%';
        setFeedback('Bundle added to cart and 5% discount applied.', 'success');
      } catch (error) {
        cta.textContent = 'Add bundle to cart - save 5%';
        setFeedback(error instanceof Error ? error.message : 'Could not add the bundle to cart.', 'error');
      } finally {
        cta.disabled = false;
      }
    });

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', function () {
        scheduleSingleVariantSync();
        scheduleBundlePosition();
      });
    } else {
      scheduleSingleVariantSync();
      scheduleBundlePosition();
    }
  })();
</script>
{% endif %}
