{%- comment -%}
  Sticky Add to Cart — persistent buy bar that appears once the main
  product form scrolls out of view. Posts to /cart/add without a page
  reload and mirrors the selected variant from the main form.
  Product-page only; renders nothing elsewhere.
{%- endcomment -%}

{%- liquid
  assign s = section.settings
  assign uid = section.id
  assign p = product
  if s.product != blank
    assign p = s.product
  endif
-%}

{%- if p != blank -%}
{% style %}
  .satc-{{ uid }} {
    position: fixed; left: 0; right: 0;
    {{ s.position }}: 0; z-index: 40;
    background: {{ s.bg_color }}; color: {{ s.text_color }};
    border-{% if s.position == 'bottom' %}top{% else %}bottom{% endif %}: 1px solid {{ s.border_color }};
    transform: translateY({% if s.position == 'bottom' %}110%{% else %}-110%{% endif %});
    transition: transform .28s cubic-bezier(.4,0,.2,1);
    padding: 10px 0;
  }
  .satc-{{ uid }}.is-visible { transform: translateY(0); }
  .satc-{{ uid }}__row {
    display: flex; align-items: center; gap: 14px;
  }
  .satc-{{ uid }}__thumb {
    width: 46px; height: 56px; object-fit: cover; border-radius: 6px; flex: 0 0 auto;
  }
  .satc-{{ uid }}__meta { min-width: 0; flex: 1 1 auto; }
  .satc-{{ uid }}__title {
    margin: 0; font-size: 14px; font-weight: 600;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
  }
  .satc-{{ uid }}__price { margin: 0; font-size: 14px; }
  .satc-{{ uid }}__price s { opacity: .55; margin-right: 6px; }
  .satc-{{ uid }}__select {
    max-width: 160px; padding: 8px 10px; border-radius: 6px;
    border: 1px solid {{ s.border_color }}; background: transparent; color: inherit;
  }
  .satc-{{ uid }}__btn {
    flex: 0 0 auto; min-width: {{ s.button_width }}px;
    padding: 12px 22px; border: 0; cursor: pointer;
    border-radius: {{ s.button_radius }}px;
    background: {{ s.button_bg }}; color: {{ s.button_text }};
    font-size: 15px; font-weight: 600;
  }
  .satc-{{ uid }}__btn[disabled] { opacity: .5; cursor: not-allowed; }
  @media screen and (max-width: 749px) {
    .satc-{{ uid }}__thumb,
    .satc-{{ uid }}__select { display: {% if s.compact_mobile %}none{% else %}block{% endif %}; }
    .satc-{{ uid }}__btn { min-width: 0; flex: 1 1 auto; }
  }
  @media (prefers-reduced-motion: reduce) { .satc-{{ uid }} { transition: none; } }
{% endstyle %}

<div class="satc-{{ uid }}" data-satc="{{ uid }}" aria-hidden="true">
  <div class="page-width">
    <form method="post" action="{{ routes.cart_add_url }}" class="satc-{{ uid }}__row" data-satc-form>
      <input type="hidden" name="form_type" value="product">
      <input type="hidden" name="utf8" value="✓">

      {%- if s.show_image and p.featured_image -%}
        {%- capture thumb_class -%}satc-{{ uid }}__thumb{%- endcapture -%}
        {{ p.featured_image | image_url: width: 140 | image_tag:
             class: thumb_class, loading: "lazy", alt: "" }}
      {%- endif -%}

      <div class="satc-{{ uid }}__meta">
        <p class="satc-{{ uid }}__title">{{ p.title | escape }}</p>
        {%- if s.show_price -%}
          <p class="satc-{{ uid }}__price" data-satc-price>
            {%- if p.selected_or_first_available_variant.compare_at_price > p.selected_or_first_available_variant.price -%}
              <s>{{ p.selected_or_first_available_variant.compare_at_price | money }}</s>
            {%- endif -%}
            {{ p.selected_or_first_available_variant.price | money }}
          </p>
        {%- endif -%}
      </div>

      {%- if s.show_variants and p.variants.size > 1 -%}
        <select class="satc-{{ uid }}__select" name="id" data-satc-select>
          {%- for v in p.variants -%}
            <option value="{{ v.id }}"
              {% if v == p.selected_or_first_available_variant %}selected{% endif %}
              {% unless v.available %}disabled{% endunless %}
              data-price="{{ v.price | money }}">
              {{ v.title }}{% unless v.available %} — {{ 'products.product.sold_out' | t }}{% endunless %}
            </option>
          {%- endfor -%}
        </select>
      {%- else -%}
        <input type="hidden" name="id" value="{{ p.selected_or_first_available_variant.id }}" data-satc-select>
      {%- endif -%}

      <button type="submit" class="satc-{{ uid }}__btn" {% unless p.available %}disabled{% endunless %}>
        {%- if p.available -%}{{ s.button_label | escape }}{%- else -%}{{ 'products.product.sold_out' | t }}{%- endif -%}
      </button>
    </form>
  </div>
