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

          // Default view and design
            defaultView: 'resourceTimelineMonth',
            aspectRatio: 1.5,
            scrollTime: '00:00',
            aspectRatio: 2,
            resourceAreaWidth: '24%',
            // height: 600,

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

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

          // Custom views and design
            views: {
                resourceTimelineTrimestre: {
                    type: 'resourceTimeline',
                    duration: { months: 3 },
                    buttonText: "{{ __('neutral_words')['quarter'] }}"
                },
                resourceTimelineOneDay: {
                    type: 'resourceTimeline',
                    duration: { days: 1 },
                    buttonText: "{{ __('neutral_words')['day'] }}"
                },
                resourceTimelineFifteenDay: {
                    type: 'resourceTimeline',
                    duration: { weeks: 2 },
                    buttonText: "{{ __('neutral_words')['fortnight'] }}"
                },
            },

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

          // 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') }}")
                    .done(successData).fail(failureMessage);
            },

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

              // Get Stored Data
                let eventsEncrypted = localStorage.getItem("NormalEventData") || 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},
                    function(response) {
                        let data = JSON.parse(response);

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

                            const encrypted = encryptData(data);
                            localStorage.setItem("NormalEventData", 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.id;
                loadReserveForm(id);
            },

            // Drag and Drop interactions
            eventResize: function(info) {
                info.revert();
                forResize(info);
            },
            eventDrop: function(info) {
                info.revert();
                forDrop(info);
            },

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

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

        // Draw Calendar
        window.normal_calendar.render();

      //* Calendar data cycle
        window.updateCalendarEvents = () => window.normal_calendar.refetchEvents();
        window.updateCalendarEventsDebounced = (window.updateCalendarEventsDebounced || debounce(updateCalendarEvents, 800));

        setInterval(() => {
            if(window.is_normal_calendar && !window.is_normal_dragging_event)
                updateCalendarEventsDebounced();
        }, 6000);

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

        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>
                    `;
                }
            });
        }
    });
</script>
