{{-- Express Calendar --}}
<script>
    $(function() {
      //* Build Calendar Data
        // Build calendar
        const $express_calendar = $('#express-calendar');
        window.express_calendar = new FullCalendar.Calendar($express_calendar[0], {
          // Plugins - Localization - Lang
            plugins: ['interaction', 'resourceTimeline'],
            locale: "{{ session('locale') }}",
            lang: "{{ session('locale') }}", // Idioma
            navLinks: false,
            timeZone: "local",

          // Default view and design
            defaultView: 'resourceTimelineDay',
            aspectRatio: 1.5,
            resourceAreaWidth: '24%',
            height: 600,

          // Time Control
            nowIndicator: true,

            slotMinTime: "00:00:00",
            slotMaxTime: "24:00:00",
            slotDuration: '00:30:00',
            slotLabelInterval: '00:30',
            scrollTime: "00:00",
            snapDuration: '00:10:00', // Drag & Drop de cuanto en cuanto

          // Header and Buttons
            header: {
                left: 'today prev,next',
                center: 'title',
                right: 'resourceTimelineDay resourceTimelineWeek resourceTimelineFifteenDay',
            },

          // Custom button's texts
            buttonText: {
                today: "{{ __('neutral_words')['today'] }}",
                resourceTimelineDay: "{{ __('neutral_words')['day'] }}",
                resourceTimelineWeek: "{{ __('neutral_words')['week'] }}",
            },

          // Custom views and design
            views: {
                resourceTimelineFifteenDay: {
                    type: 'resourceTimeline',
                    duration: { weeks: 2 },
                    buttonText: "{{ __('neutral_words')['fortnight'] }}"
                },
            },

          // Special configurations
            editable: true,
            droppable: true,

            eventDurationEditable: false, // Avoid Resize

          // Reducing recognition time for interaction (Mobile)
            longPressDelay: 0,          // General Interactions
            eventLongPressDelay: 0,     // Drag&Drop Interactions
            selectLongPressDelay: 0,    // Touch Interactions

          // Data
            resourceColumns: @json($render_data->resource_columns),
            resourceLabelText:  "{{ $render_data->resource_main_label }}",
            resourceOrder: '{{ $render_data->resource_order }}',
            resources(fetchInfo, successData, failureMessage) {
                $.get("{{ route('api.calendar.rooms') }}", {is_express: true})
                    .done(successData).fail(failureMessage);
            },

            events: function(fetchInfo, successCallback, failureCallback) {
              // Conditionals
                if(!window.is_express_calendar) {
                    successCallback([]);
                    return;
                }

              // Get Stored Data
                let eventsEncrypted = localStorage.getItem("ExpressEventData") || null;
                let eventsStored = decryptData(eventsEncrypted);

              // Request for Changes
                // Request Data
                const start = moment(fetchInfo.startStr).format('YYYY-MM-DD');
                const end = moment(fetchInfo.endStr).format('YYYY-MM-DD');

                $.get("{{ route('api.calendar.events') }}", {start, end, is_express: true},
                    function(response) {
                        let data = JSON.parse(response);

                        if (JSON.stringify(eventsStored) !== JSON.stringify(data)) {
                            successCallback(data);

                            const encrypted = encryptData(data);
                            localStorage.setItem("ExpressEventData", encrypted);

                            launchSwalToast(
                                `{{ __('neutral_words')['information'] }} <b style="color:#12a15e">{{ __('common_actions')['updated'] }}</b>`,
                                'info',
                            );
                        }
                    }
                );
            },

          // Custom appearance
            eventRender: function(info) {
                let img = document.createElement('img');
                    img.src = info.event.extendedProps.image_url;
                    img.style = "width: 1.35rem; height: 1.35rem; object-fit: cover;margin-top:0.1rem; margin-bottom:-0.2rem;margin-left: 0.2rem; border-radius: 15px;";

                info.el.prepend(img);
            },

          // Interactions
            // OnClick interactions
            eventClick: function(info) {
                let id = info.event.classNames[1];
                loadReserveForm(id);
            },

            // Drag and Drop interactions
            eventResize: function(info) {
                const start = roundToNearest(10, info.event.start);
                const end = roundToNearest(10, info.event.end);

                info.event.setStart(start);
                info.event.setEnd(end);

                info.revert();
                forResize(info);
            },
            eventDrop: function(info) {
                const start = roundToNearest(10, info.event.start);
                const end = roundToNearest(10, info.event.end);

                info.event.setStart(start);
                info.event.setEnd(end);

                info.revert();
                forDrop(info);
            },

            eventDragStart: function() {
                window.is_express_dragging_event = true;
            },

            eventDragStop: function() {
                window.is_express_dragging_event = false;
            },
        });

        // Draw Calendar
        window.express_calendar.render();
        window.express_calendar.scrollToTime(moment().format('HH:mm:ss'));

      //* Calendar data cycle
        window.updateCalendarExpressEvents = () => window.express_calendar.refetchEvents();
        window.updateCalendarExpressEventsDebounced = (window.updateCalendarExpressEventsDebounced || debounce(updateCalendarExpressEvents, 800));

        setInterval(() => {
            if(window.is_express_calendar && !window.is_express_dragging_event)
                updateCalendarExpressEventsDebounced();
        }, 6000);

      //* Complementary Functions
        //- Drag and Drop Functions
        async function forResize(info) {
            await handleReservationChange(info, {
                message: `{{ __('common_responses_and_messages')['drag_and_drop_message_2'] }}`
            }, true);
        }

        async function forDrop(info) {
            await handleReservationChange(info, {
                message: `{{ __('common_responses_and_messages')['drag_and_drop_message_3'] }}`,
                extraHtml: (data, entry_date, departure_date) => {
                  //* Extract Data
                    const room_name = info.newResource?.extendedProps?.number_room
                        || data.getResources()[0]?.extendedProps?.number_room
                        || data.id || 'N/A';

                    const room_type = info.newResource?.extendedProps?.room_type
                        || data.getResources()[0]?.extendedProps?.room_type
                        || 'N/T';

                    const room_label = `${room_type} - ${room_name}`;

                  //* Build Extra HTML
                    return `
                        <div class="mb-3 input-group">
                            <span class="input-group-text">Habitación</span>
                            <input readonly class="form-control" value="${room_label}">
                        </div>
                    `;
                }
            }, true);
        }

    });
</script>
