{%- comment -%}
  Bundle Offer — quantity-break pricing tiers ("buy 2 save 10%").
  Each tier is a block that adds N of the chosen variant in one click.
  Savings are computed from the real variant price, so the maths never
  drifts from what the cart will actually charge.
{%- endcomment -%}

{%- liquid
  assign s = section.settings
  assign p = s.product
  if p == blank and product != blank
    assign p = product
  endif
  assign uid = section.id
  assign unit = 0
  if p != blank
    assign unit = p.selected_or_first_available_variant.price
  endif
-%}

{% style %}
  .bo-{{ uid }} { padding-top: {{ s.padding_top }}px; padding-bottom: {{ s.padding_bottom }}px; }
  .bo-{{ uid }}__head { text-align: center; margin-bottom: 18px; }
  .bo-{{ uid }}__list {
    display: grid; gap: {{ s.gap }}px; max-width: {{ s.max_width }}px; margin: 0 auto;
  }
  .bo-{{ uid }}__tier {
    position: relative; display: flex; align-items: center; gap: 14px;
    width: 100%; text-align: left; cursor: pointer;
    padding: {{ s.tier_padding }}px;
    border-radius: {{ s.tier_radius }}px;
    border: 2px solid {{ s.border_color }};
    background: {{ s.tier_bg }}; color: {{ s.tier_text }};
    transition: border-color .15s ease, box-shadow .15s ease;
  }
  .bo-{{ uid }}__tier:hover { border-color: {{ s.accent }}; }
  .bo-{{ uid }}__tier[aria-pressed="true"] {
    border-color: {{ s.accent }};
    box-shadow: 0 0 0 3px {{ s.accent | color_modify: 'alpha', 0.18 }};
  }
  .bo-{{ uid }}__radio {
    width: 20px; height: 20px; border-radius: 50%; flex: 0 0 auto;
    border: 2px solid {{ s.border_color }}; display: grid; place-items: center;
  }
  .bo-{{ uid }}__tier[aria-pressed="true"] .bo-{{ uid }}__radio { border-color: {{ s.accent }}; }
  .bo-{{ uid }}__tier[aria-pressed="true"] .bo-{{ uid }}__radio::after {
    content: ''; width: 10px; height: 10px; border-radius: 50%; background: {{ s.accent }};
  }
  .bo-{{ uid }}__body { flex: 1 1 auto; min-width: 0; }
  .bo-{{ uid }}__name { display: block; font-weight: 600; font-size: 15px; }
  .bo-{{ uid }}__sub { display: block; font-size: 13px; opacity: .75; }
  .bo-{{ uid }}__prices { text-align: right; flex: 0 0 auto; }
  .bo-{{ uid }}__now { display: block; font-weight: 700; font-size: 16px; }
  .bo-{{ uid }}__was { display: block; font-size: 13px; opacity: .6; text-decoration: line-through; }
  .bo-{{ uid }}__flag {
    position: absolute; top: -10px; {{ s.flag_side }}: 14px;
    font-size: 11px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase;
    padding: 3px 9px; border-radius: 999px;
    background: {{ s.accent }}; color: {{ s.flag_text }};
  }
  .bo-{{ uid }}__cta {
    display: block; width: 100%; margin-top: 16px; cursor: pointer;
    padding: 14px 20px; border: 0; border-radius: {{ s.tier_radius }}px;
    background: {{ s.cta_bg }}; color: {{ s.cta_text }};
    font-size: 16px; font-weight: 600;
  }
  .bo-{{ uid }}__cta[disabled] { opacity: .5; cursor: not-allowed; }
{% endstyle %}

