{% comment %}
  block, margins (boolean), block_attributes (boolean)
{% endcomment %}
{% liquid
  assign item_count = 0
  if block.settings.text_2 != blank or block.settings.show_shipping_time
    assign item_count = item_count | plus: 1
  endif
%}

{%- assign text2_raw = block.settings.text_2 -%}
{%- assign text2_has_country = false -%}
{%- if text2_raw contains '[country]' -%}
  {%- assign text2_has_country = true -%}
{%- endif -%}

<div
  class="product__text-container product__text-container--{{ block.settings.alignment }}{% if mobile_align %} product__text-container--mobile-{{ block.settings.mobile_alignment }}{% endif %} product__text-container--{{ block.settings.direction }} product__text-container--{{ block.settings.width }} product__text-container--styling-container{% if block.settings.enable_bg %} product__text-container--background{% endif %}{% if item_count > 1 %} product__text-container--multiple{% endif %}{% if block.settings.width == 'full_negative' %} side-margins-negative{% endif %} {{ block.settings.visibility }}"
  style="--item-count:{{ item_count }};--mobile-text-size: {{ block.settings.mobile_text_size | divided_by: 10.0 }}rem;--desktop-text-size: {{ block.settings.desktop_text_size | divided_by: 10.0 }}rem;--icon-scale:{{ block.settings.icon_scale | divided_by: 100.0 }};--column-gap:{{ block.settings.column_gap | divided_by: 2.0 }}em;--row-gap:{{ block.settings.column_gap | divided_by: 5.0 }}em;--padding:{{ block.settings.padding | divided_by: 7.0 }}em;--bg-color:{{ block.settings.bg_color }};--corner-radius:{{ block.settings.corner_radius | divided_by: 100.0 }}em;--border-size:{{ block.settings.border_size }}px;--border-color:{{ block.settings.border_color }};{% if block.settings.dashedborder %}border-style: dashed;{% endif %}--margin-top: {{ block.settings.margin_top | divided_by: 10.0 }}rem;--margin-bottom: {{ block.settings.margin_bottom | divided_by: 10.0 }}rem;"
  {% if block_attributes %}
    {{- block.shopify_attributes -}}
  {% endif %}
