(function () {
    'use strict';

    const countInput = document.getElementById('number_of_owners');
    const anchorField = document.getElementById('cf-field-legal_name');

    if (!countInput || !anchorField) {
        return;
    }

    const labelBase = countInput.dataset.ownerLabel || 'Name of Owner';
    const maxOwners = parseInt(countInput.getAttribute('max') || '5', 10);

    function normalizeCount(value) {
        let count = parseInt(value, 10);
        if (Number.isNaN(count) || count < 1) {
            count = 1;
        }
        if (count > maxOwners) {
            count = maxOwners;
        }
        return count;
    }

    function escapeHtml(value) {
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function getInsertAfter() {
        const ownerFields = document.querySelectorAll('.owner-name-field');
        if (ownerFields.length > 0) {
            return ownerFields[ownerFields.length - 1];
        }

        return anchorField;
    }

    function renderOwnerFields() {
        const count = normalizeCount(countInput.value);
        countInput.value = String(count);

        const existing = [];
        document.querySelectorAll('.owner-name-field .owner-name-input').forEach(function (input) {
            existing.push(input.value);
        });

        document.querySelectorAll('.owner-name-field').forEach(function (field) {
            field.remove();
        });

        let insertAfter = anchorField;

        for (let i = 1; i <= count; i++) {
            const wrap = document.createElement('div');
            wrap.className = 'cf-field cf-span-1 owner-name-field';
            wrap.innerHTML =
                '<label class="form-label" for="owner_name_' + i + '">' + escapeHtml(labelBase) + ' ' + i + '</label>' +
                '<input type="text" id="owner_name_' + i + '" name="owner_names[]" class="form-input owner-name-input" value="' + escapeHtml(existing[i - 1] || '') + '" required>';
            insertAfter.insertAdjacentElement('afterend', wrap);
            insertAfter = wrap;
        }
    }

    renderOwnerFields();
    countInput.addEventListener('input', renderOwnerFields);
    countInput.addEventListener('change', renderOwnerFields);
})();
