(function() {
    // Read entity context from the container's data attributes
    const container = document.querySelector('.entityBlocksList');
    const entityType = container ? container.getAttribute('data-entity-type') : 'page';
    const entityId = container ? container.getAttribute('data-entity-id') : null;

    // AJAX endpoints (entity-generic for all types)
    const availableUrl = '/admin/blocks/ajax/entity/available';
    const addUrl = '/admin/blocks/ajax/entity/add';
    const addGlobalUrl = '/admin/blocks/ajax/entity/add-global';
    const entityBlocksHtmlUrl = '/admin/blocks/ajax/entity/blocks-html';

    // Load SortableJS dynamically to avoid blocking page if CDN fails
    function initSortable() {
        let sortableEl = document.getElementById('entityBlocksSortable');
        if (!sortableEl || typeof Sortable === 'undefined') {
            return;
        }

        new Sortable(sortableEl, {
            handle: '.drag-handle',
            animation: 150,
            ghostClass: 'sortable-ghost',
            onEnd: function(evt) {
                // Get the new order of block IDs
                let rows = sortableEl.querySelectorAll('tr[data-entity-block-id]');
                let order = [];
                rows.forEach(function(row, index) {
                    order.push({
                        id: parseInt(row.getAttribute('data-entity-block-id')),
                        order: index
                    });
                });

                // Save the new order via AJAX (reorder endpoint is already entity-agnostic)
                fetch('/admin/blocks/ajax/reorder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({ blocks: order })
                })
                .then(function(response) {
                    return response.json();
                })
                .then(function(data) {
                    if (!data.success) {
                        alert('Failed to save order: ' + (data.error || 'Unknown error'));
                    }
                })
                .catch(function(error) {
                    console.error('Error saving order:', error);
                    alert('Failed to save block order. Please try again.');
                });
            }
        });
    }

    // Load SortableJS from CDN
    if (typeof Sortable === 'undefined') {
        let script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js';
        script.integrity = 'sha256-ipiJrswvAR4VAx/th+6zWsdeYmVae0iJuiR+6OqHJHQ=';
        script.crossOrigin = 'anonymous';
        script.onload = initSortable;
        script.onerror = function() {
            console.warn('Failed to load SortableJS - drag reordering disabled');
        };
        document.head.appendChild(script);
    } else {
        initSortable();
    }

    // Handle status toggle button clicks
    document.querySelectorAll('.toggleStatusBtn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            let entityBlockId = this.getAttribute('data-entity-block-id');
            let currentStatus = this.getAttribute('data-status');
            let newStatus = currentStatus === 'published' ? 'draft' : 'published';
            let button = this;
            let row = this.closest('tr');

            fetch('/admin/blocks/ajax/toggle-status', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ id: parseInt(entityBlockId), status: newStatus })
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data.success) {
                    button.setAttribute('data-status', data.status);
                    if (data.status === 'published') {
                        button.textContent = 'Published';
                        button.style.background = '#28a745';
                        row.style.opacity = '1';
                    } else {
                        button.textContent = 'Draft';
                        button.style.background = '#6c757d';
                        row.style.opacity = '0.55';
                    }
                } else {
                    alert('Failed to update status: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(function(error) {
                console.error('Error toggling status:', error);
                alert('Failed to update status. Please try again.');
            });
        });
    });

    // Handle remove entity block button clicks
    document.querySelectorAll('.removeEntityBlockBtn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (!confirm('Are you sure you want to remove this block?')) {
                return;
            }

            let entityBlockId = this.getAttribute('data-entity-block-id');
            let row = this.closest('tr');

            fetch('/admin/blocks/data/' + entityBlockId, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(function(response) {
                if (response.ok || response.redirected) {
                    row.remove();
                    // Update badge count
                    let badge = document.querySelector('.entityBlocksFieldset .badge');
                    if (badge) {
                        let count = parseInt(badge.textContent) - 1;
                        badge.textContent = count;
                    }
                    // Show empty message if no blocks left
                    let tbody = document.querySelector('.entityBlocksTable tbody');
                    if (tbody && tbody.children.length === 0) {
                        let entityLabels = { page: 'this page', item: 'this product', category: 'this category' };
                        let label = entityLabels[entityType] || 'this item';
                        document.querySelector('.entityBlocksList').innerHTML = '<p style="color: #666; text-align: center; padding: 20px;"><i class="fa fa-info-circle"></i> No blocks from Block Registry added to ' + label + ' yet.</p>';
                    }
                } else {
                    alert('Failed to remove block. Please try again.');
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
                alert('Failed to remove block. Please try again.');
            });
        });
    });

    // Block preview tooltip (live iframe) on entity block name hover
    let blockPreviewTooltip = null;
    let blockPreviewHoverTimer = null;

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

    function showBlockPreviewTooltip(previewUrl, target) {
        hideBlockPreviewTooltip();

        let rect = target.getBoundingClientRect();

        blockPreviewHoverTimer = setTimeout(function() {
            blockPreviewTooltip = document.createElement('div');
            blockPreviewTooltip.className = 'block-preview-tooltip';
            blockPreviewTooltip.innerHTML = '<div class="block-preview-iframe-wrap">'
                + '<iframe src="' + escapeHtml(previewUrl) + '" frameborder="0" scrolling="no"></iframe>'
                + '</div>';
            document.body.appendChild(blockPreviewTooltip);

            let x = rect.right + 12;
            let y = rect.top;

            if (x + 420 > window.innerWidth) {
                x = rect.left - 420 - 12;
            }
            if (y + 270 > window.innerHeight) {
                y = window.innerHeight - 270;
            }
            if (y < 10) {
                y = 10;
            }

            blockPreviewTooltip.style.left = x + 'px';
            blockPreviewTooltip.style.top = y + 'px';
        }, 300);
    }

    function hideBlockPreviewTooltip() {
        if (blockPreviewHoverTimer) {
            clearTimeout(blockPreviewHoverTimer);
            blockPreviewHoverTimer = null;
        }
        if (blockPreviewTooltip) {
            blockPreviewTooltip.remove();
            blockPreviewTooltip = null;
        }
    }

    // Bind hover events on entity block name wraps
    document.querySelectorAll('.entity-block-name-wrap[data-preview-url]').forEach(function(el) {
        el.addEventListener('mouseenter', function() {
            showBlockPreviewTooltip(this.getAttribute('data-preview-url'), this);
        });
        el.addEventListener('mouseleave', function() {
            hideBlockPreviewTooltip();
        });
    });

    // Expose entity context for the add-block modal (used by block_registry.css modal JS)
    window.blockRegistryEntityContext = {
        entityType: entityType,
        entityId: entityId,
        availableUrl: availableUrl,
        addUrl: addUrl,
        addGlobalUrl: addGlobalUrl,
        entityBlocksHtmlUrl: entityBlocksHtmlUrl
    };
})();
