/**
 * Standalone Block Picker for non-CMS entity pages (products, categories)
 * Works without the content_manager JS globals
 */
(function() {
    const ctx = window.blockRegistryEntityContext || {};
    const entityType = ctx.entityType;
    const entityId = ctx.entityId;

    if (!entityType || !entityId) {
        return;
    }

    let blockPickerData = {
        blocks: [],
        categories: [],
        globalBlocks: [],
        searchTerm: '',
        selectedCategory: null,
        loading: false
    };

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

    // Create a simple modal dialog
    function createDialog(title, content) {
        // Remove existing dialog
        let existing = document.getElementById('blockRegistryDialog');
        if (existing) existing.remove();

        let overlay = document.createElement('div');
        overlay.id = 'blockRegistryDialog';
        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 id="blockRegistryDialogClose" class="block-registry-dialog-close">&times;</button>';

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

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

        // Close handlers
        overlay.addEventListener('click', function(e) {
            if (e.target === overlay) closeDialog();
        });
        document.getElementById('blockRegistryDialogClose').addEventListener('click', closeDialog);
    }

    function closeDialog() {
        let dialog = document.getElementById('blockRegistryDialog');
        if (dialog) dialog.remove();
    }

    function openBlockPicker() {
        let dialogContent = buildBlockPickerContent();
        createDialog('Add Block from Registry', dialogContent);
        loadAvailableBlocks();
        return false;
    }

    function buildBlockPickerContent() {
        let tpl = document.getElementById('blockPickerContentTemplate');
        if (tpl) {
            let clone = tpl.content.cloneNode(true);
            let wrapper = document.createElement('div');
            wrapper.appendChild(clone);
            return wrapper.innerHTML;
        }
        // Fallback if template not available
        return '<div class="block-picker">'
            + '<div class="block-picker-header">'
            + '<div class="block-picker-search"><input type="text" id="blockPickerSearch" placeholder="Search blocks..." /></div>'
            + '<div class="block-picker-filter"><select id="blockPickerCategory"><option value="">All Categories</option></select></div>'
            + '</div>'
            + '<div class="block-picker-content" id="blockPickerContent"><div class="block-picker-loading">Loading blocks...</div></div>'
            + '</div>';
    }

    function loadAvailableBlocks() {
        let params = new URLSearchParams({
            entity_type: entityType,
            entity_id: entityId
        });
        if (blockPickerData.searchTerm) {
            params.append('search', blockPickerData.searchTerm);
        }
        if (blockPickerData.selectedCategory) {
            params.append('category_id', blockPickerData.selectedCategory);
        }

        fetch(ctx.availableUrl + '?' + params.toString(), {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(function(response) { return response.json(); })
        .then(function(result) {
            blockPickerData.blocks = result.blocks || [];
            blockPickerData.categories = result.categories || [];
            blockPickerData.globalBlocks = result.global_blocks || [];
            blockPickerData.loading = false;
            renderBlockPicker();
        })
        .catch(function(error) {
            console.error('Failed to load blocks:', error);
            let content = document.getElementById('blockPickerContent');
            if (content) {
                content.innerHTML = '<div class="block-picker-empty" style="color:#dc3545;">Failed to load blocks. Please try again.</div>';
            }
        });
    }

    function renderBlockPicker() {
        let categorySelect = document.getElementById('blockPickerCategory');
        if (categorySelect) {
            blockPickerData.categories.forEach(function(cat) {
                let option = document.createElement('option');
                option.value = cat.id;
                option.textContent = cat.name;
                categorySelect.appendChild(option);
            });

            // Merge categories from global blocks that aren't already listed
            let existingCatIds = new Set(blockPickerData.categories.map(function(c) { return String(c.id); }));
            blockPickerData.globalBlocks.forEach(function(gb) {
                if (gb.category_id && gb.category_name && !existingCatIds.has(String(gb.category_id))) {
                    existingCatIds.add(String(gb.category_id));
                    let opt = document.createElement('option');
                    opt.value = gb.category_id;
                    opt.textContent = gb.category_name;
                    categorySelect.appendChild(opt);
                }
            });

            // Add "Uncategorized" option if any blocks or global blocks lack a category
            let hasUncategorized = blockPickerData.blocks.some(function(b) { return !b.category_id; }) ||
                blockPickerData.globalBlocks.some(function(gb) { return !gb.category_id; });
            if (hasUncategorized) {
                let uncatOpt = document.createElement('option');
                uncatOpt.value = 'uncategorized';
                uncatOpt.textContent = 'Uncategorized';
                categorySelect.appendChild(uncatOpt);
            }

            categorySelect.addEventListener('change', function() {
                blockPickerData.selectedCategory = this.value || null;
                renderBlockList();
            });
        }

        let searchInput = document.getElementById('blockPickerSearch');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                blockPickerData.searchTerm = this.value;
                renderBlockList();
            });
        }

        renderBlockList();
    }

    function renderBlockList() {
        let container = document.getElementById('blockPickerContent');
        if (!container) return;

        let blocks = blockPickerData.blocks;
        let searchTerm = blockPickerData.searchTerm.toLowerCase();
        let categoryId = blockPickerData.selectedCategory;

        let filteredBlocks = blocks.filter(function(block) {
            let matchesSearch = !searchTerm ||
                block.name.toLowerCase().indexOf(searchTerm) !== -1 ||
                (block.slug && block.slug.toLowerCase().indexOf(searchTerm) !== -1) ||
                (block.description && block.description.toLowerCase().indexOf(searchTerm) !== -1);
            let matchesCategory = !categoryId ||
                (categoryId === 'uncategorized' ? !block.category_id : block.category_id == categoryId);
            return matchesSearch && matchesCategory;
        });

        // Filter global blocks by search and category
        let globalBlocks = blockPickerData.globalBlocks || [];
        if (searchTerm) {
            globalBlocks = globalBlocks.filter(function(gb) {
                return gb.name.toLowerCase().indexOf(searchTerm) !== -1 ||
                    gb.block_name.toLowerCase().indexOf(searchTerm) !== -1;
            });
        }
        if (categoryId) {
            globalBlocks = globalBlocks.filter(function(gb) {
                return categoryId === 'uncategorized' ? !gb.category_id : gb.category_id == categoryId;
            });
        }

        if (filteredBlocks.length === 0 && globalBlocks.length === 0) {
            container.innerHTML = '<div class="block-picker-empty"><i class="fa fa-cube fa-2x"></i>No blocks found</div>';
            return;
        }

        // Group by category
        let grouped = {};
        let uncategorized = [];

        filteredBlocks.forEach(function(block) {
            if (block.category_id && block.category_name) {
                if (!grouped[block.category_name]) grouped[block.category_name] = [];
                grouped[block.category_name].push(block);
            } else {
                uncategorized.push(block);
            }
        });

        let html = '';

        Object.keys(grouped).sort().forEach(function(categoryName) {
            html += '<div class="block-picker-category-group">';
            html += '<div class="block-picker-category-title">' + escapeHtml(categoryName) + '</div>';
            html += '<div class="block-picker-grid">';
            grouped[categoryName].forEach(function(block) {
                html += buildBlockItem(block);
            });
            html += '</div></div>';
        });

        if (uncategorized.length > 0) {
            html += '<div class="block-picker-category-group">';
            html += '<div class="block-picker-category-title">Uncategorized</div>';
            html += '<div class="block-picker-grid">';
            uncategorized.forEach(function(block) {
                html += buildBlockItem(block);
            });
            html += '</div></div>';
        }

        if (globalBlocks.length > 0) {
            html += '<div class="block-picker-category-group block-picker-global-group">';
            html += '<div class="block-picker-category-title"><i class="fa fa-globe"></i> Global Blocks (Synced)</div>';
            html += '<div class="block-picker-grid">';
            globalBlocks.forEach(function(gb) {
                html += buildGlobalBlockItem(gb);
            });
            html += '</div></div>';
        }

        container.innerHTML = html;

        // Bind click events
        container.querySelectorAll('.block-picker-item[data-block-id]').forEach(function(el) {
            el.addEventListener('click', function() {
                addBlock(this.getAttribute('data-block-id'));
            });
        });

        container.querySelectorAll('.block-picker-item[data-global-block-id]').forEach(function(el) {
            el.addEventListener('click', function() {
                addGlobalBlock(this.getAttribute('data-global-block-id'));
            });
        });

        // Bind hover events for live iframe preview tooltips
        container.querySelectorAll('[data-preview-url]').forEach(function(el) {
            el.addEventListener('mouseenter', function(e) {
                showBlockPreviewTooltip(this.getAttribute('data-preview-url'), e);
            });
            el.addEventListener('mouseleave', function() {
                hideBlockPreviewTooltip();
            });
        });
    }

    function buildBlockItem(block) {
        let previewAttr = block.has_template ? ' data-preview-url="/admin/blocks/' + block.id + '/preview"' : '';
        return '<div class="block-picker-item" data-block-id="' + block.id + '"' + previewAttr + '>'
            + '<div class="block-picker-item-header">'
            + '<div class="block-picker-item-icon"><i class="fa ' + (block.icon || 'fa-cube') + '"></i></div>'
            + '<div class="block-picker-item-name">' + escapeHtml(block.name) + '</div>'
            + '</div>'
            + (block.description ? '<div class="block-picker-item-desc">' + escapeHtml(block.description) + '</div>' : '')
            + '<div class="block-picker-item-meta">' + block.field_count + ' field(s)</div>'
            + '</div>';
    }

    function buildGlobalBlockItem(gb) {
        let previewAttr = gb.has_template ? ' data-preview-url="/admin/blocks/data/' + gb.id + '/preview"' : '';
        return '<div class="block-picker-item block-picker-item--global" data-global-block-id="' + gb.id + '"' + previewAttr + '>'
            + '<div class="block-picker-item-header">'
            + '<div class="block-picker-item-icon"><i class="fa ' + (gb.icon || 'fa-globe') + '"></i></div>'
            + '<div class="block-picker-item-name">' + escapeHtml(gb.name) + '</div>'
            + '<span class="block-picker-item-badge">Synced</span>'
            + '</div>'
            + '<div class="block-picker-item-desc">' + escapeHtml(gb.block_name) + '</div>'
            + (gb.category_name ? '<div class="block-picker-item-meta">' + escapeHtml(gb.category_name) + '</div>' : '')
            + '</div>';
    }

    function addBlock(blockId) {
        closeDialog();

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

        fetch(ctx.addUrl, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: formData
        })
        .then(function(response) { return response.json(); })
        .then(function(result) {
            if (result && result.success) {
                if (result.edit_url) {
                    window.location.href = result.edit_url;
                } else {
                    reloadEntityBlocks();
                }
            } else {
                alert(result ? (result.error || 'Failed to add block') : 'Failed to add block');
            }
        })
        .catch(function(error) {
            console.error('Failed to add block:', error);
            alert('Failed to add block. Please try again.');
        });
    }

    function addGlobalBlock(globalBlockId) {
        closeDialog();

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

        fetch(ctx.addGlobalUrl, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: formData
        })
        .then(function(response) { return response.json(); })
        .then(function(result) {
            if (result && result.success) {
                reloadEntityBlocks();
            } else {
                alert(result ? (result.error || 'Failed to add global block') : 'Failed to add global block');
            }
        })
        .catch(function(error) {
            console.error('Failed to add global block:', error);
            alert('Failed to add global block. Please try again.');
        });
    }

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

        fetch(ctx.entityBlocksHtmlUrl + '?' + params.toString())
        .then(function(response) { return response.text(); })
        .then(function(html) {
            let fieldset = document.querySelector('.entityBlocksFieldset');
            if (fieldset) {
                let temp = document.createElement('div');
                temp.innerHTML = html;
                fieldset.replaceWith(temp.firstElementChild);
            }
        })
        .catch(function(error) {
            console.error('Failed to reload blocks:', error);
            window.location.reload();
        });
    }

    // Block preview tooltip (live iframe)
    let blockPreviewTooltip = null;
    let blockPreviewHoverTimer = null;

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

        let target = e.currentTarget;
        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);

            // Position to the right of the hovered card
            let x = rect.right + 12;
            let y = rect.top;

            // If it would overflow right, show to the left
            if (x + 420 > window.innerWidth) {
                x = rect.left - 420 - 12;
            }
            // Keep within vertical bounds
            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 the "Add New Block" button
    document.addEventListener('click', function(e) {
        let btn = e.target.closest('.add-block-from-registry-btn');
        if (btn) {
            e.preventDefault();
            openBlockPicker();
        }
    });

    // Template picker is handled by block-registry-entity-blocks.js (loaded for all entity types)

})();
