(function () {
    let trigger = document.getElementById('showInstancesModal');
    let modal = document.getElementById('instancesModal');
    if (!trigger || !modal) return;

    let body = document.getElementById('instancesModalBody');
    let blockId = trigger.dataset.blockId;
    let loaded = false;

    function escapeHtml(str) {
        let div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    function openModal() {
        modal.style.display = 'flex';
        if (!loaded) {
            fetchInstances();
        }
    }

    function closeModal() {
        modal.style.display = 'none';
    }

    function fetchInstances() {
        body.innerHTML = '<p>Loading instances...</p>';
        fetch('/admin/blocks/ajax/block-instances/' + blockId, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(function (response) { return response.json(); })
        .then(function (data) {
            loaded = true;
            if (!data.instances || data.instances.length === 0) {
                body.innerHTML = '<p>No instances found.</p>';
                return;
            }
            let html = '<table class="instances-table"><thead><tr>' +
                '<th>Entity</th><th>Type</th><th>Status</th><th></th>' +
                '</tr></thead><tbody>';
            data.instances.forEach(function (inst) {
                let statusClass = inst.status === 'published' ? 'tag-green' : 'tag-yellow';
                html += '<tr>' +
                    '<td><a href="' + escapeHtml(inst.entity_edit_url) + '">' +
                        escapeHtml(inst.entity_name) + '</a></td>' +
                    '<td>' + escapeHtml(inst.entity_type) + '</td>' +
                    '<td><span class="tag ' + statusClass + '">' +
                        escapeHtml(inst.status) + '</span></td>' +
                    '<td><a href="' + escapeHtml(inst.edit_url) + '" class="btn btn-small">' +
                        'Edit Data</a></td>' +
                    '</tr>';
            });
            html += '</tbody></table>';
            body.innerHTML = html;
        })
        .catch(function () {
            body.innerHTML = '<p>Error loading instances.</p>';
        });
    }

    trigger.addEventListener('click', function (e) {
        e.preventDefault();
        openModal();
    });

    document.getElementById('closeInstancesModal').addEventListener('click', closeModal);

    modal.addEventListener('click', function (e) {
        if (e.target === modal) closeModal();
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.style.display === 'flex') {
            closeModal();
        }
    });
})();
