{%- comment -%}
  Free Shipping Progress — live progress toward a free-shipping threshold.
  Reads the real cart total and re-reads it after any cart change, so it
  stays accurate when items are added from a drawer or quick-add.
  Threshold is entered in whole currency units and converted to cents.
{%- endcomment -%}

{%- liquid
  assign s = section.settings
  assign uid = section.id
  assign threshold = s.threshold | times: 100
  assign remaining = threshold | minus: cart.total_price
  if remaining < 0
    assign remaining = 0
  endif
  assign pct = 0
  if threshold > 0
    assign pct = cart.total_price | times: 100.0 | divided_by: threshold
    if pct > 100
      assign pct = 100
    endif
  endif
-%}

{% style %}
  .fsb-{{ uid }} {
    padding: {{ s.padding_y }}px 0;
    background: {{ s.bg_color }};
    color: {{ s.text_color }};
  }
  .fsb-{{ uid }}__inner {
    max-width: {{ s.max_width }}px; margin: 0 auto;
    text-align: {{ s.align }};
  }
  .fsb-{{ uid }}__msg { font-size: {{ s.font_size }}px; margin: 0 0 8px; }
  .fsb-{{ uid }}__msg strong { font-weight: 700; }
  .fsb-{{ uid }}__track {
    height: {{ s.bar_height }}px; border-radius: {{ s.bar_height }}px;
    background: {{ s.track_color }}; overflow: hidden;
  }
  .fsb-{{ uid }}__fill {
    height: 100%; width: 0%;
    border-radius: inherit;
    background: {{ s.fill_color }};
    transition: width .45s cubic-bezier(.4,0,.2,1);
  }
  {%- if s.striped -%}
  .fsb-{{ uid }}__fill {
    background-image: linear-gradient(45deg,
      rgba(255,255,255,.22) 25%, transparent 25%, transparent 50%,
      rgba(255,255,255,.22) 50%, rgba(255,255,255,.22) 75%, transparent 75%);
    background-size: 1rem 1rem;
  }
  {%- endif -%}
  .fsb-{{ uid }}--done .fsb-{{ uid }}__fill { background: {{ s.success_color }}; }
  @media (prefers-reduced-motion: reduce) {
    .fsb-{{ uid }}__fill { transition: none; }
  }
{% endstyle %}

<div class="fsb-{{ uid }}{% if remaining == 0 %} fsb-{{ uid }}--done{% endif %}"
     data-fsb="{{ uid }}"
     data-threshold="{{ threshold }}"
     data-msg-progress="{{ s.msg_progress | escape }}"
     data-msg-success="{{ s.msg_success | escape }}">
  <div class="page-width">
    <div class="fsb-{{ uid }}__inner">
      <p class="fsb-{{ uid }}__msg" data-fsb-msg>
        {%- if remaining == 0 -%}
          {{ s.msg_success }}
        {%- else -%}
          {{ s.msg_progress | replace: '[amount]', '<strong>' | append: '' }}
          {%- comment -%} rendered client-side below for accuracy {%- endcomment -%}
          {{ s.msg_progress | split: '[amount]' | first }}<strong>{{ remaining | money }}</strong>{{ s.msg_progress | split: '[amount]' | last }}
        {%- endif -%}
      </p>
      <div class="fsb-{{ uid }}__track">
        <div class="fsb-{{ uid }}__fill" data-fsb-fill style="width: {{ pct }}%"></div>
      </div>
    </div>
  </div>
</div>

<script>
  (() => {
    const root = document.querySelector('[data-fsb="{{ uid }}"]');
    if (!root) return;
    const threshold = parseInt(root.dataset.threshold, 10) || 0;
    const fill = root.querySelector('[data-fsb-fill]');
    const msg  = root.querySelector('[data-fsb-msg]');
    const fmt  = (cents) => {
      try {
        return new Intl.NumberFormat(document.documentElement.lang || 'en', {
          style: 'currency', currency: window.Shopify?.currency?.active || 'USD'
        }).format(cents / 100);
      } catch { return (cents / 100).toFixed(2); }
    };
    const render = (total) => {
      if (!threshold) return;
      const remaining = Math.max(threshold - total, 0);
      const pct = Math.min((total / threshold) * 100, 100);
      fill.style.width = pct + '%';
      root.classList.toggle('fsb-{{ uid }}--done', remaining === 0);
      msg.innerHTML = remaining === 0
        ? root.dataset.msgSuccess
        : root.dataset.msgProgress.replace('[amount]', '<strong>' + fmt(remaining) + '</strong>');
    };
    const refresh = () => fetch('/cart.js', {headers:{'Accept':'application/json'}})
      .then(r => r.json()).then(c => render(c.total_price)).catch(() => {});
    // re-check after any cart mutation
    ['cart:updated','cart-drawer:open','variant:added'].forEach(ev =>
      document.addEventListener(ev, refresh));
    const of = window.fetch;
    window.fetch = function (...args) {
      const p = of.apply(this, args);
      const url = (args[0] && (args[0].url || args[0])) + '';
      if (/\/cart\/(add|change|update|clear)/.test(url)) p.then(() => setTimeout(refresh, 120));
      return p;
    };
  })();
</script>

{% schema %}
{
  "name": "Free Shipping Bar",
  "tag": "section",
  "class": "section",
  "settings": [
    { "type": "range", "id": "threshold", "min": 0, "max": 9900, "step": 100, "label": "Free shipping threshold", "default": 3000,
      "info": "In whole currency units — e.g. 3000 means ৳3,000." },
    { "type": "text", "id": "msg_progress", "label": "Progress message", "default": "You're [amount] away from free shipping",
      "info": "Use [amount] where the remaining total should appear." },
    { "type": "text", "id": "msg_success", "label": "Success message", "default": "Congratulations — you've unlocked free shipping!" },
    { "type": "header", "content": "Style" },
    { "type": "select", "id": "align", "label": "Alignment", "default": "center",
      "options": [ {"value":"left","label":"Left"}, {"value":"center","label":"Centre"} ] },
    { "type": "range", "id": "max_width", "min": 320, "max": 1200, "step": 20, "unit": "px", "label": "Max width", "default": 640 },
    { "type": "range", "id": "font_size", "min": 11, "max": 22, "step": 1, "unit": "px", "label": "Text size", "default": 14 },
    { "type": "range", "id": "bar_height", "min": 4, "max": 24, "step": 1, "unit": "px", "label": "Bar height", "default": 8 },
    { "type": "checkbox", "id": "striped", "label": "Striped bar", "default": false },
    { "type": "color", "id": "bg_color", "label": "Background", "default": "#f7f5f2" },
    { "type": "color", "id": "text_color", "label": "Text", "default": "#111111" },
    { "type": "color", "id": "track_color", "label": "Track", "default": "#e2ded8" },
    { "type": "color", "id": "fill_color", "label": "Progress fill", "default": "#111111" },
    { "type": "color", "id": "success_color", "label": "Complete fill", "default": "#1e8f4e" },
    { "type": "range", "id": "padding_y", "min": 4, "max": 48, "step": 2, "unit": "px", "label": "Vertical padding", "default": 14 }
  ],
  "presets": [ { "name": "Free Shipping Bar" } ]
}
{% endschema %}
