document.addEventListener('DOMContentLoaded', function () {
    const calendarEl = document.getElementById('calendar');
    const formatDateTime = (date) => {
        if (!date) return '---'; // Handle null/undefined date
        const options = {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false, // Use 24-hour format
        };
        return new Intl.DateTimeFormat('en-US', options).format(date);
    };

    const calendar = new FullCalendar.Calendar(calendarEl, {
      initialView: 'dayGridMonth',
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek'
      },
        titleFormat: { // Format the title to show abbreviated month name
        month: 'short', // Abbreviated month (e.g., Dec)
        year: 'numeric' // Full year (e.g., 2024)
      },
      eventContent: function (arg) {
          // Only show the event's time
          const timeText = arg.timeText; // FullCalendar's formatted time
          return { html: `<span class='badge bg-info'>${timeText}</span>` };
      },
      dateClick: function (info) {
        const clickedDate = new Date(info.dateStr);
        const today = new Date();

        // Normalize both dates to remove time parts
        clickedDate.setHours(0, 0, 0, 0);
        today.setHours(0, 0, 0, 0);

        if (clickedDate < today) {
          //alert(`The selected date (${info.dateStr}) is in the past.`);
        } else {
          //alert(`You clicked on a future or today's date: ${info.dateStr}`);
          swal({
            title: '',
            text: $('#schedule-campaigns-msg').data('value'),
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "btn-danger",
            confirmButtonClass: "btn-primary",
            confirmButtonText: "Yes",
            closeOnConfirm: true
            }, function (isConfirm) {
              if(isConfirm) {
                location.href = 'schedule_campaigns/create';
              }
          });

          
        }
      },
      eventClick: function (info) {
        // Populate modal with event details
        const event = info.event;
        viewModal('modal', 'schedule_campaigns/'+event.id)
      },
      events: function (fetchInfo, successCallback, failureCallback) {
        // AJAX call to fetch events
        fetch('shceduled_events', {
          method: 'GET',
        })
          .then(response => response.json())
          .then(data => {
            successCallback(data);
          })
          .catch(error => {
            console.error('Error fetching events:', error);
            failureCallback(error);
          });
      },
      eventTimeFormat: {
        hour: '2-digit',
        minute: '2-digit',
        meridiem: true, // Use 24-hour format
      },
    });

    calendar.render();
  });