{% extends 'core/card/title_card.html' %}

{% block card_content %}
    <div
        x-data="{
            card_title_dropdown: false,
            endpoint: '{{ endpoint }}',
            shared_payload: {},
            page_size: parseInt('{{ page_size }}' || 10),
            current_page: parseInt('{{ current_page }}' || 1),
            has_next: {{ has_next|default:'false'|yesno:'true,false' }} || false,
            is_loading: false,
            observer: null,

            async init() {
                requestAnimationFrame(() => {
                    if (this.$refs.scroll_container) {
                        this.$refs.scroll_container.scrollTop = 0;
                    }
                });

                if (this.has_next) {
                    await this.setup_observer();
                }

                this.shared_payload = JSON.parse(document.getElementById('shared_payload').textContent)
            },

            async setup_observer() {
                let trigger = this.$refs.infinite_scroll_trigger;

                if (!trigger) {
                    console.error('Infinite scroll trigger element not found.');
                    return;
                }

                let options = {
                    root: null,
                    rootMargin: '0px',
                    threshold: 1.0
                };

                this.observer = new IntersectionObserver(
                    (entries) => {
                        entries.forEach(async entry => {
                            if (entry.isIntersecting && this.has_next && !this.is_loading) {
                                await this.load_more();
                            }
                        });
                    },
                    options
                );

                this.observer.observe(trigger);
            },

            async fetch(next_page) {
                if (!this.endpoint) return { success: false, error: 'No endpoint provided' };

                let params = new URLSearchParams({
                    page: next_page,
                    page_size: this.page_size
                });

                let url = `${this.endpoint}?${params}`;
                let view = new ViewGlue(url, this.shared_payload);

                try {
                    await view.render_insert_adjacent(this.$refs.item_container, {}, 'beforeend')
                    return { success: true };
                } catch (error) {
                    console.error(error);
                    return { success: false, error };
                }
            },

            async load_more() {
                if (!this.endpoint) return;

                this.is_loading = true;

                let next_page = this.current_page + 1;

                let container = this.$refs.item_container;
                let previous_count = container.childElementCount;

                let result = await this.fetch(next_page);

                if (!result.success) {
                    this.is_loading = false;
                    return;
                }

                let current_count = container.childElementCount;
                let added = current_count - previous_count;

                if (added > 0) {
                    this.current_page = next_page;
                }

                if (added < this.page_size) {
                    this.has_next = false;
                }

                this.is_loading = false;
            },

            toggle_card_title_dropdown() {
                this.card_title_dropdown = !this.card_title_dropdown;
            }
        }"
    >
        {{ shared_payload|json_script:'shared_payload' }}

        <div class="row justify-content-between align-items-center {% block card_title_class %}mb-2 pb-2 border-bottom-secondary{% endblock %}">
            <div class="col">
                <div class="card-title text-uppercase mb-0">{% block card_title %}{% endblock %}</div>
            </div>
            <div class="col-auto d-flex align-items-center" style="min-height: 2.0rem;">
                {% block card_button %}
                {% endblock %}
            </div>
        </div>

        <div
            x-ref="scroll_container"
            style="{% block card_title_content_style %}{% endblock %} overscroll-behavior: contain;"
        >
            {% block card_title_content %}
            {% endblock %}

            <div x-ref="item_container"></div>

            <div x-show="is_loading" class="text-center my-3">
                <div class="spinner-border" role="status"></div>
            </div>

            <div x-ref="infinite_scroll_trigger" style="height:10px;"></div>
        </div>
    </div>
{% endblock %}
