document.addEventListener('DOMContentLoaded', function () {
    const calendarEl = document.getElementById('calendar');

    // Define all locales (you can add more or fetch dynamically)
    const locales = {
        es: {
            code: 'es',
            week: {
                dow: 1, // Monday is the first day of the week.
                doy: 4, // The week that contains Jan 4th is the first week of the year.
            },
            buttonText: {
                prev: 'Ant',
                next: 'Sig',
                today: 'Hoy',
                month: 'Mes',
                week: 'Semana',
                day: 'Día',
                list: 'Agenda',
            },
            weekText: 'Sm',
            allDayText: 'Todo el día',
            moreLinkText: 'más',
            noEventsText: 'No hay eventos para mostrar',
        },
        fr: {
            code: 'fr',
            week: {
                dow: 1, // Monday is the first day of the week.
                doy: 4, // The week that contains Jan 4th is the first week of the year.
            },
            buttonText: {
                prev: 'Précédent',
                next: 'Suivant',
                today: "Aujourd'hui",
                year: 'Année',
                month: 'Mois',
                week: 'Semaine',
                day: 'Jour',
                list: 'Planning',
            },
            weekText: 'Sem.',
            allDayText: 'Toute la journée',
            moreLinkText: 'en plus',
            noEventsText: 'Aucun événement à afficher',
        },
        ru: {
            code: 'ru',
            week: {
                dow: 1, // Monday is the first day of the week.
                doy: 4, // The week that contains Jan 4th is the first week of the year.
            },
            buttonText: {
                prev: 'Пред',
                next: 'След',
                today: 'Сегодня',
                month: 'Месяц',
                week: 'Неделя',
                day: 'День',
                list: 'Повестка дня',
            },
            weekText: 'Нед',
            allDayText: 'Весь день',
            moreLinkText: function(n) {
                return '+ ещё ' + n
            },
            noEventsText: 'Нет событий для отображения',
        },
        en: {
            code: 'en',
            week: {
                dow: 0, // Sunday is the first day of the week.
                doy: 4, // The week that contains Jan 4th is the first week of the year.
            },
            buttonText: {
                prev: 'Prev',
                next: 'Next',
                today: 'Today',
                month: 'Month',
                week: 'Week',
                day: 'Day',
                list: 'Agenda',
            },
            weekText: 'Wk',
            allDayText: 'All day',
            moreLinkText: 'more',
            noEventsText: 'No events to display',
        },
        ar: {
            code: 'ar',
            week: {
                dow: 1, // الإثنين هو أول يوم في الأسبوع
                doy: 4, // الأسبوع الذي يحتوي على 4 يناير هو أول أسبوع في السنة
            },
            buttonText: {
                prev: 'السابق',
                next: 'التالي',
                today: 'اليوم',
                year: 'السنة',
                month: 'الشهر',
                week: 'الأسبوع',
                day: 'اليوم',
                list: 'الجدول',
            },
            weekText: 'أسبوع',
            allDayText: 'طوال اليوم',
            moreLinkText: 'المزيد',
            noEventsText: 'لا يوجد أحداث لعرضها',
        },
        zh: {
            code: 'zh',
            week: {
                dow: 1, // 星期一是每周的第一天
                doy: 4, // 包含1月4日的那一周是年度的第一周
            },
            buttonText: {
                prev: '上一页',
                next: '下一页',
                today: '今天',
                year: '年份',
                month: '月份',
                week: '周',
                day: '天',
                list: '日程',
            },
            weekText: '周',
            allDayText: '全天',
            moreLinkText: '更多',
            noEventsText: '没有事件显示',
        },
        de: {
            code: 'de',
            week: {
                dow: 1, // Monday is the first day of the week.
                doy: 4, // The week that contains Jan 4th is the first week of the year.
            },
            buttonText: {
                prev: 'Zurück',
                next: 'Vor',
                today: 'Heute',
                year: 'Jahr',
                month: 'Monat',
                week: 'Woche',
                day: 'Tag',
                list: 'Terminübersicht',
            },
            weekText: 'KW',
            allDayText: 'Ganztägig',
            moreLinkText: function(n) {
                return '+ weitere ' + n
            },
            noEventsText: 'Keine Ereignisse anzuzeigen',
        }
    };

    // Get the locale dynamically (you can replace this with user input or other logic)
    const selectedLocale = $('#user-lang').data('value'); // Dynamically determine this
    const locale = locales[selectedLocale] || locales['en']; // Default to English if locale is not found

    // Log the selected locale for debugging
    //console.log(locale);

    const calendar = new FullCalendar.Calendar(calendarEl, {
        locale: locale,  // Use the dynamic locale
        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: $('#msg-yes').data('value'),
                    cancelButtonText: $('#msg-cancel').data('value'),
                    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();
});
