{% comment %}
  ============================================================
  Product Bundle Selector
  File: sections/product-bundle-selector.liquid
  Target: Product ID 7853598048340 only
  ============================================================
{% endcomment %}

{%- assign target_product_id = 7853598048340 -%}
{%- if product.id == target_product_id -%}

<style>
  .bundle-selector {
    margin: 32px 0;
    font-family: inherit;
  }
  .bundle-selector__heading {
    font-size: 1.05rem;
    font-weight: 700;
    margin-bottom: 14px;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: #111;
  }
  .bundle-selector__options {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 18px;
  }
  .bundle-selector__btn {
    border: 2px solid #ccc;
    border-radius: 8px;
    padding: 10px 20px;
    cursor: pointer;
    background: #fff;
    font-size: 0.88rem;
    font-weight: 600;
    transition: all 0.18s ease;
    color: #222;
    line-height: 1.3;
  }
  .bundle-selector__btn:hover {
    border-color: #555;
    background: #f5f5f5;
  }
  .bundle-selector__btn.is-active {
    border-color: #1a1a1a;
    background: #1a1a1a;
    color: #fff;
  }
  .bundle-selector__details {
    background: #f8f8f8;
    border: 1px solid #e8e8e8;
    border-radius: 10px;
    padding: 16px 20px;
    margin-bottom: 16px;
    font-size: 0.875rem;
    line-height: 1.65;
    display: none;
  }
  .bundle-selector__details.is-visible { display: block; }
  .bundle-selector__details-title {
    font-weight: 700;
    margin-bottom: 8px;
    font-size: 0.9rem;
    color: #111;
  }
  .bundle-selector__details ul {
    margin: 0;
    padding-left: 20px;
    color: #444;
  }
  .bundle-selector__details li { margin-bottom: 3px; }
  .bundle-selector__cta {
    display: none;
    width: 100%;
    padding: 14px 20px;
    background: #1a1a1a;
    color: #fff;
    font-size: 0.95rem;
    font-weight: 700;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    letter-spacing: 0.04em;
    transition: background 0.18s;
  }
  .bundle-selector__cta:hover { background: #333; }
  .bundle-selector__cta:disabled { background: #888; cursor: not-allowed; }
  .bundle-selector__cta.is-visible { display: block; }
  .bundle-selector__feedback {
    margin-top: 10px;
    font-size: 0.85rem;
    display: none;
  }
  .bundle-selector__feedback.is-visible { display: block; }
  .bundle-selector__feedback--success { color: #27ae60; }
  .bundle-selector__feedback--error { color: #c0392b; }
</style>

<div class="bundle-selector" id="sofa-bundle-selector">
  <div class="bundle-selector__heading">Bundle &amp; Save</div>

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

  <div class="bundle-selector__details" id="sofa-bundle-details">
    <div class="bundle-selector__details-title" id="sofa-bundle-title"></div>
    <ul id="sofa-bundle-list"></ul>
  </div>

  <button class="bundle-selector__cta" id="sofa-bundle-cta" type="button">Add Bundle to Cart</button>

  <div class="bundle-selector__feedback" id="sofa-bundle-feedback"></div>
</div>

<script>
(function () {
  'use strict';

  /* ---------------------------------------------------------------
     Bundle definitions
     size values must EXACTLY match your product's Specification
     variant option values (option2).
  --------------------------------------------------------------- */
  var 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' }
      ],
      note: '(1x seat cover 90x90 + 1x cushion 90x90 merged as same SKU)'
    },
    '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' }
      ]
    }
  };

  /* ---------------------------------------------------------------
     Product variants injected from Liquid
     option1 = Color, option2 = Specification (size)
  --------------------------------------------------------------- */
  var VARIANTS = [
    {% for variant in product.variants %}
    { id: {{ variant.id }}, color: {{ variant.option1 | json }}, size: {{ variant.option2 | json }}, available: {{ variant.available }} }{% unless forloop.last %},{% endunless %}
    {% endfor %}
  ];

  /* ---------------------------------------------------------------
     DOM references
  --------------------------------------------------------------- */
  var $wrap     = document.getElementById('sofa-bundle-selector');
  var $buttons  = $wrap.querySelectorAll('.bundle-selector__btn');
  var $details  = document.getElementById('sofa-bundle-details');
  var $title    = document.getElementById('sofa-bundle-title');
  var $list     = document.getElementById('sofa-bundle-list');
  var $cta      = document.getElementById('sofa-bundle-cta');
  var $feedback = document.getElementById('sofa-bundle-feedback');

  var activeBundle = null;

  /* ---------------------------------------------------------------
     Get selected colour from the product form
     Tries multiple strategies for Horizon + other themes
  --------------------------------------------------------------- */
  function getSelectedColor() {
    // Strategy 1: standard radio input (Horizon theme uses these)
    var radios = document.querySelectorAll(
      'input[type="radio"]:checked, fieldset input[type="radio"]:checked'
    );
    for (var i = 0; i < radios.length; i++) {
      var r = radios[i];
      var name = (r.name || '').toLowerCase();
      if (name === 'color' || name === 'colour') return r.value;
    }

    // Strategy 2: select dropdown
    var selects = document.querySelectorAll('select');
    for (var j = 0; j < selects.length; j++) {
      var s = selects[j];
      var sname = (s.name || s.id || '').toLowerCase();
      if (sname.indexOf('color') > -1 || sname.indexOf('colour') > -1 || sname.indexOf('option0') > -1) {
        return s.value;
      }
    }

    // Strategy 3: read from current variant ID (master select)
    var master = document.querySelector('select[name="id"], .product-form__variants');
    if (master) {
      var vid = parseInt(master.value, 10);
      var match = VARIANTS.find(function(v) { return v.id === vid; });
      if (match) return match.color;
    }

    // Strategy 4: first available variant colour as fallback
    return VARIANTS.length ? VARIANTS[0].color : null;
  }

  /* ---------------------------------------------------------------
     Resolve variant IDs for chosen bundle + colour
     Returns array or null on failure
  --------------------------------------------------------------- */
  function resolveItems(bundleKey, color) {
    var bundle = BUNDLES[bundleKey];
    var resolved = [];
    var missing = [];
    bundle.items.forEach(function(item) {
      var v = VARIANTS.find(function(x) {
        return x.color === color && x.size === item.size;
      });
      if (!v) { missing.push(item.size); }
      else { resolved.push({ variantId: v.id, quantity: item.qty, label: item.label }); }
    });
    if (missing.length) {
      console.warn('[Bundle] Missing variants for colour "' + color + '": ' + missing.join(', '));
      return null;
    }
    return resolved;
  }

  /* ---------------------------------------------------------------
     Add items to Shopify cart via Ajax
  --------------------------------------------------------------- */
  function addToCart(items, onSuccess, onError) {
    fetch('/cart/add.js', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        items: items.map(function(i) {
          return { id: i.variantId, quantity: i.quantity };
        })
      })
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
      if (data.status && data.status >= 400) { onError(data.description || 'Could not add items.'); }
      else { onSuccess(); }
    })
    .catch(function() { onError('Network error — please try again.'); });
  }

  /* ---------------------------------------------------------------
     Refresh cart UI (works for Horizon + Dawn themes)
  --------------------------------------------------------------- */
  function refreshCart() {
    fetch('/cart.js')
      .then(function(r) { return r.json(); })
      .then(function(cart) {
        document.dispatchEvent(new CustomEvent('cart:refresh', { bubbles: true, detail: { cart: cart } }));
        document.dispatchEvent(new CustomEvent('cart:updated', { bubbles: true }));
      });
    // Horizon theme specific
    var cartBtn = document.querySelector('a[href="/cart"], button[data-cart-toggle]');
    if (cartBtn) cartBtn.click();
  }

  /* ---------------------------------------------------------------
     Show feedback message
  --------------------------------------------------------------- */
  function showFeedback(msg, type) {
    $feedback.textContent = msg;
    $feedback.className = 'bundle-selector__feedback is-visible bundle-selector__feedback--' + type;
  }

  /* ---------------------------------------------------------------
     Render bundle details panel
  --------------------------------------------------------------- */
  function renderDetails(key) {
    var b = BUNDLES[key];
    $title.textContent = b.label + ' includes:';
    $list.innerHTML = b.items.map(function(i) {
      return '<li>' + i.label + '</li>';
    }).join('');
    $details.classList.add('is-visible');
  }

  /* ---------------------------------------------------------------
     Button click handlers
  --------------------------------------------------------------- */
  $buttons.forEach(function(btn) {
    btn.addEventListener('click', function() {
      $buttons.forEach(function(b) { b.classList.remove('is-active'); });
      $feedback.className = 'bundle-selector__feedback';
      btn.classList.add('is-active');
      activeBundle = btn.getAttribute('data-bundle');
      renderDetails(activeBundle);
      $cta.classList.add('is-visible');
    });
  });

  /* ---------------------------------------------------------------
     Add to cart handler
  --------------------------------------------------------------- */
  $cta.addEventListener('click', function() {
    if (!activeBundle) return;

    var color = getSelectedColor();
    if (!color) {
      showFeedback('Please select a colour above before adding a bundle.', 'error');
      return;
    }

    var items = resolveItems(activeBundle, color);
    if (!items) {
      showFeedback('Some variants are not available for the selected colour. Please choose a different colour.', 'error');
      return;
    }

    $cta.disabled = true;
    $cta.textContent = 'Adding to cart\u2026';
    $feedback.className = 'bundle-selector__feedback';

    addToCart(
      items,
      function() {
        $cta.disabled = false;
        $cta.textContent = 'Add Bundle to Cart';
        showFeedback('\u2713 Bundle added to cart!', 'success');
        refreshCart();
      },
      function(err) {
        $cta.disabled = false;
        $cta.textContent = 'Add Bundle to Cart';
        showFeedback('\u2717 ' + err, 'error');
      }
    );
  });

})();
</script>

{%- endif -%}

{% schema %}
{
  "name": "Product Bundle Selector",
  "settings": [],
  "presets": [
    { "name": "Product Bundle Selector" }
  ]
}
{% endschema %}