{% liquid
  assign block_id = block.id | handle
  assign align_class = block.settings.content_alignment | default: 'center'
%}

<dynamic-dates
  id="estimated-shipping-{{ block_id }}"
  class="estimated-shipping{% if block.settings.icon_alignment == 'middle' %} estimated-shipping--align-center{% endif %}{% if block.settings.show_timer %} estimated-shipping--timer-enabled{% endif %}{% if block.settings.custom_icon == blank and block.settings.icon == blank %} estimated-shipping--no-icon{% endif %}"
  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 }}"
  {{ block.shopify_attributes }}
  style="--margin-top: {{ block.settings.margin_top | divided_by: 10.0 }}rem;--margin-bottom: {{ block.settings.margin_bottom | divided_by: 10.0 }}rem;"
>
  {% unless block.settings.custom_icon == blank and block.settings.icon == blank %}
    {% unless block.settings.show_timer %}
      <div class="estimated-shipping__icon estimated-shipping__icon--{{ block.settings.icon_size }}">
        {% if block.settings.custom_icon != blank %}
          <img
            src="{{ block.settings.custom_icon | image_url: width: 150 }}"
            width="auto"
            height="auto"
            loading="lazy"
          >
        {% else %}
          {% render 'material-icon', icon: block.settings.icon, filled: block.settings.filled_icon %}
        {% endif %}
      </div>
    {% endunless %}
  {% endunless %}
  
  <div class="estimated-shipping__content">
    <div class="estimated-shipping__text-container">
      {% unless block.settings.custom_icon == blank and block.settings.icon == blank %}
        {% if block.settings.show_timer %}
          <div class="estimated-shipping__icon estimated-shipping__icon--{{ block.settings.icon_size }}">
            {% if block.settings.custom_icon != blank %}
              <img
                src="{{ block.settings.custom_icon | image_url: width: 150 }}"
                width="auto"
                height="auto"
                loading="lazy"
              >
            {% else %}
              {% render 'material-icon', icon: block.settings.icon, filled: block.settings.filled_icon %}
            {% endif %}
          </div>
        {% endif %}
      {% endunless %}
      
      <div 
        class="estimated-shipping__text"
        data-dynamic-date='true'
        data-text="{{ block.settings.message }}"
        data-min-days="{{ block.settings.min_shipping_days }}"
        data-max-days="{{ block.settings.max_shipping_days }}"
      >
        {{ block.settings.message | replace: '[start_date]', '-' | replace: '[end_date]', '-' }}
      </div>
    </div>

    {% if block.settings.show_timer %}
      <div 
        class="estimated-shipping__timer"
        data-cutoff-time="{{ block.settings.cutoff_time | escape }}"
        data-timezone="{{ block.settings.timezone }}"
        data-timer-prefix="{{ block.settings.timer_prefix | default: 'ORDER WITHIN' }}"
        data-hours-text="{{ block.settings.hours_text | default: 'HOURS' }}"
        data-minutes-text="{{ block.settings.minutes_text | default: 'MINUTES' }}"
        style="--timer-text-color: {{ block.settings.timer_text_color | default: '#333333' }}; --timer-value-color: {{ block.settings.timer_value_color | default: '#6366f1' }};"
      >
        <span class="timer-text">{{ block.settings.timer_prefix | default: 'ORDER WITHIN' }} </span>
        <span class="timer-value">
          <span class="timer-hours">0</span> {{ block.settings.hours_text | default: 'HOURS' }} 
          <span class="timer-minutes">0</span> {{ block.settings.minutes_text | default: 'MINUTES' }}
        </span>
      </div>
    {% endif %}
  </div>
</dynamic-dates>

