(function($){
  'use strict';

  function safeParseMinDate(minDateRaw) {
    if ( minDateRaw instanceof Date ) { return minDateRaw; }
    if ( typeof minDateRaw === 'number' ) { return minDateRaw; }
    if ( typeof minDateRaw === 'string' ) {
      var s = minDateRaw.trim();
      var m = s.match(/^new\s+Date\s*\(\s*(\d{4})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\)\s*$/i);
      if ( m ) {
        return new Date( parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10) );
      }
      var iso = Date.parse(s);
      if ( !isNaN(iso) ) { return new Date(iso); }
      var intVal = parseInt(s, 10);
      if ( !isNaN(intVal) ) { return intVal; }
    }
    return null;
  }

  var $timeslotSelect  = null;
  var $timeslotLoading = null;
  var $timeslotNoSlots = null;
  var timeslotsEnabled = false;

  function initTimeslotElements() {
    $timeslotSelect  = $('#dreamfox_wdd_timeslot');
    $timeslotLoading = $('#dreamfox-timeslot-loading');
    $timeslotNoSlots = $('#dreamfox-timeslot-no-slots');
    timeslotsEnabled = ( typeof dreamfoxWdd !== 'undefined' && dreamfoxWdd.timeslotsEnabled );
  }

  function loadTimeslots(dateText) {
    if ( !timeslotsEnabled || !$timeslotSelect || !$timeslotSelect.length ) { return; }

    var i18n = (dreamfoxWdd && dreamfoxWdd.i18n) ? dreamfoxWdd.i18n : {};

    $timeslotSelect.hide().empty();
    $timeslotNoSlots.hide();
    $timeslotLoading.show();

    $.ajax({
      url:  dreamfoxWdd.ajaxUrl,
      type: 'POST',
      data: {
        action: 'dreamfox_wdd_get_timeslots',
        nonce:  dreamfoxWdd.nonce,
        date:   dateText,
      },
      success: function(response) {
        $timeslotLoading.hide();

        if ( !response.success || !response.data || !response.data.slots ) {
          $timeslotNoSlots.show();
          return;
        }

        var slots = response.data.slots;
        if ( slots.length === 0 ) {
          $timeslotNoSlots.show();
          return;
        }

        $timeslotSelect.append( $('<option>', { value: '', text: i18n.selectSlot || '— Select a timeslot —' }) );
        $.each(slots, function(i, slot) {
          $timeslotSelect.append( $('<option>', { value: slot.value, text: slot.label }) );
        });
        $timeslotSelect.show();
      },
      error: function() {
        $timeslotLoading.hide();
        $timeslotNoSlots.show();
      },
    });
  }

  function ensureInputExists($container, desiredId, desiredName) {
    var $input = $('#' + desiredId);
    if ($input.length) { return $input; }

    $input = $container.find('input[type="text"], input[type="date"], input.datepicker').first();
    if ($input.length) {
      if (!$input.attr('id')) { $input.attr('id', desiredId); }
      if (!$input.attr('name') && desiredName) { $input.attr('name', desiredName); }
      return $input;
    }

    var $wrap = $container.find('.woocommerce-input-wrapper').first();
    var attrs = { type: 'text', id: desiredId, name: desiredName || desiredId, 'class': 'input-text dreamfox-delivery-input', autocomplete: 'off' };
    var $new = $('<input>', attrs);
    if ($wrap.length) { $wrap.append($new); } else { $container.append($new); }
    return $new;
  }

  function initDatepickerOnce($el, opts) {
    if ( $el.hasClass('hasDatepicker') || $el.data('ui-datepicker') ) { return; }
    try {
      $el.datepicker(opts);
    } catch (e) {
      console.error('dreamfox: datepicker init failed', e, $el);
    }
  }

  function initDeliveryDatepickers() {
    if ( typeof $.datepicker === 'undefined' ) {
      console.warn('dreamfox: jQuery UI Datepicker not available');
      return;
    }
    if ( typeof dreamfoxWdd === 'undefined' ) {
      console.warn('dreamfox: dreamfoxWdd not found');
      return;
    }

    initTimeslotElements();

    var raw         = dreamfoxWdd || {};
    var holidays    = raw.holidays || [];
    var disableDays = raw.disableDays || [];
    var minDate     = safeParseMinDate(raw.minDate);
    var dateFormat  = raw.dateFormat || 'yy-mm-dd';
    var selector    = raw.selector || '#dreamfox_delivery_date';
    var i18n        = raw.i18n || { holidayLabel: 'Holiday' };

    var opts = {
      changeMonth:    true,
      changeYear:     true,
      numberOfMonths: 2,
      dateFormat:     dateFormat,
      minDate:        minDate,
      beforeShowDay: function(date) {
        var iso = $.datepicker.formatDate('yy-mm-dd', date);
        var day = date.getDay() + 1;

        if ( $.inArray(day, disableDays) !== -1 ) {
          return [ false, 'ui-state-disabled', '' ];
        }

        if ( $.inArray(iso, holidays) !== -1 ) {
          return [ false, 'ui-state-disabled dreamfox-holiday', i18n.holidayLabel ];
        }

        return [ true, '', '' ];
      },
      onSelect: function(dateText) {
        loadTimeslots(dateText);
      },
    };

    var $inputs = $(selector);

    if ( $inputs.length === 0 ) {
      var $container = $(selector + '_field');
      if ( !$container.length && selector.indexOf('_field') === -1 ) {
        $container = $(selector + '_field');
      }
      if ( $container.length ) {
        var desiredId = (selector.charAt(0) === '#') ? selector.slice(1) : selector;
        $inputs = ensureInputExists($container, desiredId, desiredId);
      }
    }

    if ( $inputs.length === 0 ) {
      $inputs = $('[name*="delivery"], [id*="delivery"], [class*="delivery"]').filter(':visible');
    }

    if ( $inputs.length === 0 ) {
      console.warn('dreamfox: Could not find delivery input. Selector:', selector);
      return;
    }

    $inputs.each(function() {
      initDatepickerOnce($(this), opts);
    });
  }

  $(function() {
    initDeliveryDatepickers();
  });

  $(document.body).on('updated_checkout', function() {
    initDeliveryDatepickers();
  });

})(jQuery);
