<div class="drts-calendar-container"></div>
<script type="text/javascript">
<?php if (\SabaiApps\Directories\Request::isXhr()):?>
jQuery(function($) {
<?php else:?>
document.addEventListener('DOMContentLoaded', function() {
    var $ = jQuery;
<?php endif;?>
    var isValidUrl = function (url) {
        try {
            new URL(url);
            return true;
        } catch (e) {
            return false;
        }
    };
    var params = <?php $url_params[\SabaiApps\Directories\Request::PARAM_CONTENT_TYPE] = 'json'; echo json_encode($url_params);?>;
    var calendar = DRTS.Calendar.calendar(DRTS.container('<?php echo $CONTEXT->getContainer();?>').container, {
        url: '<?php echo $this->Url($CONTEXT->getRoute());?>',
        params: params,
        start_date_param_name: 'calendar_start',
        end_date_param_name: 'calendar_end',
        initialView: '<?php if ($settings['calendar_display_mode'] === 'year'):?>multiMonthYear<?php elseif ($settings['calendar_display_mode'] === 'list'):?>listMonth<?php else:?>dayGridMonth<?php endif;?>',
        onEventClick: function (event, $calendar) {
            if (event.$el.closest('.fc-popover').length
                || !event.extendedProps.raw.content
                || isValidUrl(event.extendedProps.raw.content)
            ) {
                if (isValidUrl(event.extendedProps.raw.content)) {
                    if (!event.extendedProps.raw.modal) {
                        window.location.href = event.extendedProps.raw.content;
                    } else {
                        DRTS.ajax({
                            type: "get",
                            container: "#drts-modal",
                            modalSize: event.extendedProps.raw.modalSize || "lg",
                            modalTitle: event.extendedProps.raw.modalTitle || event.title,
                            url: event.extendedProps.raw.content
                        });
                    }
                }
                return false;
            }
            DRTS.popover(event.$el, {
                html: true,
                width: <?php echo intval($settings['calendar_infobox_width']);?>,
                noPadding: true,
                //noHeader: true,
                placement: 'top',
                container: $calendar,
                sanitize: false,
                content: event.extendedProps.raw.content,
                title: event.title
            });

            return false;
        },
        onEventClassNames: function (event, view, $calendar) {
            var raw = event.extendedProps.raw || {};
            var baseClasses = raw.classes || [];
            if (!Array.isArray(baseClasses)) {
                baseClasses = [baseClasses];
            }
            if (raw.viewClasses && raw.viewClasses[view.type]) {
                var viewSpecificClasses = raw.viewClasses[view.type];
                if (!Array.isArray(viewSpecificClasses)) {
                    viewSpecificClasses = [viewSpecificClasses];
                }
                return baseClasses.concat(viewSpecificClasses);
            }
            return baseClasses;
        },
        onEventsSuccess: function(events, calendarInstance, response) {
            var handleNextAvailableLogic = function(events, calendar) {
                const $container = DRTS.container('<?php echo $CONTEXT->getContainer();?>').container;
                const $dot = $container.find('.drts-calendar-view-notification-dot');
                const $menu = $container.find('.drts-calendar-view-switch-nav-buttons .drts-bs-dropdown-menu');
                const $template = $menu.find('.drts-calendar-view-jump-item').first();

                $menu.find('.drts-calendar-view-jump-item-clone').remove();
                if (events.length === 0) {
                    const viewEnd = calendar.view.activeEnd.toISOString();
                    params['calendar_start'] = viewEnd;
                    params['calendar_end'] = '';
                    params['calendar_occurrence_limit'] = 3;
                    $.ajax({
                        url: DRTS.buildUrlWithParams('<?php echo $this->Url($CONTEXT->getRoute());?>', params),
                        success: function(occurrences) {
                            if (occurrences.length === 0) {
                                $dot.fadeOut();
                                const $newItem = $template.clone();
                                $newItem.addClass('drts-calendar-view-jump-item-clone');
                                $newItem.find('.' + DRTS.bsPrefix + 'dropdown-item')
                                    .addClass(DRTS.bsPrefix + 'text-muted')
                                    .text('No upcoming dates available')
                                    .attr('disabled', 'disabled');
                                $newItem.show().appendTo($menu);
                            } else {
                                occurrences.forEach((occurrence) => {
                                    const $newItem = $template.clone();
                                    $newItem.addClass('drts-calendar-view-jump-item-clone');
                                    $newItem.find('.drts-calendar-view-jump-item-date').text(occurrence.raw.date);
                                    $newItem.find('.drts-calendar-view-jump-item-title').text(occurrence.title || '予約可能');
                                    $newItem.find('[data-action="jump"]').on('click', function(e) {
                                        e.preventDefault();
                                        $dot.fadeOut();
                                        calendar.gotoDate(occurrence.start);
                                    });
                                    $newItem.show().appendTo($menu);
                                });
                                $dot.fadeIn();
                            }
                        },
                    });
                } else {
                    $dot.fadeOut();
                    const $newItem = $template.clone();
                    $newItem.addClass('drts-calendar-view-jump-item-clone');
                    $newItem.find('.drts-calendar-view-jump-item-date').text(events[0].raw.date);
                    $newItem.find('.drts-calendar-view-jump-item-title').text(events[0].title || '予約可能');
                    $newItem.find('[data-action="jump"]').on('click', function(e) {
                        e.preventDefault();
                        calendar.gotoDate(events[0].start);
                    });
                    $newItem.show().appendTo($menu);
                }
            };
            handleNextAvailableLogic(events, calendarInstance);
        },
    });
});
</script>