Dawn Cart Drawer Not Executing Script When Items First Added To Cart

My Shopify store only uses a Dawn cart drawer for cart, and I wanted to add a delivery estimator and scheduler based on rules - not using any API connections. The idea is at the bottom it would say “Est. Delivery:” Then a radio button for ASAP or Schedule Delivery. With Scheduled Delivery, the user can select a target delivery date. Either radio button option gives a 2-day range for estimated delivery.

I’ve got intermediate Javascript skills but vibe coded a version that initially seemed to work great, but upon testing further I noticed that it doesn’t work if the cart drawer is closed and an item is added to the cart. It will update and load properly with any other cart update while the drawer is open, or after the page is manually refreshed.

The script simply doesn’t execute on that first add to cart. The “Est. Delivery: ASAP” and “Schedule Delivery” text is all there, but the delivery estimates don’t display and the scheduler doesn’t pop up when the user selects to schedule delivery. Console logs show no activity.

I’m telling my cart drawer to render cart-delivery-options.liquid, but I’ve tried putting all of the code directly in the cart drawer in the spot it renders, and that still doesn’t fix it.

I’ve searched Google and ran it through every coding AI, and none of them can figure out why this won’t load on that first add to cart that opens the drawer. I have had two other AIs completely rebuild it blindly, and each version has the same issue. I’m stuck. I’d appreciate it if anybody could please help. Here’s my cart-delivery-options.liquid file.

{%- comment -%}
  Snippet for Delivery Date Options in Cart Drawer (Compact Radio Version - Revised for Stability)
{%- endcomment -%}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr" defer="defer"></script>

<div id="CartDrawer-DeliveryOptionsContainer" style="padding: 5px 15px 2px 15px;">
  <div class="delivery-line-wrapper" style="display: flex; align-items: center; margin-bottom: 3px;">
    <span style="margin-right: 8px; font-size: 1.4rem; color: rgba(var(--color-foreground), 0.75); white-space: nowrap; flex-shrink: 0; width: 90px; line-height: 1.4;">Est. Delivery:</span>
    <div class="delivery-option-line" style="display: flex; align-items: center; min-height: initial;">
      <input type="radio" name="attributes[delivery_preference]" value="ASAP" id="DeliveryRadio-ASAP" style="margin-top: 0; margin-bottom: 0; margin-right: 4px; accent-color: rgb(var(--color-accent));" {% if cart.attributes.delivery_preference == 'ASAP' or cart.attributes.delivery_preference == blank %}checked{% endif %}>
      <label for="DeliveryRadio-ASAP" id="DeliveryLabel-ASAP" style="font-size: 1.3rem; cursor:pointer; line-height: 1.4;">ASAP (loading...)</label>
    </div>
  </div>

  <div class="delivery-line-wrapper" style="display: flex; align-items: center;">
    <span style="margin-right: 8px; font-size: 1.4rem; white-space: nowrap; flex-shrink: 0; width: 90px; visibility: hidden; line-height: 1.4;">Est. Delivery:</span>
    <div class="delivery-option-line" style="display: flex; align-items: center; min-height: initial;">
      <input type="radio" name="attributes[delivery_preference]" value="SCHEDULED" id="DeliveryRadio-Scheduled" style="margin-top: 0; margin-bottom: 0; margin-right: 4px; accent-color: rgb(var(--color-accent));" {% if cart.attributes.delivery_preference == 'SCHEDULED' %}checked{% endif %}>
      <label for="DeliveryRadio-Scheduled" id="DeliveryLabel-ScheduledText" style="font-size: 1.3rem; cursor:pointer; line-height: 1.4; white-space: nowrap;">Schedule Delivery</label>
      <span id="DeliveryDate-ScheduledRangeDisplay" style="font-size: 1.3rem; margin-left: 5px; line-height: 1.4; white-space: nowrap;"></span>
      <button type="button" id="DeliveryDate-CalendarIconTrigger" aria-label="Open calendar" class="button button--tertiary" style="margin-left: 5px; padding: 0.3rem 0.4rem; min-width: auto; line-height: 0; color: #888888;">
        {%- render 'icon-calendar' -%}
      </button>
      <input type="text" id="DeliveryDate-CalendarInput" class="visually-hidden" name="attributes[delivery_date_selected]" value="{{ cart.attributes.delivery_date_selected }}" readonly="readonly">
    </div>
  </div>
