// Interactivity for Costelio Construct Portal
document.addEventListener('DOMContentLoaded', () => {
    console.log('Costelio Construct Portal Initialized.');

    const contactForm = document.getElementById('contact-form') as HTMLFormElement | null;
    const submitBtn = document.getElementById('submit-btn');
    const formMessage = document.getElementById('form-message');

    if (contactForm && submitBtn && formMessage) {
        contactForm.addEventListener('submit', async (e: Event) => {
            e.preventDefault();

            // Set loading state
            const btnSpan = submitBtn.querySelector('span');
            const originalText = btnSpan ? btnSpan.innerText : 'Send Message';
            if (btnSpan) btnSpan.innerText = 'Sending...';
            submitBtn.setAttribute('disabled', 'true');
            submitBtn.classList.add('opacity-70', 'cursor-not-allowed');
            
            // Add a spinner icon dynamically
            const spinner = document.createElement('div');
            spinner.className = 'w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin';
            submitBtn.appendChild(spinner);

            formMessage.classList.add('hidden');
            formMessage.classList.remove('bg-green-100', 'text-green-700', 'bg-red-100', 'text-red-700');

            // Gather form data
            const formData = new FormData(contactForm);

            try {
                const response = await fetch(contactForm.action, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.text();

                formMessage.classList.remove('hidden');
                if (response.ok) {
                    formMessage.innerText = result;
                    formMessage.classList.add('bg-green-100', 'text-green-700');
                    contactForm.reset();
                } else {
                    formMessage.innerText = result || 'An error occurred. Please try again.';
                    formMessage.classList.add('bg-red-100', 'text-red-700');
                }
            } catch (error) {
                formMessage.classList.remove('hidden');
                formMessage.innerText = 'Unable to connect to the server. Please check your connection.';
                formMessage.classList.add('bg-red-100', 'text-red-700');
            } finally {
                // Restore button state
                if (btnSpan) btnSpan.innerText = originalText;
                submitBtn.removeAttribute('disabled');
                submitBtn.classList.remove('opacity-70', 'cursor-not-allowed');
                if (spinner.parentNode) spinner.parentNode.removeChild(spinner);
            }
        });
    }
});