(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,
        availableTemplatesUrl: '/admin/blocks/ajax/entity/available-templates',
        applyTemplateUrl: '/admin/blocks/ajax/entity/apply-template'
    };

    // ─── Template Picker (works for all entity types including CMS pages) ───

    function createTemplateDialog(title, content) {
        let existing = document.getElementById('blockTemplateDialog');
        if (existing) existing.remove();

        let overlay = document.createElement('div');
        overlay.id = 'blockTemplateDialog';
        overlay.className = 'block-registry-dialog-overlay';

        let dialog = document.createElement('div');
        dialog.className = 'block-registry-dialog';

        let header = document.createElement('div');
        header.className = 'block-registry-dialog-header';
        header.innerHTML = '<h3>' + escapeHtml(title) + '</h3><button class="block-registry-dialog-close" id="blockTemplateDialogClose">&times;</button>';

        let body = document.createElement('div');
        body.className = 'block-registry-dialog-body';
        body.innerHTML = content;

        dialog.appendChild(header);
        dialog.appendChild(body);
        overlay.appendChild(dialog);
        document.body.appendChild(overlay);

        overlay.addEventListener('click', function(e) {
            if (e.target === overlay) closeTemplateDialog();
        });
        document.getElementById('blockTemplateDialogClose').addEventListener('click', closeTemplateDialog);
    }

    function closeTemplateDialog() {
        let dialog = document.getElementById('blockTemplateDialog');
        if (dialog) dialog.remove();
    }

    function openTemplatePicker() {
        createTemplateDialog('Apply Block Template', '<div class="template-picker"><div class="template-picker-loading">Loading templates...</div></div>');

        let params = new URLSearchParams({
            entity_type: entityType,
            entity_id: entityId
        });

        fetch('/admin/blocks/ajax/entity/available-templates?' + params.toString(), {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(function(response) { return response.json(); })
        .then(function(result) {
            let container = document.querySelector('.template-picker');
            if (!container) return;

            if (!result.success || !result.block_templates || result.block_templates.length === 0) {
                container.innerHTML = '<div class="template-picker-empty"><i class="fa fa-clipboard fa-2x"></i><br>No templates available for this entity type.</div>';
                return;
            }

            let html = '<div class="template-picker-list">';
            result.block_templates.forEach(function(bt) {
                html += '<div class="template-picker-item" data-template-id="' + bt.id + '">';
                html += '<div class="template-picker-item-header">';
                html += '<div class="template-picker-item-name"><i class="fa fa-clipboard"></i> ' + escapeHtml(bt.name) + '</div>';
                html += '<span class="template-picker-item-count">' + bt.block_count + ' block(s)</span>';
                html += '</div>';
                if (bt.description) {
                    html += '<div class="template-picker-item-desc">' + escapeHtml(bt.description) + '</div>';
                }
                if (bt.blocks && bt.blocks.length > 0) {
                    html += '<div class="template-picker-item-blocks">';
                    bt.blocks.forEach(function(b) {
                        html += '<span class="template-picker-block-tag"><i class="fa ' + (b.icon || 'fa-cube') + '"></i> ' + escapeHtml(b.name) + '</span>';
                    });
                    html += '</div>';
                }
                html += '<button type="button" class="template-picker-apply-btn">Apply Template</button>';
                html += '</div>';
            });
            html += '</div>';

            container.innerHTML = html;

            container.querySelectorAll('.template-picker-apply-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    let templateId = this.closest('.template-picker-item').getAttribute('data-template-id');
                    applyBlockTemplate(templateId);
                });
            });
        })
        .catch(function(error) {
            console.error('Failed to load templates:', error);
            let container = document.querySelector('.template-picker');
            if (container) {
                container.innerHTML = '<div class="template-picker-empty" style="color:#dc3545;">Failed to load templates.</div>';
            }
        });
    }

    function applyBlockTemplate(templateId) {
        closeTemplateDialog();

        let formData = new FormData();
        formData.append('entity_type', entityType);
        formData.append('entity_id', entityId);
        formData.append('block_template_id', templateId);

        fetch('/admin/blocks/ajax/entity/apply-template', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: formData
        })
        .then(function(response) { return response.json(); })
        .then(function(result) {
            if (result && result.success) {
                window.location.reload();
            } else {
                alert(result ? (result.error || 'Failed to apply template') : 'Failed to apply template');
            }
        })
        .catch(function(error) {
            console.error('Failed to apply template:', error);
            alert('Failed to apply template. Please try again.');
        });
    }

    // Delegated click handler for Add Template button (works in all contexts)
    document.addEventListener('click', function(e) {
        let btn = e.target.closest('.add-template-from-registry-btn');
        if (btn) {
            e.preventDefault();
            e.stopPropagation();
            openTemplatePicker();
        }
    });
})();