<div class="bo-{{ uid }} color-{{ s.color_scheme }} gradient">
  <div class="page-width">
    {%- if s.title != blank or s.subtitle != blank -%}
      <div class="bo-{{ uid }}__head">
        {%- if s.title != blank -%}<h2>{{ s.title | escape }}</h2>{%- endif -%}
        {%- if s.subtitle != blank -%}<div>{{ s.subtitle }}</div>{%- endif -%}
      </div>
    {%- endif -%}

    {%- if p == blank -%}
      <p style="text-align:center;opacity:.7">{{ 'Select a product in the section settings.' }}</p>
    {%- else -%}
      <div class="bo-{{ uid }}__list" data-bo="{{ uid }}" data-variant="{{ p.selected_or_first_available_variant.id }}">
        {%- for block in section.blocks -%}
          {%- liquid
            assign qty = block.settings.quantity | at_least: 1
            assign full = unit | times: qty
            assign pctoff = block.settings.discount_percent
            assign now = full
            if pctoff > 0
              assign keep = 100 | minus: pctoff
              assign now = full | times: keep | divided_by: 100
            endif
            assign save = full | minus: now
          -%}
          <button type="button" class="bo-{{ uid }}__tier"
                  aria-pressed="{% if forloop.index == s.default_tier %}true{% else %}false{% endif %}"
                  data-qty="{{ qty }}" {{ block.shopify_attributes }}>
            {%- if block.settings.flag != blank -%}
              <span class="bo-{{ uid }}__flag">{{ block.settings.flag | escape }}</span>
            {%- endif -%}
            <span class="bo-{{ uid }}__radio"></span>
            <span class="bo-{{ uid }}__body">
              <span class="bo-{{ uid }}__name">
                {{ block.settings.label | default: 'Buy ' | append: qty | escape }}
              </span>
              {%- if pctoff > 0 -%}
                <span class="bo-{{ uid }}__sub">{{ s.save_label | replace: '[percent]', pctoff }}</span>
              {%- elsif block.settings.note != blank -%}
                <span class="bo-{{ uid }}__sub">{{ block.settings.note | escape }}</span>
              {%- endif -%}
            </span>
            <span class="bo-{{ uid }}__prices">
              <span class="bo-{{ uid }}__now">{{ now | money }}</span>
              {%- if save > 0 -%}<span class="bo-{{ uid }}__was">{{ full | money }}</span>{%- endif -%}
            </span>
          </button>
        {%- endfor -%}

        <button type="button" class="bo-{{ uid }}__cta" data-bo-add
                {% unless p.available %}disabled{% endunless %}>
          {%- if p.available -%}{{ s.cta_label | escape }}{%- else -%}{{ 'products.product.sold_out' | t }}{%- endif -%}
        </button>
      </div>
    {%- endif -%}
  </div>
</div>

<script>
  (() => {
    const root = document.querySelector('[data-bo="{{ uid }}"]');
    if (!root) return;
    const tiers = [...root.querySelectorAll('.bo-{{ uid }}__tier')];
    tiers.forEach(t => t.addEventListener('click', () => {
      tiers.forEach(o => o.setAttribute('aria-pressed', String(o === t)));
    }));
    root.querySelector('[data-bo-add]')?.addEventListener('click', async (e) => {
      const btn = e.currentTarget;
      const sel = tiers.find(t => t.getAttribute('aria-pressed') === 'true') || tiers[0];
      if (!sel) return;
      const label = btn.textContent;
      btn.disabled = true; btn.textContent = '…';
      try {
        const res = await fetch('{{ routes.cart_add_url }}.js', {
          method: 'POST', headers: {'Content-Type':'application/json','Accept':'application/json'},
          body: JSON.stringify({ items: [{ id: Number(root.dataset.variant), quantity: Number(sel.dataset.qty) }] })
        });
        if (!res.ok) throw new Error();
        document.dispatchEvent(new CustomEvent('cart:updated'));
        btn.textContent = {{ s.added_label | json }};
        setTimeout(() => { btn.textContent = label; btn.disabled = false; }, 1600);
      } catch {
        btn.textContent = label; btn.disabled = false;
      }
    });
  })();
</script>