>
  <div class="product__text-wrapper" style="display: flex; align-items: center; justify-content: space-between; width: 100%; {% if block.settings.layout_order == 'flipped' %}flex-direction: row-reverse;{% endif %}">

    {% comment %} Left side: blinking dot + shipping date text {% endcomment %}
    <span
      class="product__text product__text-{{ block.settings.alignment }}{% if mobile_align %} product__text-mobile-{{ block.settings.mobile_alignment }}{% endif %}"
      style="--text-color:{{ block.settings.text_color }};--icon-color:{{ block.settings.icon_color }};"
    >
      <div class="sfrom_text_newshipping">
        <dynamic-dates
          class="estimated-shipping"
          data-date-format="{{ block.settings.date_format }}"
          data-day-labels="{{ block.settings.days_labels }}"
          data-month-labels="{{ block.settings.months_labels }}"
          data-skip-weekdays="{{ block.settings.skip_weekdays }}"
          data-skip-dates="{{ block.settings.skip_specific_dates }}"
        >
          <span
            class="estimated-shipping__text new"
            style="margin:auto;"
            data-dynamic-date="true"
            data-text="{{ block.settings.arrivesdays }}"
            data-min-days="{{ block.settings.min_shipping_days }}"
            data-max-days="{{ block.settings.max_shipping_days }}"
          >
            {{- block.settings.arrivesdays | replace: '[start_date]' | replace: '[end_date]' -}}
          </span>
        </dynamic-dates>
      </div>
    </span>

    {% comment %} Right side: text_2 / shipping time / geo flag {% endcomment %}
    {% if block.settings.show_shipping_time %}
      <span
        class="product__text product__text-{{ block.settings.alignment }}{% if mobile_align %} product__text-mobile-{{ block.settings.mobile_alignment }}{% endif %}"
        style="--text-color:{{ block.settings.text_color }};--icon-color:{{ block.settings.icon_color }};"
      >
        {% if block.settings.custom_icon_2 != blank %}
          <img
            class="icon-align"
            src="{{ block.settings.custom_icon_2 | image_url }}"
            alt="{{ block.settings.custom_icon_2.alt }}"
            width="auto"
            height="auto"
            loading="lazy"
          >
        {% elsif block.settings.icon_2 != blank %}
          <span class="icon-align">
            {% render 'material-icon', icon: block.settings.icon_2, filled: block.settings.filled_icon_2 %}
          </span>
        {% endif %}
        {{ block.settings.dot_text }}
      </span>

    {% elsif block.settings.text_2 != blank %}
      <span
        class="product__text sfrom_blinkingshipping__text2 product__text-{{ block.settings.alignment }}{% if mobile_align %} product__text-mobile-{{ block.settings.mobile_alignment }}{% endif %}"
        style="--text-color:{{ block.settings.text_color }};--icon-color:{{ block.settings.icon_color }};"
        {% if text2_has_country %}data-geo-text="{{ text2_raw | escape }}"{% endif %}
      >
        <span class="sfrom_blinkingshipping__icon icon-align">
          {% if text2_has_country %}
            {{- '🌍' -}}
          {% elsif block.settings.custom_icon_2 != blank %}
            <img
              src="{{ block.settings.custom_icon_2 | image_url }}"
              alt="{{ block.settings.custom_icon_2.alt }}"
              width="auto"
              height="auto"
              loading="lazy"
            >
          {% elsif block.settings.icon_2 != blank %}
            {% render 'material-icon', icon: block.settings.icon_2, filled: block.settings.filled_icon_2 %}
          {% endif %}
        </span>
        <span class="sfrom_blinkingshipping__label">
          {{- text2_raw | replace: '[country]', '' | strip -}}
        </span>
      </span>

    {% endif %}
  </div>

  <style>
    .sfrom_text_newshipping p:before {
      position: relative;
      display: inline-block;
      content: "";
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: {{ block.settings.dot_color }};
      margin-right: 5px;
      animation: blink 1.5s infinite;
    }
    .sfrom_text_newshipping p {
      display: flex;
      align-items: center;
      gap: 5px;
      line-height: 1;
      margin: 0;
      position: relative;
      font-weight: 400;
      color: {{ block.settings.text_color }};
    }
    @keyframes blink {
      0%   { opacity: 1; }
      50%  { opacity: 0.5; }
      100% { opacity: 1; }
    }
    .sfrom_blinkingshipping__icon {
      display: inline-flex;
      align-items: center;
      margin-right: 4px;
    }
    .sfrom_blinkingshipping__icon span {
      font-size: 1.2em;
      line-height: 1;
    }
    .sfrom_blinkingshipping__label {
      display: inline;
    }
  </style>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    initializeDynamicDates();
    initializeGeoText();
  });

  // ─── GEO COUNTRY REPLACEMENT ─────────────────────────────────────────────────
  // Runs only when text_2 contains [country]. Fetches the visitor's country via
  // ipapi.co, replaces [country] with the country name, and swaps the globe
  // placeholder icon with the actual country flag emoji.

  function initializeGeoText() {
    var geoSpans = document.querySelectorAll('.sfrom_blinkingshipping__text2[data-geo-text]');
    if (!geoSpans.length) return;

    fetch('https://ipapi.co/json/')
      .then(function(res) { return res.json(); })
      .then(function(data) {
        var countryCode = (data.country_code || '').toUpperCase();

        // Short display names — common ones get a familiar abbreviation,
        // everything else falls back to the ISO 2-letter code.
        var shortNameMap = {
          'US': 'USA',
          'GB': 'UK',
          'CA': 'CA',
          'AU': 'AU',
          'NZ': 'NZ',
          'DE': 'DE',
          'FR': 'FR',
          'ES': 'ES',
          'IT': 'IT',
          'NL': 'NL',
          'BE': 'BE',
          'CH': 'CH',
          'AT': 'AT',
          'SE': 'SE',
          'NO': 'NO',
          'DK': 'DK',
          'FI': 'FI',
          'PL': 'PL',
          'PT': 'PT',
          'IE': 'IE',
          'JP': 'JP',
          'KR': 'KR',
          'CN': 'CN',
          'IN': 'IN',
          'BR': 'BR',
          'MX': 'MX',
          'ZA': 'ZA',
          'SG': 'SG',
          'HK': 'HK',
          'AE': 'UAE',
          'SA': 'KSA'
        };
        var countryName = shortNameMap[countryCode] || countryCode;

        // Build flag emoji from ISO 3166-1 alpha-2 code using regional indicator symbols
        var flagEmoji = '';
        if (countryCode.length === 2) {
          flagEmoji = countryCode.replace(/[A-Z]/g, function(c) {
            return String.fromCodePoint(0x1F1E6 + c.charCodeAt(0) - 65);
          });
        }

        geoSpans.forEach(function(span) {
          var raw = span.getAttribute('data-geo-text');
          var replaced = raw.replace(/\[country\]/gi, countryName);

          // Update the text label
          var labelEl = span.querySelector('.sfrom_blinkingshipping__label');
          if (labelEl) labelEl.innerHTML = replaced;

          // Swap the globe placeholder with the real country flag
          if (flagEmoji) {
            var iconEl = span.querySelector('.sfrom_blinkingshipping__icon');
            if (iconEl) {
              iconEl.innerHTML = '<span style="font-size:1.2em;line-height:1;">' + flagEmoji + '</span>';
            }
          }
        });
      })
      .catch(function() {
        // Graceful fallback: strip [country] so text still reads naturally
        geoSpans.forEach(function(span) {
          var raw = span.getAttribute('data-geo-text');
          var fallback = raw.replace(/\[country\]/gi, '').replace(/\s{2,}/g, ' ').trim();

          var labelEl = span.querySelector('.sfrom_blinkingshipping__label');
          if (labelEl) labelEl.innerHTML = fallback;

          // Leave globe emoji in place as a neutral fallback icon
        });
      });
  }

  // ─── DYNAMIC DATES ────────────────────────────────────────────────────────────

  function initializeDynamicDates() {
    var dateElements = document.querySelectorAll('[data-dynamic-date="true"]');

    dateElements.forEach(function(element) {
      var parentElement = element.closest('dynamic-dates');
      if (!parentElement) return;

      var minDays = parseInt(element.getAttribute('data-min-days')) || 0;
      var maxDays = parseInt(element.getAttribute('data-max-days')) || 0;
      var messageTemplate = element.getAttribute('data-text');

      if (!messageTemplate) return;

      var dateFormat  = parentElement.getAttribute('data-date-format');
      var dayLabels   = parentElement.getAttribute('data-day-labels').split(',').map(function(s) { return s.trim(); });
      var monthLabels = parentElement.getAttribute('data-month-labels').split(',').map(function(s) { return s.trim(); });

      var skipWeekdays = parentElement.getAttribute('data-skip-weekdays') || '';
      var skipDates    = parentElement.getAttribute('data-skip-dates') || '';

      var dayNameMap = {
        'sunday': 0, 'sun': 0,
        'monday': 1, 'mon': 1,
        'tuesday': 2, 'tue': 2, 'tues': 2,
        'wednesday': 3, 'wed': 3,
        'thursday': 4, 'thu': 4, 'thur': 4, 'thurs': 4,
        'friday': 5, 'fri': 5,
        'saturday': 6, 'sat': 6
      };

      var skipWeekdaysArray = skipWeekdays
        ? skipWeekdays.split(',')
            .map(function(d) { return d.trim().toLowerCase(); })
            .map(function(d) { return dayNameMap[d]; })
            .filter(function(d) { return d !== undefined; })
        : [];

      var skipDatesArray = skipDates
        ? skipDates.split(',').map(function(d) { return d.trim(); }).filter(function(d) { return d; })
        : [];

      function shouldSkipDate(date) {
        if (skipWeekdaysArray.includes(date.getDay())) return true;
        var year  = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day   = String(date.getDate()).padStart(2, '0');
        return skipDatesArray.includes(year + '-' + month + '-' + day);
      }

      function addBusinessDays(startDate, daysToAdd) {
        var currentDate = new Date(startDate.getTime());
        var daysAdded = 0;
        while (daysAdded < daysToAdd) {
          currentDate.setDate(currentDate.getDate() + 1);
          if (!shouldSkipDate(currentDate)) daysAdded++;
        }
        return currentDate;
      }

      var today     = new Date();
      var startDate = addBusinessDays(today, minDays);
      var endDate   = addBusinessDays(today, maxDays);

      function getOrdinalSuffix(day) {
        if (day > 3 && day < 21) return 'th';
        switch (day % 10) {
          case 1: return 'st';
          case 2: return 'nd';
          case 3: return 'rd';
          default: return 'th';
        }
      }

      function formatDate(date, format) {
        var day       = date.getDate();
        var month     = date.getMonth();
        var dayOfWeek = date.getDay();
        var dayWithSuffix = day + getOrdinalSuffix(day);
        var paddedDay   = String(day).padStart(2, '0');
        var paddedMonth = String(month + 1).padStart(2, '0');

        switch (format) {
          case 'day_mm_dd':         return dayLabels[dayOfWeek] + ', ' + monthLabels[month] + ' ' + dayWithSuffix;
          case 'day_dd_mm':         return dayLabels[dayOfWeek] + ', ' + day + '. ' + monthLabels[month];
          case 'mm_dd':             return monthLabels[month] + ' ' + dayWithSuffix;
          case 'month_day':         return monthLabels[month] + ' ' + day;
          case 'dd_mm':             return day + '. ' + monthLabels[month];
          case 'dd_mm_no_dot':      return day + ' ' + monthLabels[month];
          case 'day_dd_mm_numeric': return dayLabels[dayOfWeek] + ', ' + paddedDay + '. ' + paddedMonth + '.';
          case 'dd_mm_numeric':     return paddedDay + '. ' + paddedMonth + '.';
          default:                  return monthLabels[month] + ' ' + dayWithSuffix;
        }
      }

      var startDateFormatted = formatDate(startDate, dateFormat);
      var endDateFormatted   = formatDate(endDate, dateFormat);

      var finalMessage = messageTemplate
        .replace(/\[start_date\]/g, startDateFormatted)
        .replace(/\[end_date\]/g, endDateFormatted);

      element.innerHTML = finalMessage;
    });
  }
</script>