</div>

<script>
  (() => {
    const bar = document.querySelector('[data-satc="{{ uid }}"]');
    if (!bar) return;
    // show once the real product form is out of view
    const anchor = document.querySelector('product-form, .product-form, form[action*="/cart/add"]:not([data-satc-form])');
    const show = () => { bar.classList.add('is-visible'); bar.setAttribute('aria-hidden','false'); };
    const hide = () => { bar.classList.remove('is-visible'); bar.setAttribute('aria-hidden','true'); };
    if (anchor && 'IntersectionObserver' in window) {
      new IntersectionObserver(([e]) => e.isIntersecting ? hide() : show(), {rootMargin: '0px 0px -80% 0px'})
        .observe(anchor);
    } else {
      addEventListener('scroll', () => scrollY > 600 ? show() : hide(), {passive:true});
    }
    // keep price in step with the variant picker
    const sel = bar.querySelector('[data-satc-select]');
    const priceEl = bar.querySelector('[data-satc-price]');
    if (sel && sel.tagName === 'SELECT' && priceEl) {
      sel.addEventListener('change', () => {
        const o = sel.selectedOptions[0];
        if (o?.dataset.price) priceEl.textContent = o.dataset.price;
      });
    }
    // mirror the main form's variant choice into ours
    document.addEventListener('change', e => {
      if (!e.target.closest('variant-selects, variant-radios, .product-form__input')) return;
      setTimeout(() => {
        const id = new URLSearchParams(location.search).get('variant');
        if (id && sel) sel.value = id;
      }, 60);
    });
    // ajax submit so we don't lose the page
    bar.querySelector('[data-satc-form]').addEventListener('submit', async e => {
      e.preventDefault();
      const form = e.currentTarget;
      const btn = form.querySelector('button[type="submit"]');
      const original = 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: form.querySelector('[data-satc-select]').value, quantity: 1 }] })
        });
        if (!res.ok) throw new Error('add failed');
        document.dispatchEvent(new CustomEvent('cart:updated'));
        btn.textContent = {{ s.added_label | json }};
        setTimeout(() => { btn.textContent = original; btn.disabled = false; }, 1600);
      } catch {
        btn.textContent = original; btn.disabled = false;
        form.submit();   // fall back to a normal post
      }
    });
  })();
</script>
{%- endif -%}

{% schema %}
{
  "name": "Sticky Add to Cart",
  "tag": "section",
  "class": "section",
  "enabled_on": { "templates": ["product"] },
  "settings": [
    { "type": "product", "id": "product", "label": "Product", "info": "Leave blank to use the page's product." },
    { "type": "select", "id": "position", "label": "Position", "default": "bottom",
      "options": [ {"value":"bottom","label":"Bottom"}, {"value":"top","label":"Top"} ] },
    { "type": "text", "id": "button_label", "label": "Button label", "default": "Add to cart" },
    { "type": "text", "id": "added_label", "label": "Added confirmation", "default": "Added ✓" },
    { "type": "checkbox", "id": "show_image", "label": "Show product image", "default": true },
    { "type": "checkbox", "id": "show_price", "label": "Show price", "default": true },
    { "type": "checkbox", "id": "show_variants", "label": "Show variant picker", "default": true },
    { "type": "checkbox", "id": "compact_mobile", "label": "Compact on mobile", "default": true,
      "info": "Hides the thumbnail and variant picker on small screens." },
    { "type": "header", "content": "Style" },
    { "type": "color", "id": "bg_color", "label": "Background", "default": "#ffffff" },
    { "type": "color", "id": "text_color", "label": "Text", "default": "#111111" },
    { "type": "color", "id": "border_color", "label": "Border", "default": "#e6e6e6" },
    { "type": "color", "id": "button_bg", "label": "Button background", "default": "#111111" },
    { "type": "color", "id": "button_text", "label": "Button text", "default": "#ffffff" },
    { "type": "range", "id": "button_radius", "min": 0, "max": 30, "step": 2, "unit": "px", "label": "Button radius", "default": 6 },
    { "type": "range", "id": "button_width", "min": 120, "max": 320, "step": 10, "unit": "px", "label": "Button min width", "default": 180 }
  ],
  "presets": [ { "name": "Sticky Add to Cart" } ]
}
{% endschema %}
