/**
 * Block Picker - Opens a dialog to select blocks from the Block Registry
 * Part of the Block Registry module for ACF-style block management
 */
(function() {
'use strict';

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

function openBlockPicker() {
    if (busyLoading()) {
        return false;
    }

    let page_id = getPageId("sandbox");
    if (!page_id) {
        alert("Please save the page first before adding blocks.");
        return false;
    }

    blockPickerData.loading = true;

    let dialogContent = buildBlockPickerDialog();
    $('#dialog').html(dialogContent);
    $('#dialog').dialog('option', 'title', 'Add Block from Registry');
    $('#dialog').dialog('option', 'width', '700px');
    $('#dialog').dialog('option', 'buttons', {
        Cancel: function() {
            $(this).dialog('close');
        }
    });
    $("#dialog").dialog('open');

    // Load available blocks
    loadAvailableBlocks();

    return false;
}

function buildBlockPickerDialog() {
    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 page_id = getPageId("sandbox");

    $.ajax({
        type: 'get',
        url: '/admin/blocks/ajax/entity/available',
        dataType: 'json',
        data: {
            entity_type: 'page',
            entity_id: page_id,
            search: blockPickerData.searchTerm,
            category_id: blockPickerData.selectedCategory
        },
        cache: false,
        timeout: content_manager.timeout_limit
    })
    .done(function(result) {
        blockPickerData.blocks = result.blocks || [];
        blockPickerData.categories = result.categories || [];
        blockPickerData.globalBlocks = result.global_blocks || [];
        blockPickerData.loading = false;
        renderBlockPicker();
    })
    .fail(function(jq_xhr, text_status, error_thrown) {
        console.log('Block picker AJAX failed:', text_status, error_thrown, jq_xhr.responseText);
        blockPickerData.loading = false;
        $('#blockPickerContent').html('<div class="block-picker-empty">Failed to load blocks: ' + text_status + '</div>');
    });
}

function renderBlockPicker() {
    // Update category dropdown
    let categorySelect = $('#blockPickerCategory');
    categorySelect.find('option:not(:first)').remove();
    blockPickerData.categories.forEach(function(cat) {
        categorySelect.append('<option value="' + cat.id + '">' + escapeHtml(cat.name) + '</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));
            categorySelect.append('<option value="' + gb.category_id + '">' + escapeHtml(gb.category_name) + '</option>');
        }
    });

    // 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) {
        categorySelect.append('<option value="uncategorized">Uncategorized</option>');
    }

    // Bind events
    $('#blockPickerSearch').off('input').on('input', function() {
        blockPickerData.searchTerm = $(this).val();
        filterBlocks();
    });

    $('#blockPickerCategory').off('change').on('change', function() {
        blockPickerData.selectedCategory = $(this).val() || null;
        filterBlocks();
    });

    // Render blocks
    renderBlockList();
}

function filterBlocks() {
    renderBlockList();
}

function renderBlockList() {
    let container = $('#blockPickerContent');
    let blocks = blockPickerData.blocks;

    // Apply filters
    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.html('<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 = '';

    // Render categorized blocks
    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>';
        html += '</div>';
    });

    // Render uncategorized blocks
    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>';
        html += '</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>';
        html += '</div>';
    }

    container.html(html);

    // Bind click events for regular blocks
    container.find('.block-picker-item[data-block-id]').on('click', function() {
        let blockId = $(this).data('block-id');
        addBlockFromRegistry(blockId);
    });

    // Bind click events for global blocks
    container.find('.block-picker-item[data-global-block-id]').on('click', function() {
        let globalBlockId = $(this).data('global-block-id');
        addGlobalBlockToPage(globalBlockId);
    });

    // Bind hover events for live iframe preview tooltips
    container.find('[data-preview-url]').on('mouseenter', function(e) {
        showBlockPreviewTooltip($(this).data('preview-url'), e);
    }).on('mouseleave', function() {
        hideBlockPreviewTooltip();
    });
}