</div>

<style>
@media (max-width: 480px) {
  #CartDrawer-DeliveryOptionsContainer .delivery-line-wrapper {
    flex-direction: column;
    align-items: flex-start;
  }

  #CartDrawer-DeliveryOptionsContainer .delivery-line-wrapper:first-child > span:first-child {
    display: block !important;
    width: 100% !important;
    text-align: left !important;
    margin-right: 0 !important;
    margin-left: 0 !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
    box-sizing: border-box !important;
    margin-bottom: 5px;
  }

  #CartDrawer-DeliveryOptionsContainer .delivery-line-wrapper > .delivery-option-line {
    width: 100%;
    margin-left: 0;
  }

  #CartDrawer-DeliveryOptionsContainer .delivery-line-wrapper:nth-child(2) > span:first-child {
    display: none !important;
  }
}
</style>

<script>
  function onFlatpickrReadyCDO(callback) {
    if (window.flatpickr) {
      callback();
    } else {
      let attempts = 0;
      const interval = setInterval(function() {
        attempts++;
        if (window.flatpickr || attempts > 60) {
          clearInterval(interval);
          if (window.flatpickr) {
            callback();
          } else {
            console.error("Flatpickr failed to load for Cart Delivery Options.");
          }
        }
      }, 100);
    }
  }

  onFlatpickrReadyCDO(function() {
    if (typeof window.CartDeliveryOptionsManager !== 'undefined' && window.CartDeliveryOptionsManager.flatpickrInstance) {
        window.CartDeliveryOptionsManager.flatpickrInstance.destroy();
        window.CartDeliveryOptionsManager.flatpickrInstance = null;
    }

    window.CartDeliveryOptionsManager = {
      ALL_HOLIDAYS: [],
      flatpickrInstance: null,
      elements: {},
      debounceTimeout: null,
      listenersAttachedTo: null,
      _boundHandleContainerChange: null,
      _boundHandleContainerClick: null,
      lastUserInteractionTime: 0,

      formatDateYMD: function(date) { const y = date.getUTCFullYear(); const m = String(date.getUTCMonth() + 1).padStart(2, '0'); const d = String(date.getUTCDate()).padStart(2, '0'); return `${y}-${m}-${d}`; },
      parseDateYMD: function(dateString) { if (!dateString || !/^\d{4}-\d{2}-\d{2}$/.test(dateString)) return null; const parts = dateString.split('-'); return new Date(Date.UTC(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]))); },
      getNthDayOfMonth: function(year, month, dayOfWeek, occurrence) { const date = new Date(Date.UTC(year, month, 1)); let count = 0; let foundDate = null; while (date.getUTCMonth() === month) { if (date.getUTCDay() === dayOfWeek) { count++; if (count === occurrence) { foundDate = new Date(date.getTime()); break; } } date.setUTCDate(date.getUTCDate() + 1); } return foundDate ? window.CartDeliveryOptionsManager.formatDateYMD(foundDate) : null; },
      getLastDayOfMonth: function(year, month, dayOfWeek) { const date = new Date(Date.UTC(year, month + 1, 0)); while (date.getUTCDay() !== dayOfWeek) { date.setUTCDate(date.getUTCDate() - 1); } return window.CartDeliveryOptionsManager.formatDateYMD(new Date(date.getTime())); },
      getFederalHolidaysForRange: function() { const currentYear = new Date().getFullYear(); let holidaysRaw = []; [currentYear, currentYear + 1].forEach(year => { holidaysRaw.push( `${year}-01-01`, `${year}-06-19`, `${year}-07-04`, `${year}-11-11`, `${year}-12-25`, this.getNthDayOfMonth(year, 0, 1, 3), this.getNthDayOfMonth(year, 1, 1, 3), this.getLastDayOfMonth(year, 4, 1), this.getNthDayOfMonth(year, 8, 1, 1), this.getNthDayOfMonth(year, 9, 1, 2), this.getNthDayOfMonth(year, 10, 4, 4) ); }); const uniqueHolidayTimes = {}; this.ALL_HOLIDAYS = holidaysRaw.filter(dStr => dStr !== null) .map(dStr => this.parseDateYMD(dStr)) .filter(dObj => { if (!dObj) return false; const time = dObj.getTime(); if (uniqueHolidayTimes[time]) return false; uniqueHolidayTimes[time] = true; return true; }); },
      getCurrentPacificTime: function() { const now = new Date(); try { const formatter = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); const parts = formatter.formatToParts(now); const ptValues = {}; parts.forEach(part => { ptValues[part.type] = part.value; }); return new Date( parseInt(ptValues.year), parseInt(ptValues.month) - 1, parseInt(ptValues.day), parseInt(ptValues.hour), parseInt(ptValues.minute), parseInt(ptValues.second) ); } catch (e) { return now; } },
            

      
      isDateHoliday: function(dateToCheck) {
          return this.ALL_HOLIDAYS.some(h => h.getTime() === dateToCheck.getTime());
      },

      isOneOfTheTwoDaysFollowingHoliday: function(dateToCheck) {
          const checkTime = dateToCheck.getTime();
          for (let i = 0; i < this.ALL_HOLIDAYS.length; i++) {
              const holiday = this.ALL_HOLIDAYS[i];
              const holidayBaseTime = holiday.getTime();
        
              const holidayPlus1 = new Date(holidayBaseTime);
              holidayPlus1.setUTCDate(holidayPlus1.getUTCDate() + 1);
              if (checkTime === holidayPlus1.getTime()) return true;
              
              const holidayPlus2 = new Date(holidayBaseTime);
              holidayPlus2.setUTCDate(holidayPlus2.getUTCDate() + 2);
              if (checkTime === holidayPlus2.getTime()) return true;
          }
          return false;
      },

      isDeliveryBlackout: function(date) {
        const dateToReallyCheck = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
      
        const dayOfWeek = dateToReallyCheck.getUTCDay();
        if (dayOfWeek === 0 || dayOfWeek === 1 || dayOfWeek === 2) { 
            return true;
        }
      
        if (this.isDateHoliday(dateToReallyCheck)) {
            return true;
        }
      
        if (this.isOneOfTheTwoDaysFollowingHoliday(dateToReallyCheck)) {
            return true;
        }
        
        return false;
      },

      getNextShippingDate: function(fromDatePT = null) {
        const nowPT = fromDatePT || this.getCurrentPacificTime();
        let currentDayPT = nowPT.getUTCDay(); // Use getUTCDay as nowPT is already effectively PT
        let currentHourPT = nowPT.getUTCHours(); // Use getUTCHours

        let nextShipDate = new Date(Date.UTC(nowPT.getUTCFullYear(), nowPT.getUTCMonth(), nowPT.getUTCDate()));

        if (currentDayPT >= 1 && currentDayPT <= 3) { // Monday to Wednesday
            if (currentHourPT >= 15) { // After 3 PM
                nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 1); // Ship next day
            }
            // If before 3 PM, ships same day (no change to nextShipDate needed)
        } else if (currentDayPT === 4) { // Thursday
            if (currentHourPT >= 15) { // After 3 PM
                nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 3); // Ship next Monday (Fri, Sat, Sun)
            }
            // If before 3 PM, ships same day (Thursday)
        } else { // Friday (5), Saturday (6), Sunday (0)
            if (currentDayPT === 5) nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 3); // Fri -> Mon
            if (currentDayPT === 6) nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 2); // Sat -> Mon
            if (currentDayPT === 0) nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 1); // Sun -> Mon
        }
        
        // Ensure the calculated nextShipDate is a shipping day (Mon-Thu) and not a holiday
        // This loop is mostly for holidays falling on Mon-Thu
        while (nextShipDate.getUTCDay() < 1 || nextShipDate.getUTCDay() > 4 || this.isDateHoliday(nextShipDate)) {
            nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 1);
            // If it rolls over to Friday, jump to next Monday
            if (nextShipDate.getUTCDay() === 5) nextShipDate.setUTCDate(nextShipDate.getUTCDate() + 3);
        }
        return nextShipDate;
      },

      getEarliestSchedulableDeliveryDate: function() {
        const nowPT = this.getCurrentPacificTime();
        let earliestDelivery = new Date(Date.UTC(nowPT.getUTCFullYear(), nowPT.getUTCMonth(), nowPT.getUTCDate()));
        
        earliestDelivery.setUTCDate(earliestDelivery.getUTCDate() + 3);
      
        while (this.isDeliveryBlackout(earliestDelivery)) {
            earliestDelivery.setUTCDate(earliestDelivery.getUTCDate() + 1);
        }
        return earliestDelivery;
      },

      getASAPDateRangeText: function() {
        const nowPT = this.getCurrentPacificTime();
        const orderDate = new Date(Date.UTC(nowPT.getUTCFullYear(), nowPT.getUTCMonth(), nowPT.getUTCDate()));
        const dayOfWeekPT = nowPT.getUTCDay(); // 0=Sun, 1=Mon, ..., 6=Sat
        const hourPT = nowPT.getUTCHours(); // 0-23 in PT (effectively)
      
        let asapStartCandidate, asapEndCandidate;
      
        if (dayOfWeekPT >= 1 && dayOfWeekPT <= 3) { // Monday, Tuesday, Wednesday
          if (hourPT < 11) {
            asapStartCandidate = new Date(orderDate.getTime());
            asapStartCandidate.setUTCDate(orderDate.getUTCDate() + 1);
            asapEndCandidate = new Date(orderDate.getTime());
            asapEndCandidate.setUTCDate(orderDate.getUTCDate() + 2);
          } else {
            asapStartCandidate = new Date(orderDate.getTime());
            asapStartCandidate.setUTCDate(orderDate.getUTCDate() + 2);
            asapEndCandidate = new Date(orderDate.getTime());
            asapEndCandidate.setUTCDate(orderDate.getUTCDate() + 3);
          }
        } else if (dayOfWeekPT === 4) { // Thursday
          if (hourPT < 11) {
            asapStartCandidate = new Date(orderDate.getTime());
            asapStartCandidate.setUTCDate(orderDate.getUTCDate() + 1);
            asapEndCandidate = new Date(orderDate.getTime());
            asapEndCandidate.setUTCDate(orderDate.getUTCDate() + 2);
          } else { // Thursday 11 AM or after
            asapStartCandidate = new Date(orderDate.getTime());
            let daysUntilNextTuesday = (2 - orderDate.getUTCDay() + 7) % 7;
            if (daysUntilNextTuesday === 0) daysUntilNextTuesday = 7; 
            asapStartCandidate.setUTCDate(orderDate.getUTCDate() + daysUntilNextTuesday);
      
            asapEndCandidate = new Date(asapStartCandidate.getTime());
            asapEndCandidate.setUTCDate(asapStartCandidate.getUTCDate() + 1); // Wednesday
          }
        } else { // Friday (5), Saturday (6), Sunday (0)
          asapStartCandidate = new Date(orderDate.getTime());
          let daysUntilNextTuesday = (2 - orderDate.getUTCDay() + 7) % 7;
          asapStartCandidate.setUTCDate(orderDate.getUTCDate() + daysUntilNextTuesday);
      
          asapEndCandidate = new Date(asapStartCandidate.getTime());
          asapEndCandidate.setUTCDate(asapStartCandidate.getUTCDate() + 1); // Wednesday
        }
      
        let asapStart, asapEnd;
        if (this.isDateHoliday(asapStartCandidate) || this.isDateHoliday(asapEndCandidate)) {
          const nextAvailableScheduled = this.getEarliestSchedulableDeliveryDate();
          asapEnd = new Date(nextAvailableScheduled.getTime());
          asapStart = new Date(asapEnd.getTime());
          asapStart.setUTCDate(asapStart.getUTCDate() - 1);
        } else {
          asapStart = asapStartCandidate;
          asapEnd = asapEndCandidate;
        }
        
        const options = { month: 'short', day: 'numeric', timeZone: 'UTC' };
        const formattedStart = asapStart.toLocaleDateString('en-US', options);
        const formattedEnd = asapEnd.toLocaleDateString('en-US', options);
        return `${formattedStart} - ${formattedEnd}`;
      },

      getScheduledDateRangeText: function(selectedDate) {
        let dateObj = (typeof selectedDate === 'string') ? this.parseDateYMD(selectedDate) : selectedDate;
        if (!dateObj || isNaN(dateObj.getTime())) return "";
      
        const dayBeforeSelected = new Date(dateObj.getTime());
        dayBeforeSelected.setUTCDate(dayBeforeSelected.getUTCDate() - 1);
        
        const formatOptions = { month: 'short', day: 'numeric', timeZone: 'UTC' };
        
        const formattedDayBefore = new Date(Date.UTC(dayBeforeSelected.getUTCFullYear(), dayBeforeSelected.getUTCMonth(), dayBeforeSelected.getUTCDate()))
                                    .toLocaleDateString('en-US', formatOptions);
        const formattedSelected = new Date(Date.UTC(dateObj.getUTCFullYear(), dateObj.getUTCMonth(), dateObj.getUTCDate()))
                                    .toLocaleDateString('en-US', formatOptions);
      
        return `(${formattedDayBefore} - ${formattedSelected})`;
      },

      _updateCartAttributesOnServer: function(attributesToUpdate) {
        fetch('/cart/update.js', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
          body: JSON.stringify({ attributes: attributesToUpdate })
        })
        .then(response => response.json())
        .then(cartData => {
          if (typeof publish === 'function' && typeof PUB_SUB_EVENTS !== 'undefined') {
            publish(PUB_SUB_EVENTS.cartUpdate, { source: 'cart-delivery-options', cartData: cartData });
          } else {
            document.dispatchEvent(new CustomEvent('cart:updated', { bubbles: true, detail: { cart: cartData } }));
          }
        })
        .catch(error => console.error('CDO: Error updating cart attributes:', error));
      },

      queueAttributeUpdate: function(pref, dateVal) {
        clearTimeout(this.debounceTimeout);
        const attributes = {
            'delivery_preference': pref,
            'delivery_date_selected': dateVal
        };
        this.debounceTimeout = setTimeout(() => {
          this._updateCartAttributesOnServer(attributes);
        }, 750);
      },

      handleRadioChange: function(event) {
        this.lastUserInteractionTime = Date.now();
        const preference = event.target.value;

        this.elements.asapRadio.checked = (preference === 'ASAP');
        this.elements.scheduledRadio.checked = (preference === 'SCHEDULED');

        if (preference === 'ASAP') {
          this.elements.calendarInput.value = '';
          if (this.flatpickrInstance) this.flatpickrInstance.clear();
          this.queueAttributeUpdate('ASAP', '');
        } else {
          if (this.flatpickrInstance) this.flatpickrInstance.open();
        }
        this.syncVisualState();
      },

      handleFlatpickrChange: function(selectedDates, dateStr) {
        this.lastUserInteractionTime = Date.now();

        if (selectedDates.length > 0) {
          this.elements.calendarInput.value = dateStr;
          this.elements.scheduledRadio.checked = true;
          this.elements.asapRadio.checked = false;
          this.queueAttributeUpdate('SCHEDULED', dateStr);
        } else {
          this.elements.calendarInput.value = '';
          this.elements.asapRadio.checked = true;
          this.elements.scheduledRadio.checked = false;
          this.queueAttributeUpdate('ASAP', '');
        }
        this.syncVisualState();
      },

      handleFlatpickrClose: function(selectedDates) {
          if (selectedDates.length === 0 && this.elements.scheduledRadio.checked && this.elements.calendarInput.value === '') {
              this.lastUserInteractionTime = Date.now();
              this.elements.asapRadio.checked = true;
              this.elements.scheduledRadio.checked = false;
          }
          this.syncVisualState();
      },

      syncVisualState: function() {
        if (!this.elements.asapRadio || !this.elements.asapLabel || !this.elements.scheduledRangeDisplay) return;

        const newAsapText = `ASAP (${this.getASAPDateRangeText()})`; // No param needed
        if (this.elements.asapLabel.textContent !== newAsapText) {
            this.elements.asapLabel.textContent = newAsapText;
        }

        let newScheduledText = '';
        if (this.elements.scheduledRadio.checked && this.elements.calendarInput.value) {
          newScheduledText = this.getScheduledDateRangeText(this.elements.calendarInput.value);
        }
        if (this.elements.scheduledRangeDisplay.textContent !== newScheduledText) {
          this.elements.scheduledRangeDisplay.textContent = newScheduledText;
        }
      },

      refreshUIFromSource: function(cart = null) {
        const timeSinceLastInteraction = Date.now() - this.lastUserInteractionTime;
        if (timeSinceLastInteraction < 1500) {
            return;
        }

        if (!this.elements.asapRadio) this.initDOMelements();
        let preference = 'ASAP';
        let selectedDate = '';

        if (cart && cart.attributes) {
            preference = cart.attributes.delivery_preference || 'ASAP';
            selectedDate = cart.attributes.delivery_date_selected || '';
        } else {
            if (document.getElementById('DeliveryRadio-ASAP')) {
                 preference = document.getElementById('DeliveryRadio-ASAP').checked ? 'ASAP' : 'SCHEDULED';
            }
            if (document.getElementById('DeliveryDate-CalendarInput')) {
                 selectedDate = document.getElementById('DeliveryDate-CalendarInput').value;
            }
        }

        if (preference === 'SCHEDULED' && !selectedDate) {
            preference = 'ASAP';
        }

        if (this.elements.asapRadio) this.elements.asapRadio.checked = (preference === 'ASAP');
        if (this.elements.scheduledRadio) this.elements.scheduledRadio.checked = (preference === 'SCHEDULED');
        if (this.elements.calendarInput) this.elements.calendarInput.value = (preference === 'SCHEDULED' ? selectedDate : '');

        if (this.flatpickrInstance) {
            this.flatpickrInstance.set('minDate', this.formatDateYMD(this.getEarliestSchedulableDeliveryDate()));
            this.flatpickrInstance.setDate(preference === 'SCHEDULED' ? selectedDate : '', false);
        }
        this.syncVisualState();
      },

      initDOMelements: function() {
        this.elements = {
          container: document.getElementById('CartDrawer-DeliveryOptionsContainer'),
          asapRadio: document.getElementById('DeliveryRadio-ASAP'),
          asapLabel: document.getElementById('DeliveryLabel-ASAP'),
          scheduledRadio: document.getElementById('DeliveryRadio-Scheduled'),
          scheduledLabelText: document.getElementById('DeliveryLabel-ScheduledText'),
          scheduledRangeDisplay: document.getElementById('DeliveryDate-ScheduledRangeDisplay'),
          calendarIconTrigger: document.getElementById('DeliveryDate-CalendarIconTrigger'),
          calendarInput: document.getElementById('DeliveryDate-CalendarInput')
        };
      },

      setup: function() {
        this.initDOMelements();
        if (!this.elements.container || !this.elements.asapRadio) return false;
        this.getFederalHolidaysForRange();

        if (!this.listenersAttachedTo || this.listenersAttachedTo !== this.elements.container) {
            if (this.listenersAttachedTo) {
                this.listenersAttachedTo.removeEventListener('change', this._boundHandleContainerChange);
                this.listenersAttachedTo.removeEventListener('click', this._boundHandleContainerClick);
            }
            this._boundHandleContainerChange = this._boundHandleContainerChange || this._handleContainerChange.bind(this);
            this._boundHandleContainerClick = this._boundHandleContainerClick || this._handleContainerClick.bind(this);
            if (this.elements.container) {
                this.elements.container.addEventListener('change', this._boundHandleContainerChange);
                this.elements.container.addEventListener('click', this._boundHandleContainerClick);
                this.listenersAttachedTo = this.elements.container;
            }
        }

        if (this.flatpickrInstance) {
            this.flatpickrInstance.destroy();
            this.flatpickrInstance = null;
        }
        if (this.elements.calendarInput && window.flatpickr) {
          this.flatpickrInstance = flatpickr(this.elements.calendarInput, {
            dateFormat: "Y-m-d",
            minDate: this.formatDateYMD(this.getEarliestSchedulableDeliveryDate()),
            disable: [(date) => this.isDeliveryBlackout(date)],
            onChange: this.handleFlatpickrChange.bind(this),
            onClose: this.handleFlatpickrClose.bind(this),
            clickOpens: false
          });
        }
        return true;
      },

      _handleContainerChange: function(event) {
        if (event.target.name === 'attributes[delivery_preference]') {
            this.handleRadioChange(event);
        }
      },
      _handleContainerClick: function(event) {
        const target = event.target;
        if (target === this.elements.asapRadio || target === this.elements.scheduledRadio) {
            return;
        }

        if (target === this.elements.asapLabel && this.elements.asapRadio && !this.elements.asapRadio.checked) {
            this.elements.asapRadio.click();
        } else if (target === this.elements.scheduledLabelText && this.elements.scheduledRadio) {
            if (!this.elements.scheduledRadio.checked) {
                this.elements.scheduledRadio.click();
            } else if (this.flatpickrInstance) {
                 this.flatpickrInstance.open();
            }
        } else if (target === this.elements.calendarIconTrigger && this.flatpickrInstance) {
            this.flatpickrInstance.open();
        }
      }
    };

    if (document.getElementById('CartDrawer-DeliveryOptionsContainer')) {
      if (window.CartDeliveryOptionsManager.setup()) {
          window.CartDeliveryOptionsManager.refreshUIFromSource();
      }
    }

    window.refreshCartDeliveryOptionsUI = (cartData = null, mainCartObserver = null, mainObserverTarget = null, observerOptions = null) => {
      if (window.CartDeliveryOptionsManager) {
        const manager = window.CartDeliveryOptionsManager;
        let observerWasConnected = false;
        if (mainCartObserver && mainObserverTarget) {
          try { mainCartObserver.disconnect(); observerWasConnected = true; } catch (e) { /* e */ }
        }
        if (manager.setup()) {
            manager.refreshUIFromSource(cartData);
        }
        if (observerWasConnected && mainCartObserver && mainObserverTarget && observerOptions) {
          try { mainCartObserver.observe(mainObserverTarget, observerOptions); } catch (e) { /* e */ }
        }
      }
    };
  });
</script>