(function ($, Drupal){
  'use strict';
  Drupal.behaviors.timeslots = {
    attach: function (context) {
      // Calendar
      once('datepicker', '.my-datepicker-timeslot', context).forEach(selector => {
        $(selector).datepicker({
          changeMonth: false,
          changeYear: false,
          minDate: new Date(),
          numberOfMonths: [1,1],
          yearRange: "c:c+3",
          dateFormat: 'mm/dd/yy',
          monthNames: [
            Drupal.t('January',  { context: 'Long month name'}),
            Drupal.t('February', { context: 'Long month name'}),
            Drupal.t('March',  { context: 'Long month name'}),
            Drupal.t('April', { context: 'Long month name'}),
            Drupal.t('May', { context: 'Long month name'}),
            Drupal.t('June', { context: 'Long month name'}),
            Drupal.t('July', { context: 'Long month name'}),
            Drupal.t('August', { context: 'Long month name'}),
            Drupal.t('September', { context: 'Long month name'}),
            Drupal.t('October',  { context: 'Long month name'}),
            Drupal.t('November', { context: 'Long month name'}),
            Drupal.t('December',  { context: 'Long month name'}),
          ],
          firstDay: 1,
          beforeShowDay: function(date) {
            let cssClass = '';
            let formattedDate = (date.getMonth()+1).toString().padStart(2, "0") + "/" + date.getDate().toString().padStart(2, "0") + "/" + date.getFullYear();
            let timeslots = document.querySelectorAll('.time-slot-group time[data-date="' + formattedDate + '"]');
            if (timeslots.length > 0){
              cssClass += "dp-highlight";
            }
            return [true, cssClass];
          },
          onSelect: function(dateText) {
            // disabled button buy
            $('.timeslots-list .buy-buttons a').attr('disabled', true).addClass('disabled');
            // Change text selected
            let $dropdownMenuTime = $('#dropdownMenuTime');
            $dropdownMenuTime.text($dropdownMenuTime.data('text-behaviors'));

            let timeSlots = document.querySelectorAll('.time-slot-group time[data-date="'+dateText+'"]');
            if(timeSlots.length > 0) {
              // Replace for fix formater Firefox
              const dateSelected = new Date(dateText);
              $('#date-day').text(dateSelected.getDate().toString().padStart(2, "0"));
              $('#date-month').text(dateSelected.toLocaleString('default', { month: 'short' }));
              $('#date-year').text(dateSelected.getFullYear());

              // Remove all li but not the fist
              $('#time-options li').remove();
              // Populate options time
              timeSlots.forEach(timeSlot => {
                $('#time-options').append('<li><button class="dropdown-item time-option" data-timeslot-id="'+$(timeSlot).data('timeslot-id')+'">'+$(timeSlot).data('time')+'</button></li>');
              });
            }
            // refresh Behaviors to load addEventListener
            Drupal.attachBehaviors();
          }
        });

        // Select default active
        $('.my-datepicker-timeslot .ui-state-active').click();

      });

      once('time-options', '.time-option', context).forEach(link => {
        link.addEventListener('click', function (event) {
          event.preventDefault();
          let timeSlotSelected = $(this).data('timeslot-id');
          let $timeSlotSelected = $('.time-slot-group time[data-timeslot-id="'+timeSlotSelected+'"]');
          let buyTimeSlots = $timeSlotSelected.data('buy');
          // Show selected time
          $('#dropdownMenuTime').text($timeSlotSelected.data('time'));
          // Change link buy
          if(buyTimeSlots.length == 1){
            $('.buy-buttons').html('<a target="_blank" href="'+ buyTimeSlots[0].link +'" class="btn px-4 bg-primary text-white shadow text-start w-100 lh-lg">'+ buyTimeSlots[0].title +'</a>')
          } else {
            $('.buy-buttons').html('<button class="btn px-4 bg-primary text-white shadow text-start w-100 dropdown-toggle lh-lg show" type="button" id="dropdownMenuBuy" data-bs-toggle="dropdown" aria-expanded="true">'+ $('.buy-buttons').data('text-behaviors') +'</button><ul class="dropdown-menu w-100" aria-labelledby="dropdownMenuButton1" data-popper-placement="bottom-start"></ul>');
            buyTimeSlots.forEach(buyTimeSlot => {
              $('.buy-buttons .dropdown-menu').append('<li><a target="_blank" class="dropdown-item" href="'+ buyTimeSlot.link +'">'+ buyTimeSlot.title +'</a></li>');
            });
          }
          $('.timeslots-list .buy-buttons a').attr('disabled', false).removeClass('disabled');
        });
      });
    }
  }
})(jQuery, Drupal);


