(function () {
    const form = document.getElementById('contactForm');
    if (!form) return;

    const submitButton = form.querySelector('button[type="submit"]');
    const defaultSubmitLabel = submitButton ? submitButton.textContent : 'Send';
    const fallbackApi = 'https://app.tabeley.com/api';
    const configuredBase = window.TABELEY_API_BASE_URL;
    const originBase = `${window.location.origin}/api`;

    const candidates = [configuredBase, originBase, fallbackApi]
        .filter(Boolean)
        .map((url) => String(url).replace(/\/+$/, ''))
        .filter((url, idx, arr) => arr.indexOf(url) === idx);

    function getFieldValue(selector) {
        const field = form.querySelector(selector);
        return field ? field.value.trim() : '';
    }

    async function postFeedback(baseUrl, payload) {
        return fetch(`${baseUrl}/public/feedback`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json'
            },
            body: JSON.stringify(payload)
        });
    }

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

        const name = getFieldValue('input[type="text"]');
        const email = getFieldValue('input[type="email"]');
        const message = getFieldValue('textarea');

        if (message.length < 5) {
            alert('Please enter at least 5 characters.');
            return;
        }

        if (submitButton) {
            submitButton.disabled = true;
            submitButton.textContent = 'Sending...';
        }

        const payload = { message, name, email };
        let sent = false;
        let lastError = null;

        for (const base of candidates) {
            try {
                const response = await postFeedback(base, payload);
                if (response.ok) {
                    sent = true;
                    break;
                }

                const body = await response.text();
                lastError = body || `HTTP ${response.status}`;
            } catch (err) {
                lastError = err;
            }
        }

        if (submitButton) {
            submitButton.disabled = false;
            submitButton.textContent = defaultSubmitLabel;
        }

        if (sent) {
            form.reset();
            alert('Feedback sent successfully.');
            return;
        }

        console.error('Feedback send failed:', lastError);
        alert('Unable to send feedback now. Please try again later.');
    });
})();
