<style>
    #section-{{ section.id }}.countdown-bar {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 16px;
      {% if section.settings.animated_gradient_enabled %}
        background: linear-gradient(-45deg, {{ section.settings.gradient_color_1 }}, {{ section.settings.gradient_color_2 }}, {{ section.settings.gradient_color_3 }}, {{ section.settings.gradient_color_4 }});
        background-size: 400% 400%;
        animation: primaryGradient 5s ease infinite;
      {% else %}
        background-color: {{ section.settings.bg_color }};
      {% endif %}
      color: {{ section.settings.text_color }};
      padding: 8px 16px;
    }

    {% if section.settings.animated_gradient_enabled %}
      @keyframes primaryGradient {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
      }
    {% endif %}

    @media screen and (max-width: 699px) {
      #section-{{ section.id }}.countdown-bar {
        {% if section.settings.text_alignment == 'top_center' %}
          flex-direction: column;
          gap: 4px;
        {% endif %}
      }
    }

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

    #section-{{ section.id }} .countdown-bar-text-wrap {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    #section-{{ section.id }} .countdown-bar-text {
      font-size: {{ section.settings.text_font_size }}px;
      text-align: center;
    }

    #section-{{ section.id }} .countdown-bar-subtext {
      font-size: {{ section.settings.subtext_font_size }}px;
      text-align: center;
      margin-top: 2px;
    }

    @media screen and (max-width: 699px) {
      #section-{{ section.id }} .countdown-bar-text-wrap {
        {% if section.settings.text_alignment == 'top_center' %}
          margin-bottom: 4px;
        {% endif %}
      }
    }

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

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

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

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

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

    @media screen and (min-width: 700px) {
      #section-{{ section.id }} .countdown-bar-text {
        font-size: {{ section.settings.text_font_size_desktop }}px;
      }
      #section-{{ section.id }} .countdown-bar-subtext {
        font-size: {{ section.settings.subtext_font_size_desktop }}px;
      }
    }

    /* ── Compact design ──────────────────────────────────── */
    #section-{{ section.id }}.design-compact {
      gap: 14px;
      padding: 8px 20px;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-text-wrap {
      align-items: flex-start;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-text {
      text-align: left;
      font-weight: 500;
      white-space: nowrap;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-text {
    font-size: 14px;
  }

  @media screen and (min-width: 700px) {
    #section-{{ section.id }}.design-compact .countdown-bar-text {
      font-size: 18px;
    }
  }

    #section-{{ section.id }}.design-compact .countdown-bar-time-container {
      gap: 6px;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-time-cell {
      flex-direction: row;
      align-items: center;
      gap: 5px;
      background-color: rgba(255,255,255,0.15);
      color: {{ section.settings.text_color }};
      border-radius: 3px;
      padding: 4px 10px;
      min-width: unset;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-time-number {
      font-size: 14px;
      font-weight: 500;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-time-label {
      font-size: 14px;
      font-weight: 500;
      text-transform: uppercase;
    }

    #section-{{ section.id }}.design-compact .countdown-bar-time-separator {
      display: none;
    }

    @media screen and (max-width: 699px) {
      #section-{{ section.id }}.design-compact {
        gap: 10px;
        padding: 6px 15px;
      }
      #section-{{ section.id }}.design-compact .countdown-bar-text {
        white-space: normal;
      }
      #section-{{ section.id }}.design-compact .countdown-bar-time-cell {
        padding: 4px 8px;
        gap: 4px;
      }
      #section-{{ section.id }}.design-compact .countdown-bar-time-number,
      #section-{{ section.id }}.design-compact .countdown-bar-time-label {
        font-size: 12px;
      }
    }

    /* ── Pill design ─────────────────────────────────────── */
  #section-{{ section.id }}.design-pill {
    gap: 14px;
    padding: 8px 20px;
  }

  #section-{{ section.id }}.design-pill .countdown-bar-time-container {
    background-color: {{ section.settings.time_bg_color }};
    border-radius: {{ section.settings.pill_border_radius }}px;
    padding: 4px 12px;
    gap: 2px;
  }

  #section-{{ section.id }}.design-pill .countdown-bar-time-cell {
    background-color: transparent;
    color: {{ section.settings.time_text_color }};
    border-radius: 0;
    padding: 2px 4px;
    min-width: 28px;
    gap: 2px;
  }

  #section-{{ section.id }}.design-pill .countdown-bar-time-number {
    font-size: 14px;
    font-weight: 700;
  }

  #section-{{ section.id }}.design-pill .countdown-bar-time-label {
    font-size: 8px;
    font-weight: 400;
  }

  #section-{{ section.id }}.design-pill .countdown-bar-time-separator {
    color: {{ section.settings.time_text_color }};
    font-weight: 700;
    font-size: 14px;
    line-height: 1;
    align-self: flex-start;
    padding-top: 3px;
  }

  @media screen and (max-width: 699px) {
    #section-{{ section.id }}.design-pill {
      gap: 10px;
      padding: 6px 14px;
    }
    #section-{{ section.id }}.design-pill .countdown-bar-time-container {
      padding: 3px 10px;
    }
    #section-{{ section.id }}.design-pill .countdown-bar-time-cell {
      min-width: 24px;
      padding: 2px 3px;
    }
    #section-{{ section.id }}.design-pill .countdown-bar-time-number {
      font-size: 12px;
    }
    #section-{{ section.id }}.design-pill .countdown-bar-time-separator {
      font-size: 12px;
      padding-top: 2px;
    }
  }
