{% comment %}
  block, margins (boolean), block_attributes (boolean)
{% endcomment %}

{% liquid
  assign item_count = 0
  if block.settings.arrivesdays != blank
    assign item_count = item_count | plus: 1
  endif
  if block.settings.text_2 != blank
    assign item_count = item_count | plus: 1
  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 }};--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 %}
>
  <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_1 != blank %}
      <img
        class="icon-align"
        src="{{ block.settings.custom_icon_1 | image_url }}"
        alt="{{ block.settings.custom_icon_1.alt }}"
        width="auto"
        height="auto"
        loading="lazy"
      >
    {% elsif block.settings.icon_1 != blank %}
      <span class="icon-align">
        {% render 'material-icon', icon: block.settings.icon_1, filled: block.settings.filled_icon_1 %}
      </span>
    {% endif %}
    <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
    >
  </span>

  {% if block.settings.text_2 != blank %}
    <p
      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 %}
      <span>{{- block.settings.text_2 -}}</span>
    </p>
  {% endif %}
</div>

<script>
  // Dynamic date calculation with skip days
  document.addEventListener('DOMContentLoaded', function() {
    initializeDynamicDates();
  });

  function initializeDynamicDates() {
    const dateElements = document.querySelectorAll('[data-dynamic-date="true"]');
    
    dateElements.forEach(function(element) {
      const parentElement = element.closest('dynamic-dates');
      if (!parentElement) return;
      
      const minDays = parseInt(element.getAttribute('data-min-days')) || 0;
      const maxDays = parseInt(element.getAttribute('data-max-days')) || 0;
      const messageTemplate = element.getAttribute('data-text');
      
      if (!messageTemplate) return;
      
      const dateFormat = parentElement.getAttribute('data-date-format');
      const dayLabels = parentElement.getAttribute('data-day-labels').split(',').map(s => s.trim());
      const monthLabels = parentElement.getAttribute('data-month-labels').split(',').map(s => s.trim());
      
      // Get skip settings
      const skipWeekdays = parentElement.getAttribute('data-skip-weekdays') || '';
      const skipDates = parentElement.getAttribute('data-skip-dates') || '';
      
      // Parse skip weekdays - convert day names to numbers
      const 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
      };
      
      const skipWeekdaysArray = skipWeekdays 
        ? skipWeekdays.split(',')
            .map(d => d.trim().toLowerCase())
            .map(d => dayNameMap[d])
            .filter(d => d !== undefined)
        : [];
      
      // Parse skip specific dates (format: YYYY-MM-DD)
      const skipDatesArray = skipDates 
        ? skipDates.split(',').map(d => d.trim()).filter(d => d) 
        : [];
      
      // Function to check if a date should be skipped
      function shouldSkipDate(date) {
        // Check if weekday should be skipped
        if (skipWeekdaysArray.includes(date.getDay())) {
          return true;
        }
        
        // Check if specific date should be skipped
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const dateString = year + '-' + month + '-' + day;
        
        if (skipDatesArray.includes(dateString)) {
          return true;
        }
        
        return false;
      }
      
      // Function to add business days
      function addBusinessDays(startDate, daysToAdd) {
        let currentDate = new Date(startDate.getTime());
        let daysAdded = 0;
        
        while (daysAdded < daysToAdd) {
          currentDate.setDate(currentDate.getDate() + 1);
          
          if (!shouldSkipDate(currentDate)) {
            daysAdded++;
          }
        }
        
        return currentDate;
      }
      
      // Calculate start and end dates
      const today = new Date();
      const startDate = addBusinessDays(today, minDays);
      const endDate = addBusinessDays(today, maxDays);
      
      // Format date function
      function formatDate(date, format) {
        const day = date.getDate();
        const month = date.getMonth();
        const dayOfWeek = date.getDay();
        
        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';
          }
        }
        
        const dayWithSuffix = day + getOrdinalSuffix(day);
        const paddedDay = String(day).padStart(2, '0');
        const 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;
        }
      }
      
      const startDateFormatted = formatDate(startDate, dateFormat);
      const endDateFormatted = formatDate(endDate, dateFormat);
      
      // Replace placeholders in message
      const finalMessage = messageTemplate
        .replace(/\[start_date\]/g, startDateFormatted)
        .replace(/\[end_date\]/g, endDateFormatted);
      
      element.innerHTML = finalMessage;
    });
  }
</script>