{% extends "django_spire/dropdown/dropdown.html" %}

{% block dropdown_trigger %}
    <div x-data="{
        new_notification: false,
        isLoading: false,

        async init(){
            await this.check_new_notifications();
            setInterval(await this.check_new_notifications, 30000);
        },

        async check_new_notifications(){
            let url = '{% url "django_spire:notification:app:json:check_new" %}';
            let response = await django_glue_fetch(url);
            this.new_notification = response.has_new_notifications;
        },

        async render_dropdown(){
            this.isLoading = true;
            let dropdown_content = new ViewGlue(
                url='{% url "django_spire:notification:app:template:notification_dropdown" %}',
                shared_payload={app_notification_list_url: '{{ app_notification_list_url|default:"" }}'}
            );
            let element = document.querySelector(`[x-ref='spire_notification_dropdown_content']`);
            await dropdown_content.render_inner(element);
            await this.mark_notifications_as_viewed();
            this.isLoading = false;
            $dispatch('content-loaded');
        },

        async mark_notifications_as_viewed(){
            let response = await django_glue_fetch('{% url "django_spire:notification:app:json:set_viewed" %}');
            this.new_notification = false;
        }

    }"
    class="position-relative">
        <span @click='await render_dropdown()'>
            {% block notification_dropdown_trigger %}
                <i x-bind='trigger' class="bi bi-bell-fill fs-4 cursor-pointer position-absolute"></i>
                <span x-show="new_notification"  x-cloak style="width: 10px; height: 10px; top: -1px; right: -24px;" class="bg-danger rounded-circle position-absolute"></span>
            {% endblock  %}
        </span>
    </div>

{% endblock %}

{% block dropdown_style %}z-index: 100 !important;{% endblock  %}
{% block dropdown_position %}top-100 end-50{% endblock %}

{% block dropdown_content %}
    <div
        x-data="{ hasContent: false }"
        x-show="hasContent"
        x-transition
        x-cloak
        @content-loaded.window="hasContent = true"
        :style="{ width: window.innerWidth < 768 ? (window.innerWidth / 2).toFixed(0) + 'px' : '350px' }"
    >
        <div x-ref="spire_notification_dropdown_content"></div>
    </div>
{% endblock %}
