<style>
  #block-{{ block.id }}.countdown-bar {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    background-color: {{ block.settings.bg_color }};
    color: {{ block.settings.text_color }};
    padding: 8px 16px;
  }

  .countdown-bar p {
    margin: 0;
    line-height: normal;
  }

  #block-{{ block.id }} .countdown-bar-text {
    font-size: 14px;
    text-align: center;
  }

  #block-{{ block.id }} .countdown-bar-time-container {
    display: flex;
    align-items: center;
    gap: 2px;
  }

  #block-{{ block.id }} .countdown-bar-time-cell {
    min-width: 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 3px;
    background-color: {{ block.settings.time_bg_color }};
    color: {{ block.settings.time_text_color }};
    border-radius: 2px;
    padding: 3px;
    line-height: normal;
  }

  #block-{{ block.id }} .countdown-bar-time-number {
    font-size: 14px;
    font-weight: bold;
  }

  #block-{{ block.id }} .countdown-bar-time-label {
    font-size: 8px;
  }

  #block-{{ block.id }} .countdown-bar-time-separator {
    font-weight: bold;
  }

  #block-{{ block.id }} .hidden {
    display: none;
  }

  @media screen and (min-width: 700px) {
    #block-{{ block.id }} .countdown-bar-text {
      font-size: 16px;
    }
  }
</style>

{%- if block.settings.timerposition == 'ontop' -%}
  {% if block.settings.text != blank %}
    <div class="countdown-bar-text" style="text-align:center;">{{ block.settings.text }}</div>
  {% endif %}
  
  <style>
    #block-{{ block.id }}.countdown-bar {
      padding-top: 0px!important;
    }
  </style>
{% endif %}

{% liquid
  assign hide_days = false
  assign hide_hours = false

  if block.settings.auto_reset_enabled or block.settings.reset_daily_midnight
    if block.settings.reset_days == 0
      assign hide_days = true
    endif
    if block.settings.reset_days == 0 and block.settings.reset_hours == 0
      assign hide_hours = true
    endif
  endif
%}

