const FIELD_PATTERNS = {
    email: {
        priority: 1,
        types: ['email'],
        names: ['email', 'e-mail', 'mail', 'user_email', 'login_email', 'email_address', 'emailaddress'],
        ids: ['email', 'e-mail', 'mail', 'user-email', 'login-email'],
        placeholders: ['email', 'e-mail', 'email address', 'your email', 'enter email'],
        autocomplete: ['email']
    },
    confirmEmail: {
        priority: 2,
        types: ['email'],
        names: ['confirm_email', 'confirmemail', 'email_confirm', 'verify_email', 'email_verify'],
        ids: ['confirm-email', 'confirmemail', 'verify-email', 'email-confirm'],
        placeholders: ['confirm email', 'verify email', 're-enter email', 'repeat email'],
        mustHaveConfirmIndicator: true
    },
    firstName: {
        priority: 3,
        types: ['text'],
        names: ['first_name', 'firstname', 'fname', 'first-name', 'vorname', 'prenom', 'fname'],
        ids: ['first-name', 'firstname', 'fname', 'firstName', 'mce-fname'],
        placeholders: ['first name', 'firstname', 'first'],
        autocomplete: ['given-name', 'first-name']
    },
    lastName: {
        priority: 4,
        types: ['text'],
        names: ['last_name', 'lastname', 'lname', 'surname', 'family_name', 'last-name', 'lname'],
        ids: ['last-name', 'lastname', 'lname', 'surname', 'lastName', 'mce-lname'],
        placeholders: ['last name', 'lastname', 'surname', 'last'],
        autocomplete: ['family-name', 'last-name']
    },
    username: {
        priority: 5,
        types: ['text'],
        names: ['username', 'user_name', 'login', 'usr', 'uname', 'user-id', 'userid', 'account_name', 'login_id'],
        ids: ['username', 'user-name', 'login', 'usr', 'uname'],
        placeholders: ['username', 'user name', 'login', 'username or email'],
        autocomplete: ['username']
    },
    password: {
        priority: 6,
        types: ['password'],
        names: ['password', 'pass', 'pwd', 'user_password', 'login_password'],
        ids: ['password', 'pass', 'pwd'],
        placeholders: ['password', 'pass', 'enter password'],
        autocomplete: ['current-password', 'new-password']
    },
    fullName: {
        priority: 7,
        types: ['text'],
        names: ['full_name', 'fullname', 'name'],
        ids: ['full-name', 'fullname', 'name'],
        placeholders: ['full name', 'your name', 'complete name'],
        autocomplete: ['name']
    },
    phone: {
        priority: 8,
        types: ['tel', 'text'],
        names: ['phone', 'telephone', 'mobile', 'cell', 'cellphone', 'phone_number'],
        ids: ['phone', 'telephone', 'mobile', 'cell', 'tel'],
        placeholders: ['phone', 'telephone', 'mobile number'],
        autocomplete: ['tel']
    },
    age: {
        priority: 9,
        types: ['number', 'text'],
        names: ['age', 'user_age'],
        ids: ['age'],
        placeholders: ['age', 'your age']
    },
    company: {
        priority: 10,
        types: ['text'],
        names: ['company', 'organization', 'company_name', 'employer'],
        ids: ['company', 'organization', 'employer'],
        placeholders: ['company', 'organization'],
        autocomplete: ['organization']
    }
};

