async function detectSubmissionResult(page, urlBeforeSubmit = null) {
    const result = await page.evaluate((beforeUrl) => {
        const results = {
            success: false,
            failure: false,
            failureReason: null,
            currentUrl: window.location.href,
            signals: []
        };

        // Check if URL changed significantly (often indicates success)
        if (beforeUrl && window.location.href !== beforeUrl) {
            results.signals.push(`URL changed from ${beforeUrl.split('?')[0]} to ${window.location.href.split('?')[0]}`);
        }

        const errorSelectors = [
            '.error', '.Error', '.ERROR',
            '[class*="error" i]',
            '.alert-danger', '.alert-error',
            '[class*="failed" i]',
            '[class*="invalid" i]',
            '[class*="wrong" i]',
            '#error', '#Error',
            '[role="alert"]',
            '.message.error',
            '.error-message',
            '.form-error',
            '[data-form-error]'
        ];

        for (const selector of errorSelectors) {
            const el = document.querySelector(selector);
            if (el) {
                const text = el.textContent?.toLowerCase() || '';
                const style = window.getComputedStyle(el);
                if (style.display !== 'none' && 
                    style.visibility !== 'hidden' && 
                    style.opacity !== '0' &&
                    text.length > 0 &&
                    text.length < 500) {
                    results.failure = true;
                    results.failureReason = `Error message detected: ${text.substring(0, 100)}`;
                    results.signals.push(`Error: ${text.substring(0, 100)}`);
                    break;
                }
            }
        }

        const pageText = document.body.innerText.toLowerCase();
        
        const successKeywords = [
            'thank you', 'thanks for', 'successfully', 'subscribed', 'subscription confirmed',
            'you are now', 'welcome', 'email confirmed', 'verification sent',
            'check your email', 'confirm your email', 'almost done',
            'signed up', 'signed up successfully', 'subscription successful',
            'almost there', 'confirm your subscription', 'verify your email'
        ];
        
        for (const keyword of successKeywords) {
            if (pageText.includes(keyword)) {
                results.success = true;
                results.signals.push(`Success keyword: "${keyword}"`);
                break;
            }
        }

        const failureKeywords = [
            'incorrect', 'invalid captcha', 'wrong captcha', 'incorrect captcha', 
            'captcha incorrect', 'captcha invalid', 'captcha error',
            'please complete the captcha', 'complete the captcha',
            'try again', 'submission failed', 'email already exists',
            'you have already subscribed', 'already registered'
        ];
        
        if (!results.success) {
            for (const keyword of failureKeywords) {
                if (pageText.includes(keyword)) {
                    results.failure = true;
                    results.failureReason = `Failure keyword detected: "${keyword}"`;
                    results.signals.push(`Failure: ${keyword}`);
                    break;
                }
            }
        }

        // Only check form visibility if we haven't determined success/failure yet
        if (!results.success && !results.failure) {
            const formStillVisible = document.querySelector('form') !== null;
            const emailInputStillVisible = document.querySelector('input[type="email"]') !== null ||
                                           document.querySelector('input[name*="email" i]') !== null;
            
            if (formStillVisible && emailInputStillVisible) {
                // Form still visible but no explicit success/failure - could be either
                results.signals.push('Form still visible but no explicit result - unknown');
            } else if (!formStillVisible && !emailInputStillVisible) {
                // Form disappeared - likely success
                results.success = true;
                results.signals.push('Form no longer visible - assuming success');
            }
        }

        return results;
    }, urlBeforeSubmit);

    return result;
}

module.exports = {
    detectSubmissionResult
};