<div id="block-{{ block.id }}" class="countdown-bar" {{ block.shopify_attributes }}>
  {%- if block.settings.timerposition == 'nextto' -%}
    {% if block.settings.text != blank %}
      <div class="countdown-bar-text">{{ block.settings.text }}</div>
    {% endif %}
  {% endif %}

  <div id="countdown-timer-{{ block.id }}" class="countdown-bar-time-container">
    <div class="countdown-bar-time-cell{% if hide_days %} hidden{% endif %}">
      <p class="countdown-bar-time-number days">00</p>
      <p class="countdown-bar-time-label">{{ block.settings.daystext | default: "DAYS" }}</p>
    </div>

    <p class="countdown-bar-time-separator{% if hide_days %} hidden{% endif %}">:</p>

    <div class="countdown-bar-time-cell{% if hide_hours %} hidden{% endif %}">
      <p class="countdown-bar-time-number hours">00</p>
      <p class="countdown-bar-time-label">{{ block.settings.hourstext | default: "HRS" }}</p>
    </div>

    <p class="countdown-bar-time-separator{% if hide_hours %} hidden{% endif %}">:</p>

    <div class="countdown-bar-time-cell">
      <p class="countdown-bar-time-number minutes">00</p>
      <p class="countdown-bar-time-label">{{ block.settings.minstext | default: "MIN" }}</p>
    </div>

    <p class="countdown-bar-time-separator">:</p>

    <div class="countdown-bar-time-cell">
      <p class="countdown-bar-time-number seconds">00</p>
      <p class="countdown-bar-time-label">{{ block.settings.sectext | default: "SEC" }}</p>
    </div>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
  var $ = window.jQuery || false;
  
  var countdownTimer = document.querySelector('#countdown-timer-{{ block.id }}');
  var resetDailyMidnight = Boolean({{ block.settings.reset_daily_midnight | default: false | json }});
  var autoResetEnabled = Boolean({{ block.settings.auto_reset_enabled | default: false | json }}) || resetDailyMidnight;
  var resetDuration = {
    days: parseInt({{ block.settings.reset_days | default: 0 }}),
    hours: parseInt({{ block.settings.reset_hours | default: 12 }}),
    minutes: parseInt({{ block.settings.reset_minutes | default: 0 }})
  };

  var currentConfig = JSON.stringify({
    days: resetDuration.days,
    hours: resetDuration.hours,
    minutes: resetDuration.minutes,
    dailyMidnight: resetDailyMidnight
  });

  function getStoredEndTime() {
    var storedConfig = localStorage.getItem('countdownConfig-{{ block.id }}');
    if (storedConfig !== currentConfig) {
      localStorage.removeItem('countdownEndTime-{{ block.id }}');
      localStorage.setItem('countdownConfig-{{ block.id }}', currentConfig);
      return null;
    }
    var storedTime = localStorage.getItem('countdownEndTime-{{ block.id }}');
    return storedTime ? parseInt(storedTime) : null;
  }

  function setStoredEndTime(endTime) {
    localStorage.setItem('countdownEndTime-{{ block.id }}', endTime.toString());
    localStorage.setItem('countdownConfig-{{ block.id }}', currentConfig);
  }

  function calculateEndTime() {
    if (resetDailyMidnight) {
      var now = new Date();
      var midnight = new Date(now);
      midnight.setHours(24, 0, 0, 0);
      return midnight.getTime();
    }
    var now = new Date().getTime();
    var duration = (resetDuration.days * 24 * 60 * 60 * 1000) +
                  (resetDuration.hours * 60 * 60 * 1000) +
                  (resetDuration.minutes * 60 * 1000);
    return now + duration;
  }

  function updateDisplay(timeLeft) {
    if (timeLeft.days < 0 || timeLeft.hours < 0 || timeLeft.minutes < 0 || timeLeft.seconds < 0) {
      timeLeft = { days: 0, hours: 0, minutes: 0, seconds: 0 };
    }
    
    if ($) {
      $(countdownTimer).find('.days').text(timeLeft.days.toString().padStart(2, '0'));
      $(countdownTimer).find('.hours').text(timeLeft.hours.toString().padStart(2, '0'));
      $(countdownTimer).find('.minutes').text(timeLeft.minutes.toString().padStart(2, '0'));
      $(countdownTimer).find('.seconds').text(timeLeft.seconds.toString().padStart(2, '0'));
    } else {
      countdownTimer.querySelector('.days').textContent = timeLeft.days.toString().padStart(2, '0');
      countdownTimer.querySelector('.hours').textContent = timeLeft.hours.toString().padStart(2, '0');
      countdownTimer.querySelector('.minutes').textContent = timeLeft.minutes.toString().padStart(2, '0');
      countdownTimer.querySelector('.seconds').textContent = timeLeft.seconds.toString().padStart(2, '0');
    }
  }

  function calculateTimeLeft() {
    var targetDate;
    
    if (autoResetEnabled) {
      if (resetDailyMidnight) {
        targetDate = calculateEndTime();
      } else {
        targetDate = getStoredEndTime();
        if (!targetDate) {
          targetDate = calculateEndTime();
          setStoredEndTime(targetDate);
        }
      }
    } else {
      var dateString = "{{ block.settings.end_date }} {{ block.settings.end_time }}";
      targetDate = new Date(dateString).getTime();
      
      if (isNaN(targetDate)) {
        console.error('Invalid date format:', dateString);
        return { days: 0, hours: 0, minutes: 0, seconds: 0 };
      }
    }

    var now = new Date().getTime();
    var distance = targetDate - now;

    if (distance < 0 && autoResetEnabled) {
      targetDate = calculateEndTime();
      if (!resetDailyMidnight) {
        setStoredEndTime(targetDate);
      }
      distance = targetDate - now;
    }

    if (distance < 0) {
      return { days: 0, hours: 0, minutes: 0, seconds: 0 };
    }

    return {
      days: Math.floor(distance / (1000 * 60 * 60 * 24)),
      hours: Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minutes: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
      seconds: Math.floor((distance % (1000 * 60)) / 1000)
    };
  }

  updateDisplay(calculateTimeLeft());

  var intervalId = setInterval(function() {
    var timeLeft = calculateTimeLeft();
    updateDisplay(timeLeft);
  }, 1000);

  window.addEventListener('unload', function() {
    clearInterval(intervalId);
  });
});
</script>