let fieldIndex = parseInt(document.getElementById('fieldsList').dataset.fieldCount) || 0;

function addField() {
    let template = document.getElementById('fieldTemplate').innerHTML;
    template = template.replace(/__INDEX__/g, fieldIndex);
    fieldIndex++;

    let container = document.getElementById('fieldsList');
    let div = document.createElement('div');
    div.innerHTML = template;
    container.appendChild(div.firstElementChild);
}

function removeField(btn) {
    if (confirm('Remove this field?')) {
        btn.closest('.field-item').remove();
    }
}

function toggleField(header) {
    header.closest('.field-item').classList.toggle('collapsed');
}

function updateFieldOptions(select) {
    let fieldItem = select.closest('.field-item');
    let optionsRow = fieldItem.querySelector('.field-options-row');
    let repeaterSettings = fieldItem.querySelector('.repeater-settings');
    let imageSettings = fieldItem.querySelector('.image-settings');

    // Show/hide options row for select/radio/checkbox types
    let showOptions = ['select', 'radio', 'checkbox'].indexOf(select.value) !== -1;
    optionsRow.style.display = showOptions ? '' : 'none';

    // Show/hide repeater settings for repeater type
    if (repeaterSettings) {
        repeaterSettings.style.display = select.value === 'repeater' ? '' : 'none';
    }

    // Show/hide image settings for image type
    if (imageSettings) {
        imageSettings.style.display = select.value === 'image' ? '' : 'none';
    }

    // Show/hide page selector settings
    let pageSelectorSettings = fieldItem.querySelector('.page-selector-settings');
    if (pageSelectorSettings) {
        pageSelectorSettings.style.display = select.value === 'page_selector' ? '' : 'none';
    }

    // Update type badge
    let badge = fieldItem.querySelector('.field-type-badge');
    badge.textContent = select.value;
}

function toggleCropSettings(checkbox) {
    let detailSection = checkbox.closest('.image-settings').querySelector('.crop-settings-detail');
    if (detailSection) {
        detailSection.style.display = checkbox.checked ? '' : 'none';
    }
}

function toggleCustomRatio(select) {
    let customRow = select.closest('.crop-settings-detail').querySelector('.custom-ratio-row');
    if (customRow) {
        customRow.style.display = select.value === 'custom' ? '' : 'none';
        if (select.value !== 'custom') {
            let customInput = customRow.querySelector('input');
            if (customInput) {
                customInput.value = '';
            }
        }
    }
}

function addSubField(btn, parentIndex) {
    let template = document.getElementById('subFieldTemplate').innerHTML;
    template = template.replace(/__PARENT_INDEX__/g, parentIndex);

    let container = btn.closest('.sub-fields-section').querySelector('.sub-fields-list');
    let div = document.createElement('div');
    div.innerHTML = template;
    container.appendChild(div.firstElementChild);
}

function removeSubField(btn) {
    if (confirm('Remove this sub-field?')) {
        btn.closest('.sub-field-item').remove();
    }
}

function toggleSubField(header) {
    let item = header.closest('.sub-field-item');
    item.classList.toggle('collapsed');
}

function updateSubFieldOptions(select) {
    let subFieldItem = select.closest('.sub-field-item');
    let optionsRow = subFieldItem.querySelector('.field-options-row');
    let imageSettings = subFieldItem.querySelector('.image-settings');
    let badge = subFieldItem.querySelector('.sub-field-type-badge');

    // Show/hide options for select/radio/checkbox
    if (optionsRow) {
        let showOptions = ['select', 'radio', 'checkbox'].indexOf(select.value) !== -1;
        optionsRow.style.display = showOptions ? '' : 'none';
    }

    // Show/hide image settings for image type
    if (imageSettings) {
        imageSettings.style.display = select.value === 'image' ? '' : 'none';
    }

    // Update type badge
    if (badge) {
        badge.textContent = select.value;
    }
}

