/**
 * Block Template Edit — two-panel block selector with drag reorder
 */
(function() {
    const availableList = document.getElementById('availableBlocksList');
    const selectedList = document.getElementById('selectedBlocksList');
    const blockIdsContainer = document.getElementById('blockIdsContainer');
    const searchInput = document.getElementById('blockTemplateSearch');
    const countBadge = document.getElementById('selectedBlockCount');
    const emptyMsg = document.getElementById('selectedBlocksEmpty');
    const form = document.getElementById('blockTemplateForm');

    if (!availableList || !selectedList) return;

    // Track selected block IDs (ordered)
    let selectedBlocks = [];

    // Load existing items on edit
    if (window.blockTemplateExistingItems && window.blockTemplateExistingItems.length > 0) {
        window.blockTemplateExistingItems.forEach(function(item) {
            addBlockToSelected(item.id, item.name, item.icon, true);
        });
        updateState();
    }

    // Add block click handler
    availableList.addEventListener('click', function(e) {
        let addBtn = e.target.closest('.block-template-add-btn');
        let item = e.target.closest('.block-template-available-item');
        if (!item) return;

        let blockId = parseInt(item.getAttribute('data-block-id'));
        let blockName = item.getAttribute('data-block-name');
        let blockIcon = item.getAttribute('data-block-icon');

        // Don't add duplicates
        if (selectedBlocks.indexOf(blockId) !== -1) {
            return;
        }

        addBlockToSelected(blockId, blockName, blockIcon, false);
        updateState();
    });

    function addBlockToSelected(blockId, blockName, blockIcon, skipUpdate) {
        selectedBlocks.push(blockId);

        let el = document.createElement('div');
        el.className = 'block-template-selected-item';
        el.setAttribute('data-block-id', blockId);
        el.innerHTML = '<span class="drag-handle"><i class="fa fa-bars"></i></span>'
            + '<i class="fa ' + escapeHtml(blockIcon) + '"></i> '
            + '<span class="block-template-selected-name">' + escapeHtml(blockName) + '</span>'
            + '<button type="button" class="block-template-remove-btn" title="Remove"><i class="fa fa-times"></i></button>';

        // Remove button handler
        el.querySelector('.block-template-remove-btn').addEventListener('click', function() {
            let id = parseInt(el.getAttribute('data-block-id'));
            selectedBlocks = selectedBlocks.filter(function(b) { return b !== id; });
            el.remove();
            updateState();
        });

        selectedList.appendChild(el);
    }

    function updateState() {
        // Update count
        countBadge.textContent = selectedBlocks.length;

        // Show/hide empty message
        if (emptyMsg) {
            emptyMsg.style.display = selectedBlocks.length > 0 ? 'none' : '';
        }

        // Mark available items that are already selected
        availableList.querySelectorAll('.block-template-available-item').forEach(function(item) {
            let blockId = parseInt(item.getAttribute('data-block-id'));
            if (selectedBlocks.indexOf(blockId) !== -1) {
                item.classList.add('is-selected');
            } else {
                item.classList.remove('is-selected');
            }
        });

        // Update hidden inputs
        updateHiddenInputs();
    }

    function updateHiddenInputs() {
        blockIdsContainer.innerHTML = '';
        // Read order from DOM (in case of drag reorder)
        let items = selectedList.querySelectorAll('.block-template-selected-item');
        selectedBlocks = [];
        items.forEach(function(item) {
            let blockId = parseInt(item.getAttribute('data-block-id'));
            selectedBlocks.push(blockId);
            let input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'block_ids[]';
            input.value = blockId;
            blockIdsContainer.appendChild(input);
        });
    }

    // Search filter
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            let term = this.value.toLowerCase();
            let currentHeaders = {};

            availableList.querySelectorAll('.block-template-available-item').forEach(function(item) {
                let name = item.getAttribute('data-block-name').toLowerCase();
                let cat = item.getAttribute('data-category').toLowerCase();
                let visible = !term || name.indexOf(term) !== -1 || cat.indexOf(term) !== -1;
                item.style.display = visible ? '' : 'none';
                if (visible) {
                    currentHeaders[item.getAttribute('data-category')] = true;
                }
            });

            // Show/hide category headers
            availableList.querySelectorAll('.block-template-category-header').forEach(function(header) {
                let cat = header.getAttribute('data-category');
                header.style.display = currentHeaders[cat] ? '' : 'none';
            });
        });
    }

    // Load SortableJS for reorder
    function initSortable() {
        if (typeof Sortable === 'undefined') return;

        new Sortable(selectedList, {
            handle: '.drag-handle',
            animation: 150,
            ghostClass: 'sortable-ghost',
            draggable: '.block-template-selected-item',
            onEnd: function() {
                updateHiddenInputs();
            }
        });
    }

    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;
        document.head.appendChild(script);
    } else {
        initSortable();
    }

    // Ensure hidden inputs are up-to-date on form submit
    if (form) {
        form.addEventListener('submit', function() {
            updateHiddenInputs();
        });
    }

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