{% extends 'base.html' %}

{% block title %}{{ title }}{% endblock %}
{% block content_title %}{{ title }}{% endblock %}
{% block content_description %}{{ description|default('') }}{% endblock %}

{% block content %}
<div class="container">
    <form method="POST" action="{{ form_action.lstrip('/') }}" id="{{ table_id }}-form">
        {% include 'eveai_list_view.html' %}
    </form>
</div>

<script>
// Wacht tot de pagina volledig geladen is
document.addEventListener('DOMContentLoaded', function() {
    // Functie om knoppen met requiresSelection te beheren
    const updateSelectionButtons = function(hasSelection) {
        document.querySelectorAll('.requires-selection').forEach(button => {
            if (hasSelection) {
                button.disabled = false;
                button.classList.remove('disabled');
            } else {
                button.disabled = true;
                button.classList.add('disabled');
            }
        });
    };

    // Direct alle requires-selection buttons disablen bij start
    updateSelectionButtons(false);

    // Wacht tot de EveAI.ListView module beschikbaar is
    function checkAndInitialize() {
        if (window.EveAI && window.EveAI.ListView && window.EveAI.ListView.initialize) {
            // Configureer de tabel
            const tableConfig = {
                data: {{ data | tojson }},
                columns: {{ columns | tojson }},
                initialSort: {{ initial_sort | tojson }},
                actions: {{ actions | tojson }},
                tableHeight: {{ table_height|default(600) }},
                selectable: true
            };

            // Initialiseer de tabel
            const tabulatorTable = window.EveAI.ListView.initialize('{{ table_id }}', tableConfig);

            if (tabulatorTable) {
                console.log('Tabulator tabel succesvol geïnitialiseerd');

                // Luister naar selectie-events
                tabulatorTable.on("rowSelectionChanged", function(data, rows) {
                    const hasSelection = rows.length > 0;
                    updateSelectionButtons(hasSelection);
                });

                // Luister naar deselect events
                tabulatorTable.on("rowDeselected", function(row) {
                    const selectedRows = tabulatorTable.getSelectedRows();
                    updateSelectionButtons(selectedRows.length > 0);
                });

                // Luister naar select events
                tabulatorTable.on("rowSelected", function(row) {
                    updateSelectionButtons(true);
                });

            } else {
                console.error('Kon de Tabulator tabel niet initialiseren');
            }
        } else {
            // Probeer opnieuw na een korte vertraging
            setTimeout(checkAndInitialize, 100);
        }
    }

    // Start de initialisatie
    setTimeout(checkAndInitialize, 50);
});
</script>
{% endblock %}