async function detectFormFields(page) {
    console.log('Auto-detecting form fields...');
    
    const detectedFields = await page.evaluate((patterns) => {
        const results = {};
        const usedElements = new Set();
        
        const inputs = Array.from(document.querySelectorAll('input, select, textarea')).filter(input => {
            const type = input.type?.toLowerCase() || 'text';
            const style = window.getComputedStyle(input);
            const rect = input.getBoundingClientRect();
            
            if (type === 'hidden' || type === 'submit' || type === 'button') return false;
            if (input.tabIndex === -1 && input.style.position === 'absolute') return false;
            if (rect.width === 0 || rect.height === 0) return false;
            if (style.display === 'none' || style.visibility === 'hidden') return false;
            
            return true;
        });
        
        const calculateScore = (input, pattern, fieldName) => {
            let score = 0;
            const inputType = (input.type || 'text').toLowerCase();
            const inputName = (input.name || '').toLowerCase();
            const inputId = (input.id || '').toLowerCase();
            const placeholder = (input.placeholder || '').toLowerCase();
            const autocomplete = (input.autocomplete || '').toLowerCase();
            
            if (pattern.types && pattern.types.includes(inputType)) {
                score += 5;
            }
            
            if (pattern.names) {
                for (const name of pattern.names) {
                    const nameLower = name.toLowerCase();
                    if (inputName === nameLower) {
                        score += 20;
                        break;
                    } else if (inputName.includes(nameLower)) {
                        if (fieldName === 'firstName' && (inputName.includes('user') || inputName.includes('login'))) {
                            score -= 5;
                        } else if (fieldName === 'lastName' && (inputName.includes('user') || inputName.includes('login'))) {
                            score -= 5;
                        } else {
                            score += 10;
                        }
                        break;
                    }
                }
            }
            
            if (pattern.ids) {
                for (const id of pattern.ids) {
                    const idLower = id.toLowerCase();
                    if (inputId === idLower) {
                        score += 20;
                        break;
                    } else if (inputId.includes(idLower)) {
                        score += 10;
                        break;
                    }
                }
            }
            
            if (pattern.placeholders) {
                for (const ph of pattern.placeholders) {
                    const phLower = ph.toLowerCase();
                    if (placeholder === phLower) {
                        score += 15;
                        break;
                    } else if (placeholder.includes(phLower)) {
                        score += 8;
                        break;
                    }
                }
            }
            
            if (pattern.autocomplete) {
                for (const ac of pattern.autocomplete) {
                    if (autocomplete === ac.toLowerCase()) {
                        score += 12;
                        break;
                    }
                }
            }
            
            const labels = input.labels;
            if (labels && labels.length > 0) {
                const labelText = labels[0].textContent.toLowerCase();
                const fieldNameLower = fieldName.toLowerCase().replace(/([A-Z])/g, ' $1').trim();
                if (labelText.includes(fieldNameLower) || labelText.includes(pattern.names?.[0] || '')) {
                    score += 15;
                }
            }
            
            if (inputName.includes('b_') || inputId.includes('b_')) {
                score -= 30;
            }
            
            if (input.disabled || input.readOnly) {
                score -= 20;
            }
            
            if (pattern.mustHaveConfirmIndicator) {
                const hasConfirm = inputId.includes('confirm') || inputId.includes('verify') || 
                                  inputName.includes('confirm') || inputName.includes('verify') ||
                                  placeholder.includes('confirm') || placeholder.includes('verify') ||
                                  placeholder.includes('re-') || placeholder.includes('again');
                if (!hasConfirm) {
                    score -= 15;
                }
            }
            
            return score;
        };
        
        const sortedPatterns = Object.entries(patterns).sort((a, b) => a[1].priority - b[1].priority);
        
        for (const [fieldName, pattern] of sortedPatterns) {
            let bestMatch = null;
            let bestScore = 0;
            let bestIndex = -1;
            
            for (let i = 0; i < inputs.length; i++) {
                if (usedElements.has(i)) continue;
                
                const input = inputs[i];
                const score = calculateScore(input, pattern, fieldName);
                
                if (score > bestScore && score >= 10) {
                    bestScore = score;
                    bestMatch = input;
                    bestIndex = i;
                }
            }
            
            if (bestMatch && bestIndex >= 0) {
                usedElements.add(bestIndex);
                
                let selector = '';
                if (bestMatch.id) {
                    selector = `#${bestMatch.id}`;
                } else if (bestMatch.name) {
                    selector = `[name="${bestMatch.name}"]`;
                } else if (bestMatch.placeholder) {
                    selector = `[placeholder="${bestMatch.placeholder}"]`;
                } else {
                    const tagName = bestMatch.tagName.toLowerCase();
                    const type = bestMatch.type ? `[type="${bestMatch.type}"]` : '';
                    const allSame = Array.from(document.querySelectorAll(`${tagName}${type}`));
                    const index = allSame.indexOf(bestMatch) + 1;
                    selector = `${tagName}${type}:nth-of-type(${index})`;
                }
                
                results[fieldName] = { 
                    selector,
                    confidence: bestScore,
                    name: bestMatch.name,
                    id: bestMatch.id
                };
            }
        }
        
        return results;
    }, FIELD_PATTERNS);
    
    const detectedCount = Object.keys(detectedFields).length;
    if (detectedCount === 0) {
        console.log('   No fields detected');
    }
    
    return detectedFields;
}

module.exports = {
    FIELD_PATTERNS,
    detectFormFields
};