{% schema %}
{
  "name": "Bundle Offer",
  "tag": "section",
  "class": "section",
  "disabled_on": { "groups": ["header", "footer"] },
  "settings": [
    { "type": "product", "id": "product", "label": "Product", "info": "Leave blank on a product page to use that product." },
    { "type": "text", "id": "title", "label": "Title", "default": "Buy more, save more" },
    { "type": "richtext", "id": "subtitle", "label": "Subtitle" },
    { "type": "text", "id": "save_label", "label": "Discount label", "default": "Save [percent]%",
      "info": "Use [percent] for the tier's discount." },
    { "type": "text", "id": "cta_label", "label": "Button label", "default": "Add bundle to cart" },
    { "type": "text", "id": "added_label", "label": "Added confirmation", "default": "Added ✓" },
    { "type": "range", "id": "default_tier", "min": 1, "max": 5, "step": 1, "label": "Pre-selected tier", "default": 2 },
    { "type": "header", "content": "Layout" },
    { "type": "range", "id": "gap", "min": 4, "max": 28, "step": 2, "unit": "px", "label": "Gap", "default": 10 },
    { "type": "range", "id": "max_width", "min": 320, "max": 900, "step": 20, "unit": "px", "label": "Max width", "default": 520 },
    { "type": "range", "id": "tier_padding", "min": 8, "max": 32, "step": 2, "unit": "px", "label": "Tier padding", "default": 16 },
    { "type": "range", "id": "tier_radius", "min": 0, "max": 26, "step": 2, "unit": "px", "label": "Corner radius", "default": 10 },
    { "type": "select", "id": "flag_side", "label": "Flag position", "default": "right",
      "options": [ {"value":"left","label":"Left"}, {"value":"right","label":"Right"} ] },
    { "type": "header", "content": "Colours" },
    { "type": "color", "id": "accent", "label": "Accent", "default": "#111111" },
    { "type": "color", "id": "border_color", "label": "Border", "default": "#e0dcd5" },
    { "type": "color", "id": "tier_bg", "label": "Tier background", "default": "#ffffff" },
    { "type": "color", "id": "tier_text", "label": "Tier text", "default": "#111111" },
    { "type": "color", "id": "flag_text", "label": "Flag text", "default": "#ffffff" },
    { "type": "color", "id": "cta_bg", "label": "Button background", "default": "#111111" },
    { "type": "color", "id": "cta_text", "label": "Button text", "default": "#ffffff" },
    { "type": "header", "content": "Section" },
    { "type": "color_scheme", "id": "color_scheme", "label": "Colour scheme", "default": "scheme-1" },
    { "type": "range", "id": "padding_top", "min": 0, "max": 100, "step": 4, "unit": "px", "label": "Top padding", "default": 36 },
    { "type": "range", "id": "padding_bottom", "min": 0, "max": 100, "step": 4, "unit": "px", "label": "Bottom padding", "default": 36 }
  ],
  "blocks": [
    {
      "type": "tier",
      "name": "Tier",
      "settings": [
        { "type": "range", "id": "quantity", "min": 1, "max": 10, "step": 1, "label": "Quantity", "default": 1 },
        { "type": "range", "id": "discount_percent", "min": 0, "max": 70, "step": 1, "unit": "%", "label": "Discount", "default": 0 },
        { "type": "text", "id": "label", "label": "Label", "default": "Buy 1" },
        { "type": "text", "id": "note", "label": "Note", "info": "Shown when there is no discount." },
        { "type": "text", "id": "flag", "label": "Flag", "info": "e.g. Most popular" }
      ]
    }
  ],
  "presets": [
    {
      "name": "Bundle Offer",
      "blocks": [
        { "type": "tier", "settings": { "quantity": 1, "discount_percent": 0,  "label": "Buy 1", "note": "Standard price" } },
        { "type": "tier", "settings": { "quantity": 2, "discount_percent": 10, "label": "Buy 2", "flag": "Most popular" } },
        { "type": "tier", "settings": { "quantity": 3, "discount_percent": 18, "label": "Buy 3", "flag": "Best value" } }
      ]
    }
  ]
}
{% endschema %}
