document.addEventListener('DOMContentLoaded', function () {
    var forms = document.querySelectorAll('.wpis-form');
    var form = forms[0];

    if (!form) {
        return;
    }

    if (forms.length > 1) {
        alert('WP Immo Sync : Multiple forms have been found on the page; only one form could be present by page.');
    }

    var COMMON_FIELDS = ['gender', 'firstname', 'lastname', 'email', 'phone', 'message'];
    var ADDRESS_FIELDS = ['addressStreet', 'addressNumber', 'addressBox', 'addressZip', 'addressCity'];

    var FORM_CONFIGS = {
        'wpis-form-contact-default': {
            source: 'contactForm',
            fields: COMMON_FIELDS,
        },
        'wpis-form-contact-extended': {
            source: 'contactForm',
            fields: COMMON_FIELDS.concat(ADDRESS_FIELDS),
        },
        'wpis-form-evaluation': {
            source: 'evaluationForm',
            fields: COMMON_FIELDS.concat(ADDRESS_FIELDS),
        },
        'wpis-form-estate': {
            source: 'estateForm',
            fields: COMMON_FIELDS,
            data: { estateId: 'eid', postId: 'pid', listId: 'lid' },
        },
    };

    function getSubmitButton(formElement) {
        return formElement.querySelector('button[type="submit"], button:not([type])');
    }

    function getFieldValue(formElement, fieldName) {
        var field = formElement.elements[fieldName];
        return field ? field.value : '';
    }

    function collectFormData(formElement) {
        var config = FORM_CONFIGS[formElement.id];

        if (!config) {
            return null;
        }

        var formData = {
            url: window.location.href,
            agreement: true,
            source: config.source,
        };

        config.fields.forEach(function (field) {
            formData[field] = getFieldValue(formElement, field);
        });

        if (config.data) {
            Object.keys(config.data).forEach(function (key) {
                formData[key] = formElement.dataset[config.data[key]];
            });
        }

        return formData;
    }

    function postForm(url, data) {
        var body = new URLSearchParams();

        Object.keys(data).forEach(function (key) {
            if (data[key] !== undefined && data[key] !== null) {
                body.append(key, data[key]);
            }
        });

        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: body.toString(),
        }).then(function (response) {
            return response.json();
        });
    }

    function showSuccess(formElement) {
        formElement.querySelectorAll('input, select, textarea, button').forEach(function (element) {
            element.disabled = true;
        });

        var button = getSubmitButton(formElement);
        if (button) {
            button.style.display = 'none';
        }

        formElement.querySelectorAll('.form-group').forEach(function (group) {
            group.style.opacity = '0.65';
        });

        var successMessage = document.createElement('span');
        successMessage.className = 'wpis-form-success';
        successMessage.textContent = literals['message.success'];
        formElement.appendChild(successMessage);

        postForm('/wp-json/wpis/form-sync', {});
    }

    function showErrors(formElement, errors) {
        var heading = errors.length === 1
            ? literals['error.single']
            : literals['error.multiple'];

        var errorMessage = '<div><span>' + heading + '</span><ul>';
        errors.forEach(function (error) {
            errorMessage += '<li>' + error.message + '</li>';
        });
        errorMessage += '</ul></div>';

        var errorContainer = formElement.querySelector('.form-errors');
        if (errorContainer) {
            errorContainer.innerHTML = errorMessage;
        }

        var button = getSubmitButton(formElement);
        if (button) {
            button.textContent = literals['form.submit.value'];
            button.disabled = false;
        }
    }

    form.addEventListener('submit', function (event) {
        event.preventDefault();

        var formData = collectFormData(form);
        if (!formData) {
            return;
        }

        var button = getSubmitButton(form);
        if (button) {
            button.textContent = literals['message.processing'];
            button.disabled = true;
        }

        postForm('/wp-json/wpis/form-data', formData).then(function (data) {
            if (data.success) {
                showSuccess(form);
            } else {
                showErrors(form, data.errors || []);
            }
        });
    });
});
