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;

    // Refresh visibility selects (available controllers may have changed)
    initVisibilitySelects();
}

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

// --- Conditional visibility settings ---

function initVisibilitySelects() {
    // Collect all top-level select-type fields (potential controllers)
    let selectFields = [];
    document.querySelectorAll('#fieldsList > .field-item').forEach(function(item) {
        let nameInput = item.querySelector('input[name^="field_name"]');
        let typeSelect = item.querySelector('select[name^="field_type"]');
        if (nameInput && typeSelect && typeSelect.value === 'select') {
            selectFields.push(nameInput.value);
        }
    });

    // Populate all visibility-field-select dropdowns
    document.querySelectorAll('.visibility-field-select').forEach(function(select) {
        let savedValue = select.dataset.value || '';
        let currentValue = select.value || savedValue;

        // Get the field name this select belongs to (to exclude self)
        let fieldItem = select.closest('.field-item');
        let ownName = '';
        if (fieldItem) {
            let nameInput = fieldItem.querySelector('input[name^="field_name"]');
            if (nameInput) ownName = nameInput.value;
        }

        // Clear existing options except first
        while (select.options.length > 1) {
            select.remove(1);
        }

        // Add select-type fields as options
        selectFields.forEach(function(name) {
            if (name && name !== ownName) {
                let option = document.createElement('option');
                option.value = name;
                option.textContent = name;
                if (name === currentValue) option.selected = true;
                select.appendChild(option);
            }
        });

        // If value was restored, trigger values population
        if (select.value) {
            updateVisibilityValues(select);
        }
    });
}

function updateVisibilityValues(selectEl) {
    let container = selectEl.closest('.visibility-settings');
    let valuesRow = container.querySelector('.visibility-values-row');
    let checkboxesDiv = container.querySelector('.visibility-values-checkboxes');
    let hiddenInput = container.querySelector('.visibility-values-hidden');

    if (!selectEl.value) {
        valuesRow.style.display = 'none';
        checkboxesDiv.innerHTML = '';
        return;
    }

    // Find the controller field's options textarea
    let controllerOptions = '';
    document.querySelectorAll('#fieldsList > .field-item').forEach(function(item) {
        let nameInput = item.querySelector('input[name^="field_name"]');
        if (nameInput && nameInput.value === selectEl.value) {
            let optionsTextarea = item.querySelector('textarea[name^="field_options"]');
            if (optionsTextarea) controllerOptions = optionsTextarea.value;
        }
    });

    if (!controllerOptions.trim()) {
        valuesRow.style.display = 'none';
        checkboxesDiv.innerHTML = '<small>Selected field has no options defined</small>';
        valuesRow.style.display = '';
        return;
    }

    // Parse options and build checkboxes via safe DOM APIs (values/labels are admin-authored but untrusted for HTML)
    let savedValues = (hiddenInput.value || '').split(',').filter(Boolean);
    let lines = controllerOptions.split('\n').filter(Boolean);

    checkboxesDiv.innerHTML = '';
    lines.forEach(function(line) {
        let parts = line.split('|');
        let value = parts[0].trim();
        let label = (parts[1] || parts[0]).trim();

        let labelEl = document.createElement('label');
        let cb = document.createElement('input');
        cb.type = 'checkbox';
        cb.value = value;
        cb.checked = savedValues.indexOf(value) !== -1;
        cb.addEventListener('change', function() { syncVisibilityHidden(cb); });
        labelEl.appendChild(cb);
        labelEl.appendChild(document.createTextNode(' ' + label));
        checkboxesDiv.appendChild(labelEl);
    });
    valuesRow.style.display = '';
}

function syncVisibilityHidden(checkbox) {
    let container = checkbox.closest('.visibility-settings');
    let hiddenInput = container.querySelector('.visibility-values-hidden');
    let checkboxes = container.querySelectorAll('.visibility-values-checkboxes input[type="checkbox"]');
    let values = [];
    checkboxes.forEach(function(cb) {
        if (cb.checked) values.push(cb.value);
    });
    hiddenInput.value = values.join(',');
}

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

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

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