<style>
  {% if block.settings.enable_custom_colors %}
  #estimated-shipping-{{ block_id }} {
    background-color: {{ block.settings.background_color }};
    color: {{ block.settings.text_color }};
    padding: {{ block.settings.vertical_padding }}px 16px;
    border-radius: {{ block.settings.border_radius }}px;
  }
  
  #estimated-shipping-{{ block_id }} .estimated-shipping__timer .timer-text {
    color: {{ block.settings.timer_text_color | default: block.settings.text_color }};
  }
  
  #estimated-shipping-{{ block_id }} .estimated-shipping__timer .timer-value {
    color: {{ block.settings.text_color }};
  }
  
  #estimated-shipping-{{ block_id }} .estimated-shipping__timer .timer-hours,
  #estimated-shipping-{{ block_id }} .estimated-shipping__timer .timer-minutes {
    color: {{ block.settings.timer_value_color }};
  }
  {% endif %}
  
  .estimated-shipping {
    display: flex;
    align-items: flex-start;
    gap: 10px;
  }
  
  .estimated-shipping--align-center {
    align-items: center;
  }
  
  .estimated-shipping__content {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }
  
  .estimated-shipping__text-container {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .estimated-shipping__timer {
    font-weight: bold;
  }
  
  .estimated-shipping__timer .timer-text {
    color: var(--timer-text-color, #333);
  }
  
  .estimated-shipping__timer .timer-value {
    color: var(--timer-text-color, #333);
  }
  
  .estimated-shipping__timer .timer-hours,
  .estimated-shipping__timer .timer-minutes {
    color: var(--timer-value-color, #6366f1);
  }
  
  /* Timer enabled styles */
  .estimated-shipping--timer-enabled {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .estimated-shipping--timer-enabled .estimated-shipping__content {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .estimated-shipping--timer-enabled .estimated-shipping__text-container {
    text-align: center;
    display: flex;
    align-items: center;
    gap: 10px;
    justify-content: center;
  }
  
  .estimated-shipping--timer-enabled .estimated-shipping__timer {
    text-align: center;
  }
  
  /* No icon styles - center everything */
  .estimated-shipping--no-icon {
    justify-content: center;
    align-items: center;
    text-align: center;
  }
  
  .estimated-shipping--no-icon .estimated-shipping__content {
    align-items: center;
    text-align: center;
  }
  
  .estimated-shipping--no-icon .estimated-shipping__text-container {
    justify-content: center;
    text-align: center;
  }
  
  .estimated-shipping--no-icon .estimated-shipping__timer {
    text-align: center;
  }

  /* Content alignment â€” scoped to block instance, placed last to win cascade */
  #estimated-shipping-{{ block_id }} {
    justify-content: {{ block.settings.content_alignment | default: 'center' }};
  }
  #estimated-shipping-{{ block_id }} .estimated-shipping__content {
    align-items: {% if block.settings.content_alignment == 'left' %}flex-start{% else %}center{% endif %};
    flex: {% if block.settings.content_alignment == 'left' %}1{% else %}0 1 auto{% endif %};
  }
  #estimated-shipping-{{ block_id }} .estimated-shipping__text-container {
    justify-content: {% if block.settings.content_alignment == 'left' %}flex-start{% else %}center{% endif %};
  }
  #estimated-shipping-{{ block_id }} .estimated-shipping__timer {
    text-align: {{ block.settings.content_alignment | default: 'center' }};
  }
</style>

<script>
  // Timer functionality
  document.addEventListener('DOMContentLoaded', function() {
    if (document.querySelector('.estimated-shipping__timer')) {
      initializeTimers();
    }
    // Initialize date calculations
    initializeDynamicDates();
  });

  function initializeTimers() {
    const timerElements = document.querySelectorAll('.estimated-shipping__timer');
    
    timerElements.forEach(function(timerElement) {
      const cutoffTime = timerElement.getAttribute('data-cutoff-time');
      const timezone = timerElement.getAttribute('data-timezone');
      
      updateTimer(timerElement, cutoffTime, timezone);
      
      setInterval(function() {
        updateTimer(timerElement, cutoffTime, timezone);
      }, 60000);
    });
  }

  function updateTimer(timerElement, cutoffTime, timezone) {
    const now = new Date();
    const [hours, minutes] = cutoffTime.split(':').map(Number);
    
    if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
      console.error('Invalid cutoff time format. Please use HH:MM in 24-hour format.');
      timerElement.innerHTML = '<div class="timer-error">Invalid time format</div>';
      return;
    }
    
    const cutoff = new Date();
    cutoff.setHours(hours, minutes, 0, 0);
    
    if (cutoff < now) {
      cutoff.setDate(cutoff.getDate() + 1);
    }
    
    const timeRemaining = cutoff - now;
    const hoursRemaining = Math.floor(timeRemaining / (1000 * 60 * 60));
    const minutesRemaining = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
    
    timerElement.querySelector('.timer-hours').textContent = hoursRemaining;
    timerElement.querySelector('.timer-minutes').textContent = minutesRemaining;
  }

  // Dynamic date calculation with skip days
  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');
      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>