/**
 * Block Template Edit — two-panel item selector with drag reorder.
 * Items are typed: 'block' (a BlockRegistry definition) or 'global' (a global
 * EntityBlock reference). Order is preserved across both types.
 */
(function() {
    const availableList = document.getElementById('availableBlocksList');
    const selectedList = document.getElementById('selectedBlocksList');
    const itemsContainer = document.getElementById('blockItemsContainer');
    const searchInput = document.getElementById('blockTemplateSearch');
    const countBadge = document.getElementById('selectedBlockCount');
    const emptyMsg = document.getElementById('selectedBlocksEmpty');
    const form = document.getElementById('blockTemplateForm');

    if (!availableList || !selectedList) return;

    let selectedItems = [];

    if (window.blockTemplateExistingItems && window.blockTemplateExistingItems.length > 0) {
        window.blockTemplateExistingItems.forEach(function(item) {
            const type = item.type === 'global' ? 'global' : 'block';
            addItemToSelected(type, item.id, item.name, item.icon, true);
        });
        updateState();
    }

    availableList.addEventListener('click', function(e) {
        const item = e.target.closest('.block-template-available-item');
        if (!item) return;

        const type = item.getAttribute('data-item-type') || 'block';
        const id = parseInt(item.getAttribute('data-item-id'), 10);
        const name = item.getAttribute('data-block-name');
        const icon = item.getAttribute('data-block-icon');

        if (isSelected(type, id)) return;

        addItemToSelected(type, id, name, icon, false);
        updateState();
    });

    function isSelected(type, id) {
        return selectedItems.some(function(it) {
            return it.type === type && it.id === id;
        });
    }

    function addItemToSelected(type, id, name, icon, skipUpdate) {
        selectedItems.push({ type: type, id: id });

        const el = document.createElement('div');
        el.className = 'block-template-selected-item' + (type === 'global' ? ' is-global' : '');
        el.setAttribute('data-item-type', type);
        el.setAttribute('data-item-id', id);

        const safeIcon = escapeHtml(icon || (type === 'global' ? 'fa-globe' : 'fa-cube'));
        const safeName = escapeHtml(name || (type === 'global' ? 'Global Block' : 'Block'));
        const badge = type === 'global'
            ? '<span class="block-template-type-badge" title="Global block reference"><i class="fa fa-globe"></i> Global</span>'
            : '';

        el.innerHTML = '<span class="drag-handle"><i class="fa fa-bars"></i></span>'
            + '<i class="fa ' + safeIcon + '"></i> '
            + '<span class="block-template-selected-name">' + safeName + '</span>'
            + badge
            + '<button type="button" class="block-template-remove-btn" title="Remove"><i class="fa fa-times"></i></button>';

        el.querySelector('.block-template-remove-btn').addEventListener('click', function() {
            const t = el.getAttribute('data-item-type');
            const i = parseInt(el.getAttribute('data-item-id'), 10);
            selectedItems = selectedItems.filter(function(it) {
                return !(it.type === t && it.id === i);
            });
            el.remove();
            updateState();
        });

        selectedList.appendChild(el);
    }

    function updateState() {
        countBadge.textContent = selectedItems.length;

        if (emptyMsg) {
            emptyMsg.style.display = selectedItems.length > 0 ? 'none' : '';
        }

        availableList.querySelectorAll('.block-template-available-item').forEach(function(item) {
            const t = item.getAttribute('data-item-type') || 'block';
            const i = parseInt(item.getAttribute('data-item-id'), 10);
            if (isSelected(t, i)) {
                item.classList.add('is-selected');
            } else {
                item.classList.remove('is-selected');
            }
        });

        updateHiddenInputs();
    }

    function updateHiddenInputs() {
        itemsContainer.innerHTML = '';
        const rows = selectedList.querySelectorAll('.block-template-selected-item');
        selectedItems = [];
        rows.forEach(function(row, index) {
            const type = row.getAttribute('data-item-type') || 'block';
            const id = parseInt(row.getAttribute('data-item-id'), 10);
            selectedItems.push({ type: type, id: id });

            const typeInput = document.createElement('input');
            typeInput.type = 'hidden';
            typeInput.name = 'items[' + index + '][type]';
            typeInput.value = type;
            itemsContainer.appendChild(typeInput);

            const idInput = document.createElement('input');
            idInput.type = 'hidden';
            idInput.name = 'items[' + index + '][id]';
            idInput.value = id;
            itemsContainer.appendChild(idInput);
        });
    }

    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const term = this.value.toLowerCase();
            const currentHeaders = {};

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

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

    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') {
        const 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();
    }

    if (form) {
        form.addEventListener('submit', function() {
            updateHiddenInputs();
        });
    }

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