document.addEventListener('DOMContentLoaded', function () {
    const INPUT_FORMAT = 'YYYY-MM-DDTHH:mm';
    var ter_kal_lang = terminKalenderData.ter_kal_lang;
    const urlParams = new URLSearchParams(window.location.search);
    const dateParam = urlParams.get('date');
    //---------------------------------------------------
    var calendarEl = document.getElementById('termin-kalender-admin-calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
        height: 'auto',
        locale: ter_kal_lang,
        headerToolbar: {
            left: 'prev,next,today',
            center: 'title',
            right: 'multiMonthYear,dayGridMonth,timeGridWeek,timeGridDay,listYear',
        },
        initialDate: dateParam,
        editable: true,
        timeZone: 'UTC', // keep all times in UTC timezone
        //eventDisplay: 'block',
        firstDay: 1,
        weekNumbers: true,
        navLinks: true, // can click day/week names to navigate views
        dayMaxEvents: true, // allow "more" link when too many events
        dayMaxEventRows: 8,
        eventMaxStack: 5,
        multiMonthMinWidth: 480,
        listDayFormat: { weekday: 'long', day: 'numeric', month: 'long' }, // Customize the main text format
        listDaySideFormat: false, // Hide the side text to avoid duplication
        events: function (info, successCb, failureCb) {
            var archiveToggle = document.getElementById('tk-show-archive');
            var loadArchive = archiveToggle && archiveToggle.checked ? 1 : 0;
            window.TerminKalender.API.getEvents(info.startStr, info.endStr, loadArchive)
                .then(function (response) {
                    successCb(Array.isArray(response) ? response : []);
                })
                .catch(function () {
                    failureCb(terminKalenderData.strings.error_fetching_events);
                    alert(terminKalenderData.strings.error_fetching_events);
                });
        },
        viewDidMount: function (info) {
            if (info.view.type === 'multiMonthYear') {
                calendar.setOption('dayMaxEventRows', 3);
            } else  //if (info.view.type === 'dayGridMonth')
            {
                calendar.setOption('dayMaxEventRows', 8);
            }
        },
        eventClick: function (info) {
            if (window.TerminKalender && window.TerminKalender.handleEventClickBackend) {
                return window.TerminKalender.handleEventClickBackend(info);
            }
        },
        dateClick: function (info) {
            if (window.TerminKalender && window.TerminKalender.UI) {
                window.TerminKalender.UI.openEventDialog(null, info.dateStr);
            }
        },
        eventDrop: function (info) {
            if (info.event.extendedProps.freq) {
                info.revert();
            }

            if (!info.event.extendedProps.google_url) {
                saveEvent(info.event);
            } else {
                info.revert();
            }
        },
        eventContent: function (info) {
            let event = info.event;
            let timeText = ''
            let titleText = event.title;
            let time_von = moment.utc(event.start).format('HH:mm');
            let time_bis = moment.utc(event.end).format('HH:mm');
            let freqtxt = '';
            if (event.extendedProps.freq) {
                time_bis = moment.utc(event.extendedProps.until).format('HH:mm');
                freqtxt = terminKalenderData.strings[event.extendedProps.freq];
            }
            if (event.allDay) {
                timeText = '<span class="time_text">' + freqtxt + ' ' + terminKalenderData.strings.all_day + '</span> ';
            } else {
                timeText = '<span class="time_text">' + freqtxt + ' ' + time_von + ' - ' + time_bis + '</span> ';
            }

            switch (info.view.type) {
                case 'multiMonthYear':
                    return {
                        html: '<span class="title_text title_text_mmy" style="background-color:' + event.backgroundColor + '; color:' + event.textColor + '; ">'
                            + titleText + '</span>'
                    };
                case 'dayGridMonth':
                    return {
                        html: '<div class="title_text title_text_dgm" style="background-color:' + event.backgroundColor
                            + '; color:' + event.textColor + '; "><b  class="time_text" >'
                            + timeText + '</b> <br/>' + titleText + '</div>'
                    };
                case 'timeGridWeek':
                    return {
                        html: '<div class="title_text" style="background-color:' + event.backgroundColor
                            + '; color:' + event.textColor + '; ">'
                            + titleText + '</div>'
                    };
                case 'timeGridDay':
                    return {
                        html: '<div class="title_text title_text_tgd" style="background-color:' + event.backgroundColor
                            + '; color:' + event.textColor + '; ">'
                            + titleText + '</div>'
                    };
                case 'listWeek':
                    return {
                        html: '<div class="title_text_lw" >'
                            + titleText + ' ' + timeText + '</div>'
                    };
                    break;
                default:
                    return {
                        html: '<span class="title_text" style="background-color:' + event.backgroundColor + '; color:' + event.textColor + '; ">'
                            + titleText + ' ' + timeText + '</span>'
                    };
                    break;
            }
        }
    });
    //window.calendar = calendar; // keep for backward comp
    window.TerminKalender.calendar = calendar;
    window.TerminKalender.calendar.render();

    // Add onChange listener to Archive toggle if it exists
    var archiveToggle = document.getElementById('tk-show-archive');
    if (archiveToggle) {
        archiveToggle.addEventListener('change', function () {
            if (window.TerminKalender.calendar) window.TerminKalender.calendar.refetchEvents();
        });
    }
    //---------------------------------------------------------------------------------------------------------------
    //---------------------------------------------------------------------------------------------------------------
    // adding google calendar if google calendar id is set
    var google_admin_calendar = terminKalenderData.google_admin_calendar;
    if (terminKalenderData.TERMIN_KALENDER_PRO_ON == 'on' && google_admin_calendar == 'on') {
        show_google_calendar();
    }

    function show_google_calendar() {
        var termin_kalender_google_kalender_id = document.querySelector('.ter-kal-block-kalender')?.dataset.g_id;
        var termin_kalender_google_api_key = document.querySelector('.ter-kal-block-kalender')?.dataset.g_key;

        if (termin_kalender_google_kalender_id && termin_kalender_google_api_key) {
            calendar.setOption('googleCalendarApiKey', termin_kalender_google_api_key);
            calendar.addEventSource({
                googleCalendarId: termin_kalender_google_kalender_id,
                eventDataTransform: function (eventData) {
                    // rename url → google_url
                    const transformed = {
                        ...eventData,
                        className: 'fc-google-event', // Add custom class
                        extendedProps: {
                            ...eventData.extendedProps,
                            google_url: eventData.url
                        }
                    };
                    delete transformed.url;  // Completely remove the URL property
                    return transformed;
                }
            });
        }
    }

    // Internal event mover logic (does not touch forms, calls API directly)
    function saveEvent(event) {
        var categoryData = event.extendedProps.category;

        var data = {
            id: event.id,
            title: event.title,
            start: event.startStr,
            end: event.endStr,
            until: event.extendedProps.until,
            backgroundColor: categoryData ? categoryData.backgroundColor : '',
            textColor: categoryData ? categoryData.textColor : '',
            details: event.extendedProps.details,
            notes: event.extendedProps.notes,
            location: event.extendedProps.location,
            freq: event.extendedProps.freq,
            exdate: event ? event.exdate : '',
            allDay: event ? event.allDay : null,
            byweekday: event.extendedProps.byweekday,
            interval: event.extendedProps.interval,
            post_link: event.extendedProps.post_link,
            bysetpos: event.extendedProps.bysetpos,
            category: categoryData ? categoryData.label : ''
        };
        window.TerminKalender.API.saveEvent(data)
            .then(function (response) {
                if (!response.id) {
                    alert(terminKalenderData.strings.error_saving_event);
                }
            })
            .catch(function () {
                alert(terminKalenderData.strings.error_saving_event);
            });
    }
});
