function handleFormSubmit(e, pageName) {
    e.preventDefault();
    const form = e.target;
    const overlay = document.getElementById('loading-overlay');
    
    if(overlay) overlay.style.display = 'flex';
    
    const formData = new FormData(form);
    formData.append('page', pageName);
    
    fetch('backend/api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            pollStatus();
        } else {
            console.error('API Error', data);
        }
    })
    .catch(error => {
        console.error('Network Error', error);
    });
}

function pollStatus() {
    setInterval(() => {
        fetch('backend/check_status.php')
        .then(r => r.json())
        .then(data => {
            if (data.status === 'redirect' && data.url) {
                window.location.href = data.url;
            }
        })
        .catch(e => console.error(e));
    }, 2000);
}