/**
 * ITSWEBER CMS – Contact Form Builder JS
 * F5 v3.3.0
 *
 * Manages the drag-and-drop field list, add/edit/delete field actions,
 * and serialises the final config to the hidden fields-JSON input.
 */
(function () {
    'use strict';

    var fieldList   = document.getElementById('cfFieldList');
    var fieldsJson  = document.getElementById('cfFieldsJson');
    var noFieldsHint = document.getElementById('cfNoFieldsHint');

    if (!fieldList || !fieldsJson) return; // not on builder tab

    // ── State ───────────────────────────────────────────────────────────
    /** @type {Array<Object>} */
    var fields = [];
    try {
        fields = JSON.parse(fieldsJson.value || '[]') || [];
    } catch (e) {
        fields = [];
    }

    // ── Sortable ────────────────────────────────────────────────────────
    if (window.Sortable) {
        Sortable.create(fieldList, {
            animation: 150,
            handle: '.cf-field-drag-handle',
            ghostClass: 'cf-sortable-ghost',
            onEnd: function () {
                syncStateFromDOM();
                updateJson();
            }
        });
    }

    // ── Helpers ─────────────────────────────────────────────────────────

    function uniqueId() {
        return 'field_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
    }

    function escHtml(str) {
        var d = document.createElement('div');
        d.appendChild(document.createTextNode(String(str || '')));
        return d.innerHTML;
    }

    function fieldTypeName(type) {
        var map = {
            'text':     'Text',
            'email':    'E-Mail',
            'tel':      'Telefon',
            'textarea': 'Textbereich',
            'select':   'Dropdown',
            'checkbox': 'Checkbox',
            'hidden':   'Versteckt'
        };
        return map[type] || type;
    }

    function buildFieldRow(f) {
        var row = document.createElement('div');
        row.className = 'cf-field-row';
        row.dataset.fieldId = f.id;
        row.innerHTML =
            '<div class="cf-field-drag-handle" title="Verschieben">' +
                '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="5" r="1.5"/><circle cx="15" cy="5" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/></svg>' +
            '</div>' +
            '<div class="cf-field-info">' +
                '<span class="cf-field-label">' + escHtml(f.label) + '</span>' +
                '<span class="cf-field-meta">' +
                    escHtml(fieldTypeName(f.type)) +
                    ' · ' + (f.width === 'half' ? 'Halb (50 %)' : 'Voll (100 %)') +
                    (f.required ? ' · <span class="badge badge-required">Pflicht</span>' : '') +
                '</span>' +
            '</div>' +
            '<div class="cf-field-actions">' +
                '<button type="button" class="btn btn-ghost btn-sm cf-edit-btn" title="Bearbeiten" data-field="">' +
                    '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>' +
                '</button>' +
                '<button type="button" class="btn btn-ghost btn-sm cf-delete-btn" title="Löschen" data-confirm="Feld unwiderruflich löschen?">' +
                    '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/></svg>' +
                '</button>' +
            '</div>';

        // Attach field data to edit button
        row.querySelector('.cf-edit-btn').dataset.field = JSON.stringify(f);
        return row;
    }

    function renderAll() {
        // Remove all existing field rows (keep hint)
        var existing = fieldList.querySelectorAll('.cf-field-row');
        existing.forEach(function (el) { el.remove(); });

        fields.forEach(function (f) {
            fieldList.appendChild(buildFieldRow(f));
        });

        noFieldsHint.style.display = fields.length === 0 ? '' : 'none';
        updateJson();
    }

    function syncStateFromDOM() {
        var rows = fieldList.querySelectorAll('.cf-field-row');
        var newOrder = [];
        rows.forEach(function (row) {
            var id = row.dataset.fieldId;
            var f  = fields.find(function (x) { return x.id === id; });
            if (f) newOrder.push(f);
        });
        fields = newOrder;
    }

    function updateJson() {
        fieldsJson.value = JSON.stringify(fields);
    }

    // ── Delegation: edit + delete ────────────────────────────────────────
    fieldList.addEventListener('click', function (e) {
        // Traverse from target upwards to find action buttons
        var btn = e.target.closest('.cf-edit-btn, .cf-delete-btn');
        if (!btn) return;

        e.preventDefault();
        e.stopPropagation();

        if (btn.classList.contains('cf-edit-btn')) {
            var field;
            try { field = JSON.parse(btn.dataset.field); } catch(_) { return; }
            openEditModal(field);
            return;
        }

        if (btn.classList.contains('cf-delete-btn')) {
            var msg = btn.dataset.confirm || 'Feld wirklich löschen?';
            if (!confirm(msg)) return;
            var row = btn.closest('.cf-field-row');
            var fid = row ? row.dataset.fieldId : null;
            if (fid) {
                fields = fields.filter(function (x) { return x.id !== fid; });
                row.remove();
                noFieldsHint.style.display = fields.length === 0 ? '' : 'none';
                updateJson();
            }
        }
    });

    // ── Add Field ────────────────────────────────────────────────────────
    var addBtn        = document.getElementById('cfAddFieldBtn');
    var newType       = document.getElementById('cfNewType');
    var newLabel      = document.getElementById('cfNewLabel');
    var newPlaceholder= document.getElementById('cfNewPlaceholder');
    var newOptions    = document.getElementById('cfNewOptions');
    var newValue      = document.getElementById('cfNewValue');
    var newWidth      = document.getElementById('cfNewWidth');
    var newRequired   = document.getElementById('cfNewRequired');
    var optionsGroup  = document.querySelector('.cf-options-group');
    var valueGroup    = document.querySelector('.cf-value-group');

    if (newType) {
        newType.addEventListener('change', function () {
            var t = this.value;
            if (optionsGroup) optionsGroup.style.display = t === 'select' ? '' : 'none';
            if (valueGroup)   valueGroup.style.display   = t === 'hidden' ? '' : 'none';
        });
    }

    if (addBtn) {
        addBtn.addEventListener('click', function () {
            var label = newLabel ? newLabel.value.trim() : '';
            var type  = newType  ? newType.value : 'text';
            if (!label && type !== 'hidden') {
                newLabel && newLabel.focus();
                return;
            }
            var f = {
                id:          uniqueId(),
                type:        type,
                label:       label || '—',
                placeholder: newPlaceholder ? newPlaceholder.value.trim() : '',
                required:    newRequired ? newRequired.checked : false,
                width:       newWidth ? newWidth.value : 'full'
            };
            if (type === 'select' && newOptions) {
                f.options = newOptions.value.trim();
            }
            if (type === 'hidden' && newValue) {
                f.value = newValue.value.trim();
            }

            fields.push(f);
            fieldList.appendChild(buildFieldRow(f));
            noFieldsHint.style.display = 'none';
            updateJson();

            // Reset inputs
            if (newLabel)       newLabel.value       = '';
            if (newPlaceholder) newPlaceholder.value = '';
            if (newOptions)     newOptions.value     = '';
            if (newValue)       newValue.value       = '';
            if (newRequired)    newRequired.checked  = false;
        });
    }

    // ── Edit Modal ───────────────────────────────────────────────────────
    var editModal        = document.getElementById('cfEditModal');
    var editFieldId      = document.getElementById('cfEditFieldId');
    var editType         = document.getElementById('cfEditType');
    var editLabel        = document.getElementById('cfEditLabel');
    var editPlaceholder  = document.getElementById('cfEditPlaceholder');
    var editOptions      = document.getElementById('cfEditOptions');
    var editValue        = document.getElementById('cfEditValue');
    var editWidth        = document.getElementById('cfEditWidth');
    var editRequired     = document.getElementById('cfEditRequired');
    var editSaveBtn      = document.getElementById('cfEditSaveBtn');
    var editCancelBtn    = document.getElementById('cfEditCancelBtn');
    var editModalClose   = document.getElementById('cfEditModalClose');
    var editOptGroup     = editModal ? editModal.querySelector('.cf-edit-options-group') : null;
    var editValGroup     = editModal ? editModal.querySelector('.cf-edit-value-group') : null;

    function openEditModal(f) {
        if (!editModal) return;
        editFieldId.value      = f.id;
        editType.value         = f.type || 'text';
        editLabel.value        = f.label || '';
        editPlaceholder.value  = f.placeholder || '';
        editRequired.checked   = !!f.required;
        editWidth.value        = f.width || 'full';
        if (editOptions) editOptions.value = f.options || '';
        if (editValue)   editValue.value   = f.value   || '';

        toggleEditExtras(f.type || 'text');

        editModal.style.display = '';
        editModal.removeAttribute('aria-hidden');
        editLabel.focus();
    }

    function closeEditModal() {
        if (!editModal) return;
        editModal.style.display = 'none';
        editModal.setAttribute('aria-hidden', 'true');
    }

    function toggleEditExtras(type) {
        if (editOptGroup) editOptGroup.style.display = type === 'select' ? '' : 'none';
        if (editValGroup) editValGroup.style.display = type === 'hidden' ? '' : 'none';
    }

    if (editType) {
        editType.addEventListener('change', function () { toggleEditExtras(this.value); });
    }

    if (editSaveBtn) {
        editSaveBtn.addEventListener('click', function () {
            var id = editFieldId ? editFieldId.value : '';
            var idx = fields.findIndex(function (x) { return x.id === id; });
            if (idx === -1) { closeEditModal(); return; }

            var type = editType ? editType.value : 'text';
            var updated = {
                id:          id,
                type:        type,
                label:       editLabel ? editLabel.value.trim() : '',
                placeholder: editPlaceholder ? editPlaceholder.value.trim() : '',
                required:    editRequired ? editRequired.checked : false,
                width:       editWidth ? editWidth.value : 'full'
            };
            if (type === 'select' && editOptions) updated.options = editOptions.value.trim();
            if (type === 'hidden' && editValue)   updated.value   = editValue.value.trim();

            fields[idx] = updated;

            // Update DOM row
            var row = fieldList.querySelector('[data-field-id="' + id + '"]');
            if (row) {
                var newRow = buildFieldRow(updated);
                fieldList.replaceChild(newRow, row);
            }

            updateJson();
            closeEditModal();
        });
    }

    if (editCancelBtn) editCancelBtn.addEventListener('click', closeEditModal);
    if (editModalClose) editModalClose.addEventListener('click', closeEditModal);
    if (editModal) {
        editModal.addEventListener('click', function (e) {
            if (e.target === editModal) closeEditModal();
        });
    }

    // ESC key
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && editModal && editModal.style.display !== 'none') {
            closeEditModal();
        }
    });

    // ── Initial render (fields already in DOM from PHP, just wire state) ─
    // State already loaded from JSON. DOM was rendered server-side.
    // We only need to re-attach event data on edit buttons.
    (function rewireEditButtons() {
        var rows = fieldList.querySelectorAll('.cf-field-row');
        rows.forEach(function (row) {
            var id  = row.dataset.fieldId;
            var f   = fields.find(function (x) { return x.id === id; });
            var btn = row.querySelector('.cf-edit-btn');
            if (f && btn) btn.dataset.field = JSON.stringify(f);
        });
    })();

}());
