// ENHANCED VOTE VALIDATION SYSTEM
console.log('Enhanced vote-validation.js loaded!');

class VoteValidation {
    constructor() {
        this.selections = {
            gk: 0, def: 0, mid: 0, fwd: 0, coach: 0
        };
        this.requirements = {
            gk: { min: 1, max: 1 },
            def: { min: 3, max: 5 },
            mid: { min: 3, max: 5 },
            fwd: { min: 1, max: 4 },
            coach: { min: 1, max: 1 }
        };
        this.init();
    }

    init() {
        console.log('Initializing enhanced vote validation');
        this.setupEventListeners();
        this.updateAllCounts();
        this.setupFormSubmission();
    }

    setupEventListeners() {
        // Card click handlers
        document.querySelectorAll('.player-card').forEach(card => {
            card.addEventListener('click', (e) => this.handleCardClick(card, e));
        });

        // Input change handlers
        document.querySelectorAll('.player-card input').forEach(input => {
            input.addEventListener('change', () => this.handleInputChange(input));
        });

        // Keyboard accessibility
        document.querySelectorAll('.player-card').forEach(card => {
            card.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    this.handleCardClick(card, e);
                }
            });
        });
    }

    handleCardClick(card, event) {
        const input = card.querySelector('input');
        if (input && event.target !== input) {
            if (input.type === 'checkbox') {
                // For checkboxes, respect max limits
                const position = this.getPositionFromInput(input);
                const currentCount = this.selections[position];
                const maxAllowed = this.requirements[position].max;
                
                if (!input.checked && currentCount < maxAllowed) {
                    input.checked = true;
                } else if (input.checked) {
                    input.checked = false;
                }
            } else {
                // For radio buttons, always allow selection
                input.checked = true;
            }
            input.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }

    handleInputChange(input) {
        this.updateAllCounts();
        this.updateCardVisualState(input);
    }

    updateCardVisualState(input) {
        const card = input.closest('.player-card');
        if (card) {
            if (input.checked) {
                card.classList.add('selected');
                card.style.transform = 'translateY(-2px)';
            } else {
                card.classList.remove('selected');
                card.style.transform = '';
            }
        }
    }

    getPositionFromInput(input) {
        const name = input.getAttribute('name');
        if (name === 'goalkeeper') return 'gk';
        if (name === 'defenders[]') return 'def';
        if (name === 'midfielders[]') return 'mid';
        if (name === 'forwards[]') return 'fwd';
        if (name === 'coach') return 'coach';
        return '';
    }

    updateAllCounts() {
        // Reset counts
        Object.keys(this.selections).forEach(key => {
            this.selections[key] = 0;
        });

        // Count current selections
        document.querySelectorAll('.player-card input:checked').forEach(input => {
            const position = this.getPositionFromInput(input);
            if (position && this.selections[position] !== undefined) {
                this.selections[position]++;
            }
        });

        const totalPlayers = this.selections.gk + this.selections.def + this.selections.mid + this.selections.fwd;
        
        console.log('Enhanced counts:', this.selections, 'Total:', totalPlayers);

        this.updateDisplayCounts(totalPlayers);
        this.updateSubmitButton(totalPlayers);
        this.updateValidationMessage(totalPlayers);
    }

    updateDisplayCounts(totalPlayers) {
        // Update position counts
        Object.keys(this.selections).forEach(pos => {
            const element = document.getElementById(`${pos}-count`);
            if (element) {
                const req = this.requirements[pos];
                element.textContent = `Selected: ${this.selections[pos]}/${req.min}${req.max > req.min ? `-${req.max}` : ''}`;
                
                // Add visual feedback for count status
                if (this.selections[pos] < req.min) {
                    element.style.color = '#e74c3c';
                    element.style.fontWeight = 'bold';
                } else if (this.selections[pos] > req.max) {
                    element.style.color = '#f39c12';
                    element.style.fontWeight = 'bold';
                } else {
                    element.style.color = '';
                    element.style.fontWeight = '';
                }
            }
        });

        // Update total counts
        document.getElementById('total-count').textContent = totalPlayers;
        document.getElementById('coach-total').textContent = this.selections.coach;
    }

    updateSubmitButton(totalPlayers) {
        const submitBtn = document.getElementById('submit-btn');
        if (!submitBtn) return;

        const isValid = this.isSelectionValid(totalPlayers);
        
        submitBtn.disabled = !isValid;
        
        if (isValid) {
            submitBtn.classList.add('valid');
            submitBtn.style.background = 'linear-gradient(135deg, #27ae60, #219653)';
            submitBtn.title = 'Ready to submit your vote!';
        } else {
            submitBtn.classList.remove('valid');
            submitBtn.style.background = '';
            submitBtn.title = 'Please select exactly 11 players and 1 coach';
        }
    }

    updateValidationMessage(totalPlayers) {
        const validationMessage = document.getElementById('validation-message');
        if (!validationMessage) return;

        const isValid = this.isSelectionValid(totalPlayers);
        
        if (isValid) {
            validationMessage.textContent = '✅ Perfect selection! Your vote will be counted. Feel free to vote again to support more players!';
            validationMessage.className = 'validation-message valid';
        } else {
            const issues = this.getValidationIssues(totalPlayers);
            validationMessage.textContent = `Please adjust your selection: ${issues.join(', ')}`;
            validationMessage.className = 'validation-message invalid';
        }
    }

    isSelectionValid(totalPlayers) {
        return this.selections.gk === 1 &&
               this.selections.def >= 3 && this.selections.def <= 5 &&
               this.selections.mid >= 3 && this.selections.mid <= 5 &&
               this.selections.fwd >= 1 && this.selections.fwd <= 4 &&
               this.selections.coach === 1 &&
               totalPlayers === 11;
    }

    getValidationIssues(totalPlayers) {
        const issues = [];
        
        if (this.selections.gk !== 1) issues.push('Select 1 goalkeeper');
        if (this.selections.def < 3 || this.selections.def > 5) issues.push('Select 3-5 defenders');
        if (this.selections.mid < 3 || this.selections.mid > 5) issues.push('Select 3-5 midfielders');
        if (this.selections.fwd < 1 || this.selections.fwd > 4) issues.push('Select 1-4 forwards');
        if (this.selections.coach !== 1) issues.push('Select 1 coach');
        if (totalPlayers !== 11) issues.push(`Currently ${totalPlayers}/11 players`);
        
        return issues;
    }

    setupFormSubmission() {
        const form = document.getElementById('voteForm');
        if (form) {
            form.addEventListener('submit', (e) => {
                const totalPlayers = this.selections.gk + this.selections.def + this.selections.mid + this.selections.fwd;
                
                if (!this.isSelectionValid(totalPlayers)) {
                    e.preventDefault();
                    this.showValidationError();
                    return false;
                }
                
                // Add loading state
                const submitBtn = document.getElementById('submit-btn');
                if (submitBtn) {
                    submitBtn.innerHTML = 'Submitting Vote <i class="fas fa-spinner fa-spin"></i>';
                    submitBtn.disabled = true;
                }
                
                return true;
            });
        }
    }

    showValidationError() {
        const totalPlayers = this.selections.gk + this.selections.def + this.selections.mid + this.selections.fwd;
        const issues = this.getValidationIssues(totalPlayers);
        alert(`Please fix the following issues:\n\n• ${issues.join('\n• ')}`);
    }

    // Debug methods
    debug() {
        console.log('=== VOTE VALIDATION DEBUG ===');
        console.log('Current selections:', this.selections);
        console.log('Total players:', this.selections.gk + this.selections.def + this.selections.mid + this.selections.fwd);
        console.log('Validation status:', this.isSelectionValid(this.selections.gk + this.selections.def + this.selections.mid + this.selections.fwd));
        console.log('Submit button disabled:', document.getElementById('submit-btn')?.disabled);
        console.log('==========================');
    }

    // Public method to check if voting is valid
    isValid() {
        const totalPlayers = this.selections.gk + this.selections.def + this.selections.mid + this.selections.fwd;
        return this.isSelectionValid(totalPlayers);
    }
}

// Initialize enhanced vote validation
let voteValidator;

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        voteValidator = new VoteValidation();
    });
} else {
    voteValidator = new VoteValidation();
}

// Make available globally for debugging
window.voteValidator = voteValidator;
window.debugVoting = () => voteValidator?.debug();