</style>

{% liquid
  assign displayed = true

  # Handle product page visibility
  if section.settings.hidden_products != blank and product
    assign hidden_handles = section.settings.hidden_products | split: ','
    for hidden_handle in hidden_handles
      assign handle_strip = hidden_handle | strip
      if handle_strip == product.handle
        assign displayed = false
        break
      endif
    endfor
  endif

  if section.settings.enable_specific_display and section.settings.displayed_products != blank and product
    assign displayed_handles = section.settings.displayed_products | split: ','
    assign displayed = false
    for displayed_handle in displayed_handles
      assign handle_strip = displayed_handle | strip
      if handle_strip == product.handle
        assign displayed = true
        break
      endif
    endfor
  endif

  # Handle normal page visibility
  if section.settings.hidden_pages != blank and page
    assign hidden_page_handles = section.settings.hidden_pages | split: ','
    for hidden_page_handle in hidden_page_handles
      assign page_handle_strip = hidden_page_handle | strip
      if page_handle_strip == page.handle
        assign displayed = false
        break
      endif
    endfor
  endif

  if section.settings.enable_specific_page_display and section.settings.displayed_pages != blank and page
    assign displayed_page_handles = section.settings.displayed_pages | split: ','
    assign displayed = false
    for displayed_page_handle in displayed_page_handles
      assign page_handle_strip = displayed_page_handle | strip
      if page_handle_strip == page.handle
        assign displayed = true
        break
      endif
    endfor
  endif
%}

