@php
    $fields = $fields ?? old('fields', []);
    if ($fields === null) {
        $fields = [];
    }
@endphp
<div class="space-y-3" id="form-field-builder">
    <div class="flex items-center justify-between">
        <p class="text-sm font-medium text-slate-700">Form fields</p>
        <button type="button" id="add-form-field" class="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50">Add field</button>
    </div>
    <div id="form-fields-list" class="space-y-3">
        @foreach($fields as $index => $field)
            @include('forms.partials.field-row', ['index' => $index, 'field' => $field])
        @endforeach
    </div>
    <p class="text-xs text-slate-500">For select fields, enter comma-separated options.</p>
</div>

<template id="form-field-row-template">
    @include('forms.partials.field-row', ['index' => '__INDEX__', 'field' => []])
</template>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const list = document.getElementById('form-fields-list');
    const addBtn = document.getElementById('add-form-field');
    const template = document.getElementById('form-field-row-template');
    if (!list || !addBtn || !template) return;

    function initSelect2(root) {
        if (!window.jQuery || !window.jQuery.fn || !window.jQuery.fn.select2) {
            return;
        }

        window.jQuery(root).find('.js-select2').each(function () {
            const $select = window.jQuery(this);
            if ($select.data('select2')) return;

            const inlineWidth = $select[0].style.width;
            const inlineMinWidth = $select[0].style.minWidth;

            $select.select2({
                width: inlineWidth ? 'style' : '100%',
                minimumResultsForSearch: Infinity
            });

            const $container = $select.next('.select2-container');
            $container.addClass('site-select2');

            if ($select.hasClass('text-xs')) {
                $container.addClass('site-select2-xs');
            }
            if (inlineMinWidth) {
                $container.css('min-width', inlineMinWidth);
            }
        });
    }

    initSelect2(list);

    let nextIndex = list.querySelectorAll('[data-field-row]').length;

    addBtn.addEventListener('click', function () {
        const html = template.innerHTML.replaceAll('__INDEX__', String(nextIndex));
        const wrapper = document.createElement('div');
        wrapper.innerHTML = html.trim();
        const row = wrapper.firstElementChild;
        list.appendChild(row);
        initSelect2(row);
        nextIndex++;
    });

    list.addEventListener('click', function (event) {
        const btn = event.target.closest('[data-remove-field]');
        if (!btn) return;
        const row = btn.closest('[data-field-row]');
        if (row) row.remove();
    });
});
</script>
@endpush