// Update field title and hidden label when name changes
document.getElementById('fieldsList').addEventListener('input', function(e) {
    if (e.target.name === 'field_name[]') {
        let item = e.target.closest('.field-item');
        let nameInput = item.querySelector('input[name="field_name[]"]');
        let labelInput = item.querySelector('input[name="field_label[]"]');
        let title = item.querySelector('.field-title');
        title.textContent = nameInput.value || 'New Field';
        labelInput.value = nameInput.value; // Keep label in sync with name
    }
    // Also sync sub-field name to label and header title
    if (e.target.name === 'subfield_name[]') {
        let subItem = e.target.closest('.sub-field-item');
        let labelInput = subItem.querySelector('input[name="subfield_label[]"]');
        let titleSpan = subItem.querySelector('.sub-field-title');
        labelInput.value = e.target.value;
        if (titleSpan) titleSpan.textContent = e.target.value || 'New Sub-field';
    }
});

// Drag and drop functionality for fields (uses shared handler from block-registry-drag.js)
let fieldDragDrop = createDragDropHandler('.field-item', function() {
    reindexFields();
});

function initFieldDragDrop() {
    let container = document.getElementById('fieldsList');
    fieldDragDrop.init(container);
}

function makeFieldsDraggable() {
    let container = document.getElementById('fieldsList');
    if (container) {
        fieldDragDrop.makeDraggable(container);
    }
}

function reindexFields() {
    let container = document.getElementById('fieldsList');
    let fields = container.querySelectorAll('.field-item');

    fields.forEach(function(field, index) {
        field.setAttribute('data-index', index);
        // Update order index hidden input if it exists
        let orderInput = field.querySelector('input[name="field_order[]"]');
        if (orderInput) {
            orderInput.value = index;
        }

        // Update subfield_parent_index values for any sub-fields in this field
        let subFieldParentInputs = field.querySelectorAll('input[name="subfield_parent_index[]"]');
        subFieldParentInputs.forEach(function(input) {
            input.value = index;
        });

        // Update data-parent-index on sub-fields list
        let subFieldsList = field.querySelector('.sub-fields-list');
        if (subFieldsList) {
            subFieldsList.setAttribute('data-parent-index', index);
        }

        // Update addSubField button onclick parameter
        let addSubFieldBtn = field.querySelector('.btn-add-subfield');
        if (addSubFieldBtn) {
            addSubFieldBtn.setAttribute('onclick', 'addSubField(this, ' + index + ')');
        }
    });
}

function togglePageSelectorMode(select) {
    let settings = select.closest('.page-selector-settings');
    let limitRow = settings.querySelector('.page-selector-limit-row');
    if (limitRow) {
        limitRow.style.display = select.value === 'auto' ? '' : 'none';
    }
}

function loadListingContainers() {
    let selects = document.querySelectorAll('.page-selector-container-select');
    if (selects.length === 0) return;

    fetch('/admin/blocks/ajax/listing-containers', { credentials: 'same-origin' })
        .then(function(r) { return r.json(); })
        .then(function(containers) {
            selects.forEach(function(select) {
                let currentValue = select.dataset.value || '';
                containers.forEach(function(c) {
                    let option = document.createElement('option');
                    option.value = c.id;
                    option.textContent = c.title;
                    if (String(c.id) === String(currentValue)) {
                        option.selected = true;
                    }
                    select.appendChild(option);
                });
            });
        });
}

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', function() {
    initFieldDragDrop();
    loadListingContainers();

    // Re-initialize after adding new fields
    let addFieldBtn = document.querySelector('.btn-add-field');
    if (addFieldBtn) {
        let originalAddField = window.addField;
        window.addField = function() {
            originalAddField();
            makeFieldsDraggable();
        };
    }

    // Confirmation alert for Update Block button
    let instanceCount = parseInt(document.getElementById('blockForm').dataset.instanceCount) || 0;
    if (instanceCount > 0) {
        document.getElementById('blockForm').addEventListener('submit', function(e) {
            if (!confirm('This will affect ' + instanceCount + ' block instance(s). Are you sure you want to update?')) {
                e.preventDefault();
            }
        });
    }
});