{% if displayed %}
  <div
    id="section-{{ section.id }}"
    class="countdown-bar{% if section.settings.design_style == 'compact' %} design-compact{% elsif section.settings.design_style == 'pill' %} design-pill{% endif %}"
  >
    {% if section.settings.text != blank or section.settings.subtext != blank %}
      <div class="countdown-bar-text-wrap">
        {% if section.settings.text != blank %}
          <div class="countdown-bar-text">{{ section.settings.text }}</div>
        {% endif %}
        {% if section.settings.subtext != blank %}
          <div class="countdown-bar-subtext">{{ section.settings.subtext }}</div>
        {% endif %}
      </div>
    {% endif %}
    <div id="countdown-timer-{{ section.id }}" class="countdown-bar-time-container">
      {% assign hide_days = false %}
      {% assign hide_seconds = false %}
      {% if section.settings.auto_reset_enabled and section.settings.reset_days == 0 %}
        {% assign hide_days = true %}
      {% endif %}
      {% if section.settings.design_style == 'compact' and hide_days == false %}
        {% assign hide_seconds = true %}
      {% endif %}

      <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">{{ section.settings.daystext }}</p>
      </div>
      <p class="countdown-bar-time-separator {% if hide_days %}hidden{% endif %}">:</p>

      <div class="countdown-bar-time-cell">
        <p class="countdown-bar-time-number hours">00</p>
        <p class="countdown-bar-time-label">{{ section.settings.hourstext }}</p>
      </div>

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

      <div class="countdown-bar-time-cell">
        <p class="countdown-bar-time-number minutes">00</p>
        <p class="countdown-bar-time-label">{{ section.settings.minstext }}</p>
      </div>

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

      <div class="countdown-bar-time-cell {% if hide_seconds %}hidden{% endif %}">
        <p class="countdown-bar-time-number seconds">00</p>
        <p class="countdown-bar-time-label">{{ section.settings.sectext }}</p>
      </div>
    </div>
  </div>
{% endif %}