function buildPickerCard(opts) {
    let previewAttr = opts.previewUrl ? ' data-preview-url="' + escapeHtml(opts.previewUrl) + '"' : '';
    let html = '<div class="block-picker-item ' + (opts.extraClass || '') + '" data-' + opts.dataAttr + '="' + opts.dataValue + '"' + previewAttr + '>';
    html += '<div class="block-picker-item-header">';
    html += '<div class="block-picker-item-icon"' + (opts.iconStyle ? ' style="' + opts.iconStyle + '"' : '') + '><i class="fa ' + opts.iconClass + '"></i></div>';
    html += '<div class="block-picker-item-name">' + escapeHtml(opts.name) + '</div>';
    if (opts.badge) {
        html += '<span class="block-picker-item-badge"' + (opts.badgeStyle ? ' style="' + opts.badgeStyle + '"' : '') + '>' + opts.badge + '</span>';
    }
    html += '</div>';
    if (opts.desc) {
        html += '<div class="block-picker-item-desc">' + escapeHtml(opts.desc) + '</div>';
    }
    if (opts.meta) {
        html += '<div class="block-picker-item-meta">' + opts.meta + '</div>';
    }
    html += '</div>';
    return html;
}

function buildBlockItem(block) {
    return buildPickerCard({
        dataAttr: 'block-id',
        dataValue: block.id,
        iconClass: block.icon || 'fa-cube',
        name: block.name,
        badge: block.is_default ? 'Default' : '',
        badgeStyle: block.is_default ? 'background:#28a745;' : '',
        desc: block.description,
        meta: block.field_count + ' field(s)',
        previewUrl: block.has_template ? '/admin/blocks/' + block.id + '/preview' : null,
    });
}

function addBlockFromRegistry(blockId) {
    ldrPending("Adding block...");
    $('#dialog').dialog('close');

    $.ajax({
        type: 'post',
        url: '/admin/blocks/ajax/entity/add',
        dataType: 'json',
        data: {
            entity_type: 'page',
            entity_id: getPageId("sandbox"),
            block_id: blockId
        },
        cache: false,
        timeout: content_manager.timeout_limit
    })
    .done(function(result) {
        if (result && result.success) {
            ldrSuccess(result.message);
            // Redirect to edit the block data
            if (result.edit_url) {
                window.location.href = result.edit_url;
            } else {
                // Fallback: reload the entity blocks section
                reloadEntityBlocks();
            }
        } else {
            ldrFailure(result ? (result.error || "Failed to add block") : "Failed to add block");
        }
    })
    .fail(function(jq_xhr, text_status, error_thrown) {
        console.error('Add block failed:', text_status, error_thrown, jq_xhr.responseText);
        ldrFailure("Failed to add block. Please try again.");
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        }
    });
}

function buildGlobalBlockItem(gb) {
    return buildPickerCard({
        dataAttr: 'global-block-id',
        dataValue: gb.id,
        extraClass: 'block-picker-item--global',
        iconClass: gb.icon || 'fa-globe',
        name: gb.name,
        badge: 'Synced',
        desc: gb.block_name,
        meta: gb.category_name ? escapeHtml(gb.category_name) : '',
        previewUrl: gb.has_template ? '/admin/blocks/data/' + gb.id + '/preview' : null,
    });
}

function addGlobalBlockToPage(globalBlockId) {
    ldrPending("Adding global block...");
    $('#dialog').dialog('close');

    $.ajax({
        type: 'post',
        url: '/admin/blocks/ajax/entity/add-global',
        dataType: 'json',
        data: {
            entity_type: 'page',
            entity_id: getPageId("sandbox"),
            global_block_id: globalBlockId
        },
        cache: false,
        timeout: content_manager.timeout_limit
    })
    .done(function(result) {
        if (result && result.success) {
            ldrSuccess(result.message);
            reloadEntityBlocks();
        } else {
            ldrFailure(result ? (result.error || "Failed to add global block") : "Failed to add global block");
        }
    })
    .fail(function(jq_xhr, text_status, error_thrown) {
        console.error('Add global block failed:', text_status, error_thrown);
        ldrFailure("Failed to add global block. Please try again.");
    });
}

function reloadEntityBlocks() {
    let page_id = getPageId("sandbox");
    if (!page_id) return;

    $.get('/admin/blocks/ajax/entity/blocks-html', { entity_type: 'page', entity_id: page_id }, function(html) {
        let $fieldset = $('.entityBlocksFieldset');
        if ($fieldset.length) {
            $fieldset.replaceWith(html);
        }
    });
}

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

// 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;
    }
}

// Expose functions needed by external scripts (panel-init.js)
window.openBlockPicker = openBlockPicker;

})();
