(function(){
  'use strict';

  // Guard: localized data must exist and feature must be enabled.
  if (typeof window.foodord_ttd !== 'object' || !window.foodord_ttd.enabled) {
    return;
  }

  const cfg = window.foodord_ttd;
  let mounted = false;
  const dropdownChevron = '<svg viewBox="0 0 20 20" focusable="false" aria-hidden="true"><path d="M6 8l4 4 4-4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"/></svg>';
  function markMounted(select) {
    if (!select) {
      mounted = false;
      return;
    }
    select.dataset.foodordTtdMounted = '1';
    mounted = true;
  }

  function sendSelection(time) {
    try {
      if (!cfg.ajaxUrl || !cfg.nonce) return;
      const body = new URLSearchParams();
      body.set('action', 'foodord_set_delivery_time');
      body.set('nonce', cfg.nonce);
      body.set('time', String(time || ''));
      fetch(cfg.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body: body.toString()
      }).catch(function(){ /* silent */ });
    } catch (err) { void err; }
  }

  function sendDate(date) {
    try {
      if (!cfg.ajaxUrl || !cfg.nonceDate) return;
      const body = new URLSearchParams();
      body.set('action', 'foodord_set_delivery_date');
      body.set('nonce', cfg.nonceDate);
      body.set('date', String(date || ''));
      fetch(cfg.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body: body.toString()
      }).catch(function(){ /* silent */ });
    } catch (err) { void err; }
  }

  function fetchSlots(date) {
    try {
      if (!cfg.ajaxUrl || !cfg.nonceSlots) {
        return Promise.resolve(null);
      }
      const body = new URLSearchParams();
      body.set('action', 'foodord_get_delivery_slots');
      body.set('nonce', cfg.nonceSlots);
      body.set('date', String(date || ''));
      return fetch(cfg.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body: body.toString()
      })
        .then(function(r){
          if (!r || !r.ok) return null;
          return r.json();
        })
        .then(function(json){
          if (!json || !json.success || !json.data) return null;
          return json.data;
        })
        .catch(function(){ return null; });
    } catch (err) {
      void err;
      return Promise.resolve(null);
    }
  }

  function isScheduledEnabled() {
    return Boolean(cfg.scheduledDateEnabled);
  }

  function isValidDateString(value) {
    return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);
  }

  function getMinDate() {
    return isValidDateString(cfg.scheduledDateMin) ? cfg.scheduledDateMin : '';
  }

  function getMaxDate() {
    return isValidDateString(cfg.scheduledDateMax) ? cfg.scheduledDateMax : '';
  }

  function isDateInRange(date) {
    if (!isValidDateString(date)) return false;
    const min = getMinDate();
    const max = getMaxDate();
    if (!min || !max) return false;
    return (date >= min && date <= max);
  }

  function isToday(date) {
    const min = getMinDate();
    if (!min) return true;
    return !date || date === min;
  }

  function getScheduledDateOptions() {
    const options = Array.isArray(cfg.scheduledDateOptions) ? cfg.scheduledDateOptions : [];
    return options.filter(function(item){
      return item && typeof item.value === 'string' && isValidDateString(item.value);
    });
  }

  function populateDateSelect(select) {
    if (!select) {
      return;
    }

    const todayLabel = (cfg.labels && cfg.labels.today) || 'Today';
    const options = getScheduledDateOptions();

    select.innerHTML = '';

    if (options.length > 0) {
      for (const item of options) {
        const value = String(item.value || '');
        if (!isValidDateString(value)) {
          continue;
        }

        const opt = document.createElement('option');
        opt.value = value;

        const baseLabel = (item && typeof item.label === 'string' && item.label)
          ? item.label
          : value;

        const isTodayItem = Boolean(item && item.isToday) || value === getMinDate();
        opt.textContent = isTodayItem ? todayLabel : baseLabel;
        select.appendChild(opt);
      }
    }

    if (select.options.length === 0) {
      const min = getMinDate();
      const max = getMaxDate();
      if (min && max && min <= max) {
        const opt = document.createElement('option');
        opt.value = min;
        opt.textContent = todayLabel;
        select.appendChild(opt);
      }
    }

    const initial = isValidDateString(cfg.scheduledDate)
      ? cfg.scheduledDate
      : (select.options[0] ? select.options[0].value : '');

    if (initial) {
      select.value = initial;
    }

    syncCustomDropdown(select);
  }

  function populateTimeSelect(select, state) {
    if (!select) {
      return;
    }

    const options = Array.isArray(state && state.options) ? state.options : [];
    const today = Boolean(state && state.isToday);
    const allowAsap = today && Boolean(state && state.allowAsap);
    const preorderAvailable = today && Boolean(state && state.preorderOpen);

    const canShowSlots = isScheduledEnabled() && !today
      ? options.length > 0
      : (allowAsap || (preorderAvailable && options.length > 0));

    select.innerHTML = '';

    if (!canShowSlots || (state && state.invalidDate)) {
      const opt = document.createElement('option');
      opt.value = '';
      opt.disabled = true;
      opt.selected = true;

      if (state && state.invalidDate) {
        opt.textContent = (cfg.labels && cfg.labels.invalidDate) || 'Please select a valid date.';
      } else if (!today) {
        opt.textContent = (cfg.labels && cfg.labels.noSlots) || 'No time slots available for selected date.';
      } else {
        opt.textContent = (cfg.labels && cfg.labels.closed) || 'Restaurant is currently closed.';
      }

      select.appendChild(opt);
      select.disabled = true;
      sendSelection('');
      setCheckoutButtonsDisabled(true);
      syncCustomDropdown(select);
      return;
    }

    select.disabled = false;

    if (allowAsap) {
      const asap = document.createElement('option');
      asap.value = 'ASAP';
      asap.textContent = (cfg.labels && cfg.labels.asap) || 'As soon as possible';
      select.appendChild(asap);
    }

    for (const t of options) {
      const opt = document.createElement('option');
      opt.value = t;
      opt.textContent = t;
      select.appendChild(opt);
    }

    if (allowAsap) {
      select.value = 'ASAP';
      sendSelection('ASAP');
    } else if (options.length > 0) {
      select.value = options[0];
      sendSelection(select.value);
    } else {
      sendSelection('');
    }

    setCheckoutButtonsDisabled(false);
    syncCustomDropdown(select);
  }

  function setCheckoutButtonsDisabled(disabled) {
    const selectors = [
      '.wc-block-components-checkout-place-order-button',
      '.wc-block-components-button.wc-block-components-checkout-place-order-button',
      '#place_order',
      '.foodord-mobile-cart__bottom-checkout-btn',
      '.foodord-mobile-cart__checkout-btn'
    ];

    selectors.forEach(function(selector){
      document.querySelectorAll(selector).forEach(function(button){
        if (disabled) {
          if (!button.dataset.foodordTtdOrigDisabled) {
            button.dataset.foodordTtdOrigDisabled = button.disabled ? '1' : '0';
          }
          if (!button.dataset.foodordTtdAria) {
            const aria = button.getAttribute('aria-disabled');
            button.dataset.foodordTtdAria = aria !== null ? aria : 'none';
          }
          button.disabled = true;
          button.setAttribute('aria-disabled', 'true');
          button.classList.add('foodord-ttd-checkout-disabled');
          button.dataset.foodordTtdDisabled = '1';
        } else if (button.dataset.foodordTtdDisabled === '1') {
          if (button.dataset.foodordTtdOrigDisabled === '0') {
            button.disabled = false;
          }
          const storedAria = button.dataset.foodordTtdAria;
          if (storedAria === 'none') {
            button.removeAttribute('aria-disabled');
          } else if (storedAria) {
            button.setAttribute('aria-disabled', storedAria);
          }
          button.classList.remove('foodord-ttd-checkout-disabled');
          delete button.dataset.foodordTtdOrigDisabled;
          delete button.dataset.foodordTtdAria;
          delete button.dataset.foodordTtdDisabled;
        }
      });
    });
  }

  function closeCustomDropdowns(exceptSelect) {
    document.querySelectorAll('.foodord-ttd__dropdown.is-open').forEach(function(dropdown){
      const ownerSelect = dropdown.parentNode ? dropdown.parentNode.querySelector('.foodord-ttd__native-select') : null;

      if (exceptSelect && ownerSelect === exceptSelect) {
        return;
      }

      dropdown.classList.remove('is-open');

      const trigger = dropdown.querySelector('.foodord-ttd__trigger');
      if (trigger) {
        trigger.setAttribute('aria-expanded', 'false');
      }
    });
  }

  function syncCustomDropdown(select) {
    if (!select || !select.parentNode) {
      return;
    }

    let dropdown = select.parentNode.querySelector('.foodord-ttd__dropdown');

    if (!dropdown) {
      dropdown = document.createElement('div');
      dropdown.className = 'foodord-ttd__dropdown';

      const trigger = document.createElement('button');
      trigger.type = 'button';
      trigger.className = 'foodord-ttd__trigger';
      trigger.setAttribute('aria-haspopup', 'listbox');
      trigger.setAttribute('aria-expanded', 'false');

      const triggerLabel = document.createElement('span');
      triggerLabel.className = 'foodord-ttd__trigger-label';

      const triggerIcon = document.createElement('span');
      triggerIcon.className = 'foodord-ttd__trigger-icon';
      triggerIcon.innerHTML = dropdownChevron;

      const menu = document.createElement('div');
      menu.className = 'foodord-ttd__menu';
      menu.setAttribute('role', 'listbox');

      trigger.appendChild(triggerLabel);
      trigger.appendChild(triggerIcon);
      dropdown.appendChild(trigger);
      dropdown.appendChild(menu);
      select.parentNode.appendChild(dropdown);
      select.classList.add('foodord-ttd__native-select');

      trigger.addEventListener('click', function(){
        if (trigger.disabled) {
          return;
        }

        const isOpen = dropdown.classList.contains('is-open');
        closeCustomDropdowns(select);
        dropdown.classList.toggle('is-open', !isOpen);
        trigger.setAttribute('aria-expanded', !isOpen ? 'true' : 'false');
      }, { once: false });
    }

    const trigger = dropdown.querySelector('.foodord-ttd__trigger');
    const triggerLabel = dropdown.querySelector('.foodord-ttd__trigger-label');
    const menu = dropdown.querySelector('.foodord-ttd__menu');
    const options = Array.from(select.options || []);
    const selectedOption = select.selectedIndex >= 0 ? select.options[select.selectedIndex] : options[0];
    let interactiveOptionCount = 0;

    if (triggerLabel) {
      triggerLabel.textContent = selectedOption ? selectedOption.textContent : '';
    }

    if (menu) {
      menu.innerHTML = '';

      options.forEach(function(option, index){
        const item = document.createElement('button');
        item.type = 'button';
        item.className = 'foodord-ttd__option';
        item.setAttribute('role', 'option');
        item.textContent = option.textContent || '';

        if (option.selected) {
          item.classList.add('is-selected');
          item.setAttribute('aria-selected', 'true');
        } else {
          item.setAttribute('aria-selected', 'false');
        }

        if (option.disabled) {
          item.disabled = true;
        } else {
          interactiveOptionCount += 1;
        }

        item.addEventListener('click', function(){
          if (option.disabled) {
            return;
          }

          select.selectedIndex = index;
          select.value = option.value;
          select.dispatchEvent(new Event('change', { bubbles: true }));
          syncCustomDropdown(select);
          closeCustomDropdowns();
        }, { once: false });

        menu.appendChild(item);
      });
    }

    if (trigger) {
      const shouldDisableTrigger = select.disabled || interactiveOptionCount <= 1;
      trigger.disabled = shouldDisableTrigger;
      dropdown.classList.toggle('is-disabled', shouldDisableTrigger);

      if (shouldDisableTrigger) {
        dropdown.classList.remove('is-open');
        trigger.setAttribute('aria-expanded', 'false');
      }
    }
  }

  // Build the dropdown element from localized options.
  function buildDropdown() {
    const wrap = document.createElement('div');
    wrap.className = 'foodord-ttd';

    let dateGroup = null;
    let dateSelect = null;
    if (isScheduledEnabled()) {
      dateGroup = document.createElement('div');
      dateGroup.className = 'foodord-ttd__label-group';

      const dateLabel = document.createElement('label');
      dateLabel.className = 'foodord-ttd__label';
      dateLabel.setAttribute('for', 'foodord-ttd-date');
      dateLabel.textContent = (cfg.labels && cfg.labels.dateLabel) || 'Delivery date';

      dateSelect = document.createElement('select');
      dateSelect.className = 'foodord-ttd__date';
      dateSelect.id = 'foodord-ttd-date';
      dateSelect.name = 'foodord_delivery_date';

      dateGroup.appendChild(dateLabel);
      dateGroup.appendChild(dateSelect);
      wrap.appendChild(dateGroup);

      populateDateSelect(dateSelect);
    }

    const timeGroup = document.createElement('div');
    timeGroup.className = 'foodord-ttd__label-group';

    const label = document.createElement('label');
    label.className = 'foodord-ttd__label';
    label.setAttribute('for', 'foodord-ttd-select');
    label.textContent = (cfg.labels && cfg.labels.label) || 'Delivery time';

    const select = document.createElement('select');
    select.className = 'foodord-ttd__select';
    select.id = 'foodord-ttd-select';
    select.name = 'foodord_delivery_time';

    timeGroup.appendChild(label);
    timeGroup.appendChild(select);
    wrap.appendChild(timeGroup);

    const currentDate = dateSelect ? (dateSelect.value || '') : '';
    populateTimeSelect(select, {
      isToday: isToday(currentDate),
      options: Array.isArray(cfg.options) ? cfg.options : [],
      allowAsap: Boolean(cfg.allowAsap),
      preorderOpen: Boolean(cfg.preorderOpen)
    });

    // send session update on change
    select.addEventListener('change', function(){
      sendSelection(select.value || '');
    }, { once: false });

    if (dateSelect) {
      sendDate(dateSelect.value || '');
      dateSelect.addEventListener('change', function(){
        const value = String(dateSelect.value || '');

        if (!isDateInRange(value)) {
          sendDate('');
          populateTimeSelect(select, { isToday: true, options: [], allowAsap: false, preorderOpen: false, invalidDate: true });
          return;
        }

        sendDate(value);
        select.disabled = true;
        setCheckoutButtonsDisabled(true);

        fetchSlots(value).then(function(data){
          if (!data) {
            populateTimeSelect(select, { isToday: isToday(value), options: [], allowAsap: false, preorderOpen: false });
            return;
          }

          cfg.options = Array.isArray(data.options) ? data.options : [];
          cfg.allowAsap = Boolean(data.allowAsap);
          cfg.preorderOpen = Boolean(data.preorderOpen);
          cfg.preorderEnabled = Boolean(data.preorderEnabled);
          cfg.isOpen = Boolean(data.isOpen);
          cfg.scheduledDate = value;

          populateTimeSelect(select, {
            isToday: Boolean(data.isToday),
            options: cfg.options,
            allowAsap: cfg.allowAsap,
            preorderOpen: cfg.preorderOpen
          });
        });
      }, { once: false });
    }
    return wrap;
  }

  // Insert into Blocks checkout form at the very top.
  function insertIntoBlocks() {
    // .wc-block-checkout__form exists for blocks checkout
    const form = document.querySelector('.wc-block-checkout__form');
    if (!form) return false;

    // Avoid duplicates
    if (form.querySelector('#foodord-ttd-select')) return true;

    const dropdown = buildDropdown();
    form.insertBefore(dropdown, form.firstChild);
    markMounted(dropdown.querySelector('#foodord-ttd-select'));
    return true;
  }

  // Hydrate classic slot (rendered via PHP) if present.
  function hydrateClassicSlot() {
    const container = document.getElementById('foodord-ttd');
    if (!container) return false;

    const select = container.querySelector('#foodord-ttd-select');
    if (!select) return false;

    const dateInput = container.querySelector('#foodord-ttd-date');
    if (dateInput && dateInput.options && dateInput.options.length === 0) {
      populateDateSelect(dateInput);
    }

    // Avoid duplicate binding
    if (!select.dataset.foodordTtdBound) {
      select.addEventListener('change', function(){
        sendSelection(select.value || '');
      }, { once: false });
      select.dataset.foodordTtdBound = '1';
    }

    if (dateInput && !dateInput.dataset.foodordTtdDateBound) {
      dateInput.addEventListener('change', function(){
        const value = String(dateInput.value || '');

        if (!isDateInRange(value)) {
          sendDate('');
          populateTimeSelect(select, { isToday: true, options: [], allowAsap: false, preorderOpen: false, invalidDate: true });
          return;
        }

        sendDate(value);
        select.disabled = true;
        setCheckoutButtonsDisabled(true);

        fetchSlots(value).then(function(data){
          if (!data) {
            populateTimeSelect(select, { isToday: isToday(value), options: [], allowAsap: false, preorderOpen: false });
            return;
          }

          cfg.options = Array.isArray(data.options) ? data.options : [];
          cfg.allowAsap = Boolean(data.allowAsap);
          cfg.preorderOpen = Boolean(data.preorderOpen);
          cfg.preorderEnabled = Boolean(data.preorderEnabled);
          cfg.isOpen = Boolean(data.isOpen);
          cfg.scheduledDate = value;

          populateTimeSelect(select, {
            isToday: Boolean(data.isToday),
            options: cfg.options,
            allowAsap: cfg.allowAsap,
            preorderOpen: cfg.preorderOpen
          });
        });
      }, { once: false });
      dateInput.dataset.foodordTtdDateBound = '1';

      if (dateInput.value) {
        sendDate(dateInput.value);
      }
    }

    if (select.dataset.foodordTtdHydrated !== '1') {
      const currentDate = dateInput ? (dateInput.value || '') : '';
      populateTimeSelect(select, {
        isToday: isToday(currentDate),
        options: Array.isArray(cfg.options) ? cfg.options : [],
        allowAsap: Boolean(cfg.allowAsap),
        preorderOpen: Boolean(cfg.preorderOpen)
      });

      select.dataset.foodordTtdHydrated = '1';
    }

    markMounted(select);
    return true;
  }

  function isPickupMode() {
    // Body class added elsewhere when pickup is active.
    return document.body.classList.contains('foodord-pickup-mode');
  }

  function maybeRender() {
    const existingSelect = document.querySelector('#foodord-ttd-select');
    if (mounted && existingSelect && existingSelect.dataset.foodordTtdMounted === '1') {
      if (isPickupMode()) {
        const slot = document.getElementById('foodord-ttd');
        if (slot) slot.style.display = 'none';
        if (existingSelect) {
          existingSelect.dataset.foodordTtdMounted = '';
        }
        mounted = false;
        sendSelection('');
        sendDate('');
        return false;
      }
      return true;
    }

    if (isPickupMode()) {
      // Hide if present and clear any stored selection on session
      const slot = document.getElementById('foodord-ttd');
      if (slot) slot.style.display = 'none';
      sendSelection('');
      sendDate('');
      if (existingSelect) {
        existingSelect.dataset.foodordTtdMounted = '';
      }
      mounted = false;
      return false;
    }
    // Show/hydrate classic slot if exists; otherwise try blocks.
    if (!hydrateClassicSlot()) {
      insertIntoBlocks();
    } else {
      const slot = document.getElementById('foodord-ttd');
      if (slot) slot.style.display = '';
    }

    const updatedSelect = document.querySelector('#foodord-ttd-select');
    if (updatedSelect) {
      if (!mounted || updatedSelect.dataset.foodordTtdMounted !== '1') {
        markMounted(updatedSelect);
      }
      return true;
    }

    mounted = false;
    return false;
  }

  // Initial attempt
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', maybeRender);
  } else {
    maybeRender();
  }

  document.addEventListener('click', function(event){
    if (!event.target.closest('.foodord-ttd__dropdown')) {
      closeCustomDropdowns();
    }
  }, { once: false });

  document.addEventListener('keydown', function(event){
    if (event.key === 'Escape') {
      closeCustomDropdowns();
    }
  }, { once: false });

  // Observe for Blocks checkout rendering (dynamic mount)
  const mo = new MutationObserver(() => {
    if (maybeRender()) {
      mo.disconnect();
    }
  });
  mo.observe(document.documentElement || document.body, { subtree: true, childList: true });
})();