<script>
  document.addEventListener("DOMContentLoaded", function() {
    // Check if jQuery exists, if not use vanilla JS
    var $ = window.jQuery || false;

    var countdownTimer = document.querySelector('#countdown-timer-{{ section.id }}');
    var resetDailyMidnight = Boolean({{ section.settings.reset_daily_midnight | json }});
    var autoResetEnabled = Boolean({{ section.settings.auto_reset_enabled | json }}) || resetDailyMidnight;
    var resetDuration = {
      days: parseInt({{ section.settings.reset_days | default: 0 }}),
      hours: parseInt({{ section.settings.reset_hours | default: 12 }}),
      minutes: parseInt({{ section.settings.reset_minutes | default: 0 }})
    };

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

    function getStoredEndTime() {
      // Check if config has changed
      var storedConfig = localStorage.getItem('countdownConfig-{{ section.id }}');
      if (storedConfig !== currentConfig) {
        localStorage.removeItem('countdownEndTime-{{ section.id }}');
        localStorage.setItem('countdownConfig-{{ section.id }}', currentConfig);
        return null;
      }

      var storedTime = localStorage.getItem('countdownEndTime-{{ section.id }}');
      return storedTime ? parseInt(storedTime) : null;
    }

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

    function calculateEndTime() {
      // Handle daily midnight reset
      if (resetDailyMidnight) {
        var now = new Date();
        var midnight = new Date(now);
        midnight.setHours(24, 0, 0, 0);
        return midnight.getTime();
      }

      // Existing auto-reset logic
      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 ($) {
        // jQuery version
        $(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 {
        // Vanilla JS version
        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) {
        // For daily midnight reset, always recalculate to ensure accuracy
        if (resetDailyMidnight) {
          targetDate = calculateEndTime();
        } else {
          targetDate = getStoredEndTime();
          if (!targetDate) {
            targetDate = calculateEndTime();
            setStoredEndTime(targetDate);
          }
        }
      } else {
        var dateString = "{{ section.settings.end_date }} {{ section.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)
      };
    }

    // For debugging
    window.debugCountdown = function() {
      console.log({
        autoResetEnabled: autoResetEnabled,
        resetDailyMidnight: resetDailyMidnight,
        resetDuration: resetDuration,
        storedEndTime: getStoredEndTime(),
        currentConfig: JSON.parse(currentConfig),
        storedConfig: localStorage.getItem('countdownConfig-{{ section.id }}'),
        currentTimeLeft: calculateTimeLeft()
      });
    };

    // Initial calculation
    updateDisplay(calculateTimeLeft());

    // Update every second
    var intervalId = setInterval(function() {
      var timeLeft = calculateTimeLeft();
      updateDisplay(timeLeft);
    }, 1000);

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

{% if section.settings.enablestickycountdownbar %}
  <style>
    .countdown-bar-section {
        position: sticky !important;
        top: var(--sticky-top-offset, 0px);
        z-index: 4;
    }

    /* Lower z-index when mobile menu is active */
    body.menu-open .countdown-bar-section,
    html.menu-open .countdown-bar-section {
        z-index: 1;
    }
  </style>
{% endif %}

{% schema %}
{
  "name": "Countdown Bar",
  "disabled_on": {
    "groups": ["footer"]
  },
  "class": "countdown-bar-section",
  "settings": [
    {
      "type": "checkbox",
      "id": "enablestickycountdownbar",
      "label": "Enable sticky countdown bar",
      "default": false
    },
    {
      "type": "select",
      "id": "design_style",
      "label": "Timer design style",
      "options": [
        {
          "value": "default",
          "label": "Default (boxed cells)"
        },
        {
          "value": "compact",
          "label": "Compact (inline pill boxes)"
        },
        {
          "value": "pill",
          "label": "Pill (all units in one pill)"
        }
      ],
      "default": "default"
    },
    {
      "type": "range",
      "id": "pill_border_radius",
      "label": "Pill border radius",
      "min": 0,
      "max": 60,
      "step": 2,
      "unit": "px",
      "default": 40,
      "visible_if": "{{ section.settings.design_style == 'pill' }}"
    },
    {
      "type": "header",
      "content": "Section Colors"
    },
    {
      "type": "color",
      "id": "bg_color",
      "label": "Background color",
      "default": "#000",
      "info": "Only used when animated gradient is disabled"
    },
    {
      "type": "color",
      "id": "text_color",
      "label": "Text color",
      "default": "#fff"
    },
    {
      "type": "color",
      "id": "time_bg_color",
      "label": "Time background color",
      "default": "#fff"
    },
    {
      "type": "color",
      "id": "time_text_color",
      "label": "Time text color",
      "default": "#000"
    },
    {
      "type": "header",
      "content": "Animated gradient background"
    },
    {
      "type": "checkbox",
      "id": "animated_gradient_enabled",
      "label": "Enable animated gradient background",
      "default": false
    },
    {
      "type": "color",
      "id": "gradient_color_1",
      "label": "Gradient Color 1",
      "default": "#3D348B",
      "info": "Only used when animated gradient is enabled"
    },
    {
      "type": "color",
      "id": "gradient_color_2",
      "label": "Gradient Color 2",
      "default": "#3D348B",
      "info": "Only used when animated gradient is enabled"
    },
    {
      "type": "color",
      "id": "gradient_color_3",
      "label": "Gradient Color 3",
      "default": "#9E388B",
      "info": "Only used when animated gradient is enabled"
    },
    {
      "type": "color",
      "id": "gradient_color_4",
      "label": "Gradient Color 4",
      "default": "#DF4F79",
      "info": "Only used when animated gradient is enabled"
    },
    {
      "type": "header",
      "content": "Content"
    },
    {
      "type": "richtext",
      "id": "text",
      "label": "Title text",
      "default": "<p><strong>FLASH SALE ENDS SOON</strong></p>"
    },
    {
      "type": "richtext",
      "id": "subtext",
      "label": "Subtitle text",
      "info": "Optional secondary line below the title"
    },
    {
      "type": "select",
      "id": "text_alignment",
      "label": "Text alignment (Mobile only)",
      "options": [
        {
          "value": "inline",
          "label": "Inline with countdown (default)"
        },
        {
          "value": "top_center",
          "label": "Above countdown (centered)"
        }
      ],
      "default": "inline",
      "info": "Choose how to position the text relative to the countdown timer on mobile devices"
    },
    {
      "type": "header",
      "content": "Font Sizes"
    },
    {
      "type": "range",
      "id": "text_font_size",
      "label": "Title font size (mobile)",
      "min": 10,
      "max": 28,
      "step": 1,
      "unit": "px",
      "default": 14
    },
    {
      "type": "range",
      "id": "text_font_size_desktop",
      "label": "Title font size (desktop)",
      "min": 10,
      "max": 32,
      "step": 1,
      "unit": "px",
      "default": 16
    },
    {
      "type": "range",
      "id": "subtext_font_size",
      "label": "Subtitle font size (mobile)",
      "min": 8,
      "max": 24,
      "step": 1,
      "unit": "px",
      "default": 12
    },
    {
      "type": "range",
      "id": "subtext_font_size_desktop",
      "label": "Subtitle font size (desktop)",
      "min": 8,
      "max": 28,
      "step": 1,
      "unit": "px",
      "default": 14
    },
    {
      "type": "header",
      "content": "Timer Settings"
    },
    {
      "type": "checkbox",
      "id": "auto_reset_enabled",
      "label": "Enable Auto Reset",
      "default": false,
      "info": "When enabled, the timer will automatically reset after completion"
    },
    {
      "type": "range",
      "id": "reset_days",
      "label": "Days",
      "min": 0,
      "max": 31,
      "step": 1,
      "default": 0,
      "info": "Number of days for the timer (when auto-reset is enabled)"
    },
    {
      "type": "range",
      "id": "reset_hours",
      "label": "Hours",
      "min": 0,
      "max": 23,
      "step": 1,
      "default": 12,
      "info": "Number of hours for the timer (when auto-reset is enabled)"
    },
    {
      "type": "range",
      "id": "reset_minutes",
      "label": "Minutes",
      "min": 0,
      "max": 59,
      "step": 1,
      "default": 0,
      "info": "Number of minutes for the timer (when auto-reset is enabled)"
    },
    {
      "type": "checkbox",
      "id": "reset_daily_midnight",
      "label": "Reset daily at midnight",
      "default": false,
      "info": "When enabled, timer resets every day at midnight in visitors local timezone"
    },
    {
      "type": "text",
      "id": "end_date",
      "label": "End Date (Traditional Countdown)",
      "default": "2024-09-30",
      "info": "Format: yyyy-mm-dd - Example: 2024-09-30"
    },
    {
      "type": "text",
      "id": "end_time",
      "label": "End Time (Traditional Countdown)",
      "default": "12:00",
      "info": "Format: hh:mm - Example: 12:00"
    },
    {
      "type": "header",
      "content": "Timer text"
    },
    {
      "type": "text",
      "id": "daystext",
      "label": "Days text",
      "default": "DAYS"
    },
    {
      "type": "text",
      "id": "hourstext",
      "label": "Hours text",
      "default": "HOURS"
    },
    {
      "type": "text",
      "id": "minstext",
      "label": "Mins text",
      "default": "MIN"
    },
    {
      "type": "text",
      "id": "sectext",
      "label": "Sec text",
      "default": "SEC"
    },
    {
      "type": "header",
      "content": "Visibility",
      "info": "Use this if you want to display/hide this section on certain product or normal page(s)."
    },
    {
      "type": "text",
      "id": "hidden_products",
      "label": "Product pages to hide the section on",
      "info": "Handles of products to hide the section on, split with a comma."
    },
    {
      "type": "text",
      "id": "hidden_pages",
      "label": "Normal pages to hide the section on",
      "info": "Handles of pages to hide the section on, split with a comma."
    },
    {
      "type": "checkbox",
      "id": "enable_specific_display",
      "label": "Display the section on specific product pages only",
      "default": false
    },
    {
      "type": "text",
      "id": "displayed_products",
      "label": "Specific product pages to display the section on",
      "info": "Applied if the checkbox above is checked. Handles of products to only display the section on, split with a comma."
    },
    {
      "type": "checkbox",
      "id": "enable_specific_page_display",
      "label": "Display the section on specific normal pages only",
      "default": false
    },
    {
      "type": "text",
      "id": "displayed_pages",
      "label": "Specific normal pages to display the section on",
      "info": "Applied if the checkbox above is checked. Handles of pages to only display the section on, split with a comma."
    }
  ],
  "presets": [
    {
      "name": "Countdown Bar",
      "category": "Announcement"
    }
  ]
}
{% endschema %}
