{% set c = module.content %}
{% set l = module.layout %}
{% set vs = module.value_style %}
{% set ls = module.label_style %}
{% set anim = module.animation %}
{% set bg = module.background %}
{% set a = module.advanced %}

{# Build CSS classes #}
{% set module_classes = "stats-counter" %}
{% set module_classes = module_classes ~ " stats-counter--align-" ~ l.alignment %}
{% if l.show_dividers %}
  {% set module_classes = module_classes ~ " stats-counter--dividers" %}
{% endif %}
{% if anim.animate_on_scroll %}
  {% set module_classes = module_classes ~ " stats-counter--animate" %}
{% endif %}
{% if a.custom_class %}
  {% set module_classes = module_classes ~ " " ~ a.custom_class %}
{% endif %}

<section class="{{ module_classes }}"
         {% if a.custom_id %}id="{{ a.custom_id }}"{% endif %}
         {% if anim.animate_on_scroll %}data-animate="true" data-duration="{{ anim.animation_duration }}"{% endif %}
         style="
           --sc-cols-mobile: {{ l.cols_mobile }};
           --sc-cols-tablet: {{ l.cols_tablet }};
           --sc-cols-desktop: {{ l.cols_desktop }};
           --sc-gap: {{ l.gap }};
           --sc-value-color: {{ vs.color.color }};
           --sc-highlight-color: {{ vs.highlight_color.color }};
           --sc-label-color: {{ ls.color.color }};
           --sc-divider-color: {{ bg.divider_color.color }};
           --sc-bg: {{ bg.color.css }};
           --sc-pt: {{ bg.padding_top }};
           --sc-pb: {{ bg.padding_bottom }};
         ">

  {# Section Header #}
  {% if c.section_heading or c.section_subheading %}
    <header class="stats-counter__header">
      {% if c.section_heading %}
        <h2 class="stats-counter__heading">{{ c.section_heading|escape }}</h2>
      {% endif %}
      {% if c.section_subheading %}
        <p class="stats-counter__subheading">{{ c.section_subheading|escape }}</p>
      {% endif %}
    </header>
  {% endif %}

  {# Stats Grid #}
  <div class="stats-counter__grid">
    {% for stat in c.stats %}
      <div class="stats-counter__item{% if stat.highlight %} stats-counter__item--highlight{% endif %}">
        <div class="stats-counter__value stats-counter__value--{{ vs.size }} stats-counter__value--{{ vs.weight }}"
             {% if anim.animate_on_scroll %}
               data-value="{{ stat.value }}"
               data-prefix="{{ stat.prefix|default('', true) }}"
               data-suffix="{{ stat.suffix|default('', true) }}"
             {% endif %}>
          {% if stat.prefix %}<span class="stats-counter__prefix">{{ stat.prefix }}</span>{% endif %}
          <span class="stats-counter__number">{{ stat.value }}</span>
          {% if stat.suffix %}<span class="stats-counter__suffix">{{ stat.suffix }}</span>{% endif %}
        </div>
        <div class="stats-counter__label stats-counter__label--{{ ls.size }}{% if ls.uppercase %} stats-counter__label--uppercase{% endif %}">
          {{ stat.stat_label|escape }}
        </div>
      </div>
    {% endfor %}
  </div>
</section>

{% require_css %}
<style>
  .stats-counter {
    padding: var(--sc-pt, 48px) 0 var(--sc-pb, 48px);
    background-color: var(--sc-bg, transparent);
  }

  /* Section Header */
  .stats-counter__header {
    text-align: center;
    max-width: 720px;
    margin: 0 auto 2.5rem;
  }

  .stats-counter__heading {
    color: var(--sc-value-color, var(--color-text, #111827));
    font-size: clamp(1.5rem, 4vw, 2.25rem);
    font-weight: 700;
    line-height: 1.2;
    margin: 0 0 0.75rem;
  }

  .stats-counter__subheading {
    color: var(--sc-label-color, #6b7280);
    font-size: 1.125rem;
    line-height: 1.6;
    margin: 0;
  }

  /* Grid */
  .stats-counter__grid {
    display: grid;
    grid-template-columns: repeat(var(--sc-cols-mobile, 2), 1fr);
    gap: var(--sc-gap, 32px);
  }

  @media (min-width: 640px) {
    .stats-counter__grid {
      grid-template-columns: repeat(var(--sc-cols-tablet, 4), 1fr);
    }
  }

  @media (min-width: 993px) {
    .stats-counter__grid {
      grid-template-columns: repeat(var(--sc-cols-desktop, 4), 1fr);
    }
  }

  /* Item */
  .stats-counter__item {
    position: relative;
  }

  .stats-counter--align-center .stats-counter__item {
    text-align: center;
  }

  .stats-counter--align-left .stats-counter__item {
    text-align: left;
  }

  /* Dividers - desktop only */
  @media (min-width: 993px) {
    .stats-counter--dividers .stats-counter__item:not(:last-child)::after {
      content: '';
      position: absolute;
      right: calc(var(--sc-gap, 32px) / -2);
      top: 50%;
      transform: translateY(-50%);
      height: 60%;
      width: 1px;
      background-color: var(--sc-divider-color, #e5e7eb);
    }
  }

  /* Value */
  .stats-counter__value {
    color: var(--sc-value-color, var(--color-text, #111827));
    line-height: 1;
    margin-bottom: 0.5rem;
    font-variant-numeric: tabular-nums;
    display: flex;
    align-items: baseline;
    flex-wrap: wrap;
  }

  .stats-counter--align-center .stats-counter__value {
    justify-content: center;
  }

  /* Highlighted stat */
  .stats-counter__item--highlight .stats-counter__value {
    color: var(--sc-highlight-color, var(--color-primary, #3b82f6));
  }

  /* Value sizes */
  .stats-counter__value--3xl { font-size: clamp(1.875rem, 5vw, 2.25rem); }
  .stats-counter__value--4xl { font-size: clamp(2.25rem, 6vw, 3rem); }
  .stats-counter__value--5xl { font-size: clamp(2.5rem, 7vw, 3.75rem); }
  .stats-counter__value--6xl { font-size: clamp(3rem, 8vw, 4.5rem); }

  /* Value weights */
  .stats-counter__value--semibold { font-weight: 600; }
  .stats-counter__value--bold { font-weight: 700; }
  .stats-counter__value--extrabold { font-weight: 800; }

  .stats-counter__prefix,
  .stats-counter__suffix {
    font-size: 0.6em;
    opacity: 0.8;
  }

  .stats-counter__number {
    display: inline-block;
  }

  /* Label */
  .stats-counter__label {
    color: var(--sc-label-color, #6b7280);
    line-height: 1.4;
  }

  .stats-counter__label--sm { font-size: 0.875rem; }
  .stats-counter__label--base { font-size: 1rem; }
  .stats-counter__label--lg { font-size: 1.125rem; }

  .stats-counter__label--uppercase {
    text-transform: uppercase;
    letter-spacing: 0.05em;
    font-weight: 500;
  }

  /* Animation - start state. Gated on .is-armed (added by JS) so that with JS
     disabled the numbers stay visible instead of being stuck at opacity:0. */
  .stats-counter--animate.is-armed .stats-counter__number {
    opacity: 0;
  }

  .stats-counter--animate.stats-counter--visible .stats-counter__number {
    opacity: 1;
  }

  /* Print */
  @media print {
    .stats-counter {
      padding: 1rem 0;
    }

    .stats-counter__grid {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }

    .stats-counter__item {
      flex: 0 0 auto;
      margin: 0.5rem;
    }
  }

  /* Dark mode */
  {% if theme.dark_mode.enabled %}
  @media (prefers-color-scheme: dark) {
    .stats-counter__heading,
    .stats-counter__value {
      color: var(--color-text);
    }

    .stats-counter__label {
      color: var(--color-text-muted);
    }

    /* :not(:last-child) to match the base divider rule's specificity — otherwise
       this override can't win and dividers stay light in dark mode. */
    .stats-counter--dividers .stats-counter__item:not(:last-child)::after {
      background-color: var(--color-border);
    }
  }
  {% endif %}

</style>
{% end_require_css %}

{# Animation script - only included when animation is enabled #}
{% if anim.animate_on_scroll %}
{% require_js position="footer" defer=true %}
<script>
(function() {
  var counters = document.querySelectorAll('.stats-counter--animate');

  if (!counters.length) return;

  // Reduced motion: skip the count-up, just reveal the final values.
  if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
    counters.forEach(function(counter) {
      counter.classList.add('stats-counter--visible');
    });
    return;
  }

  // Arm the hidden start-state only now that JS is running (see .is-armed CSS).
  counters.forEach(function(counter) {
    counter.classList.add('is-armed');
  });

  var animateCounter = function(element, target, duration, prefix, suffix) {
    var start = 0;
    var startTime = null;
    var isFloat = target.toString().indexOf('.') !== -1;
    var decimals = isFloat ? (target.toString().split('.')[1] || '').length : 0;
    var numericTarget = parseFloat(target.replace(/[^0-9.-]/g, ''));

    if (isNaN(numericTarget)) {
      element.textContent = target;
      return;
    }

    var step = function(timestamp) {
      if (!startTime) startTime = timestamp;
      var progress = Math.min((timestamp - startTime) / duration, 1);
      var easeProgress = 1 - Math.pow(1 - progress, 3); // easeOutCubic
      var current = start + (numericTarget - start) * easeProgress;

      element.textContent = isFloat ? current.toFixed(decimals) : Math.floor(current);

      if (progress < 1) {
        requestAnimationFrame(step);
      } else {
        element.textContent = target;
      }
    };

    requestAnimationFrame(step);
  };

  var observer = new IntersectionObserver(function(entries) {
    entries.forEach(function(entry) {
      if (entry.isIntersecting && !entry.target.classList.contains('stats-counter--visible')) {
        entry.target.classList.add('stats-counter--visible');
        var duration = parseInt(entry.target.dataset.duration) || 2000;

        entry.target.querySelectorAll('.stats-counter__value').forEach(function(valueEl) {
          var numberEl = valueEl.querySelector('.stats-counter__number');
          var value = valueEl.dataset.value;
          var prefix = valueEl.dataset.prefix || '';
          var suffix = valueEl.dataset.suffix || '';

          if (numberEl && value) {
            animateCounter(numberEl, value, duration, prefix, suffix);
          }
        });

        observer.unobserve(entry.target);
      }
    });
  }, { threshold: 0.2 });

  counters.forEach(function(counter) {
    observer.observe(counter);
  });
})();
</script>
{% end_require_js %}
{% endif %}
