// Voting Interface JavaScript
document.addEventListener('DOMContentLoaded', function() {
    'use strict';
    
    console.log('Voting JS loaded');
    
    // Get configuration from data attributes
    var votingConfig = document.getElementById('voting-config');
    if (!votingConfig) {
        console.error('Voting config element not found');
        return;
    }
    
    console.log('Voting config found:', votingConfig);
    
    var isSimulation = votingConfig.dataset.simulation === 'true';
    var requiredFemales = parseInt(votingConfig.dataset.requiredFemales || '0', 10);
    var requiredMales = parseInt(votingConfig.dataset.requiredMales || '0', 10);
    
    console.log('Simulation:', isSimulation, 'Required:', requiredFemales, requiredMales);
    
    var femaleChecks = document.querySelectorAll('input[name="female_candidates[]"]');
    var maleChecks = document.querySelectorAll('input[name="male_candidates[]"]');
    var femaleCount = document.getElementById('female_count');
    var maleCount = document.getElementById('male_count');
    
    // Flow: step 1 (females) → modal confirm females → step 2 (males) → modal confirm final → submit
    var step1 = document.getElementById('vote-step-1');
    var step1b = document.getElementById('vote-step-1b');
    var step2 = document.getElementById('vote-step-2');
    var step3 = document.getElementById('vote-step-3');
    var modalFemales = document.getElementById('vote-confirm-females-modal');
    var modalFinal = document.getElementById('vote-confirm-final-modal');
    var continueBtns = document.querySelectorAll('.vote-continue-to-males');
    if (step1 && step2) {
        step2.style.display = 'none';
    }
    // "Confirm female selections" (step 1) → show modal with female summary
    var confirmFemalesBtn = document.getElementById('vote-confirm-females');
    var confirmFemalesOnlyEl = document.getElementById('vote-confirm-females-only');
    if (confirmFemalesBtn && modalFemales && confirmFemalesOnlyEl) {
        confirmFemalesBtn.addEventListener('click', function() {
            var items = [];
            femaleChecks.forEach(function(ch) {
                if (ch.checked) {
                    var card = ch.closest('label');
                    if (card) {
                        var name = card.dataset.candidateName || 'Candidate';
                        var photo = card.dataset.candidatePhoto || (card.querySelector('img.candidate-image') && card.querySelector('img.candidate-image').src) || '';
                        items.push({ name: name, photoUrl: photo });
                    }
                }
            });
            confirmFemalesOnlyEl.innerHTML = '';
            if (items.length) {
                items.forEach(function(item) {
                    var wrap = document.createElement('div');
                    wrap.className = 'vote-confirm-thumb';
                    wrap.setAttribute('style', 'text-align: center;');
                    var img = document.createElement('img');
                    img.src = item.photoUrl;
                    img.alt = '';
                    img.setAttribute('style', 'width: 64px; height: 64px; object-fit: cover; border-radius: 50%; display: block; margin: 0 auto 0.25rem;');
                    img.onerror = function() { this.style.visibility = 'hidden'; };
                    wrap.appendChild(img);
                    confirmFemalesOnlyEl.appendChild(wrap);
                });
            }
            modalFemales.hidden = false;
        });
    }
    // Female modal: "Back to edit" → close modal
    var backFromFemaleConfirm = document.getElementById('vote-back-from-female-confirm');
    if (backFromFemaleConfirm && modalFemales) {
        backFromFemaleConfirm.addEventListener('click', function() {
            modalFemales.hidden = true;
        });
    }
    // Female modal: "Continue to Male Candidates" → close modal, show step 2
    var continueAfterFemaleConfirm = document.getElementById('vote-continue-after-female-confirm');
    if (continueAfterFemaleConfirm && modalFemales && step2) {
        continueAfterFemaleConfirm.addEventListener('click', function() {
            selectedFemaleForConfirm = [];
            femaleChecks.forEach(function(ch) {
                if (ch.checked) {
                    var card = ch.closest('label');
                    if (card) {
                        var name = card.dataset.candidateName || 'Candidate';
                        var photoUrl = card.dataset.candidatePhoto || (card.querySelector('img.candidate-image') && card.querySelector('img.candidate-image').src) || '';
                        selectedFemaleForConfirm.push({ name: name, photoUrl: photoUrl });
                    }
                }
            });
            modalFemales.hidden = true;
            step1.style.display = 'none';
            step2.style.display = 'block';
        });
    }
    // Female modal: close on backdrop click
    var femalesBackdrop = document.querySelector('.vote-confirm-females-backdrop');
    if (femalesBackdrop && modalFemales) {
        femalesBackdrop.addEventListener('click', function() { modalFemales.hidden = true; });
    }
    // "Continue to Male Candidates" from step 1 when no females → step 2
    if (step1 && step2 && continueBtns.length) {
        continueBtns.forEach(function(btn) {
            btn.addEventListener('click', function() {
                step1.style.display = 'none';
                step2.style.display = 'block';
            });
        });
    }
    
    var confirmBtn = document.getElementById('vote-confirm-votes');
    var backToEditBtn = document.getElementById('vote-back-to-edit');
    var confirmFemalesEl = document.getElementById('vote-confirm-females');
    var confirmMalesEl = document.getElementById('vote-confirm-males');
    // Store female names+photos when leaving step 1 so final confirm can show them (step 1 is hidden on step 2)
    var selectedFemaleForConfirm = [];
    if (confirmBtn && modalFinal && confirmFemalesEl && confirmMalesEl) {
        confirmBtn.addEventListener('click', function() {
            var femaleItems = selectedFemaleForConfirm.length ? selectedFemaleForConfirm.slice() : (function() {
                var list = [];
                femaleChecks.forEach(function(ch) {
                    if (ch.checked) {
                        var card = ch.closest('label');
                        if (card) list.push({
                            name: card.dataset.candidateName || 'Candidate',
                            photoUrl: card.dataset.candidatePhoto || (card.querySelector('img.candidate-image') && card.querySelector('img.candidate-image').src) || ''
                        });
                    }
                });
                return list;
            })();
            var maleItems = [];
            maleChecks.forEach(function(ch) {
                if (ch.checked) {
                    var card = ch.closest('label');
                    if (card) maleItems.push({
                        name: card.dataset.candidateName || 'Candidate',
                        photoUrl: card.dataset.candidatePhoto || (card.querySelector('img.candidate-image') && card.querySelector('img.candidate-image').src) || ''
                    });
                }
            });
            function renderThumbnails(container, items) {
                container.innerHTML = '';
                items.forEach(function(item) {
                    var wrap = document.createElement('div');
                    wrap.className = 'vote-confirm-thumb';
                    wrap.setAttribute('style', 'text-align: center;');
                    var img = document.createElement('img');
                    img.src = item.photoUrl;
                    img.alt = '';
                    img.setAttribute('style', 'width: 64px; height: 64px; object-fit: cover; border-radius: 50%; display: block; margin: 0 auto;');
                    img.onerror = function() { this.style.visibility = 'hidden'; };
                    wrap.appendChild(img);
                    container.appendChild(wrap);
                });
            }
            renderThumbnails(confirmFemalesEl, femaleItems);
            renderThumbnails(confirmMalesEl, maleItems);
            modalFinal.hidden = false;
        });
    }
    if (backToEditBtn && modalFinal) {
        backToEditBtn.addEventListener('click', function() {
            modalFinal.hidden = true;
        });
    }
    // Final modal: close on backdrop click
    var finalBackdrop = document.querySelector('.vote-confirm-final-backdrop');
    if (finalBackdrop && modalFinal) {
        finalBackdrop.addEventListener('click', function() { modalFinal.hidden = true; });
    }
    
    console.log('Found checkboxes - Female:', femaleChecks.length, 'Male:', maleChecks.length);
    
    function updateCounts() {
        var fCount = Array.from(femaleChecks).filter(c => c.checked).length;
        var mCount = Array.from(maleChecks).filter(c => c.checked).length;
        if (femaleCount) {
            femaleCount.textContent = fCount + ' of ' + requiredFemales + ' selected';
            femaleCount.style.background    = fCount > 0 ? '#f0fdf4' : '#f1f5f9';
            femaleCount.style.borderColor   = fCount > 0 ? '#059669' : '#e2e8f0';
            femaleCount.style.color         = fCount > 0 ? '#065f46' : '#374151';
        }
        if (maleCount) {
            maleCount.textContent = mCount + ' of ' + requiredMales + ' selected';
            maleCount.style.background  = mCount > 0 ? '#f0fdf4' : '#f1f5f9';
            maleCount.style.borderColor = mCount > 0 ? '#059669' : '#e2e8f0';
            maleCount.style.color       = mCount > 0 ? '#065f46' : '#374151';
        }
    }
    
    function updateSelectionIndicator(input, isSelected) {
        var card = input.closest('label');
        if (!card) {
            console.warn('No label found for input');
            return;
        }
        
        var indicator = card.querySelector('.selection-indicator');
        var fill = card.querySelector('.selection-fill');
        var image = card.querySelector('.candidate-image') || card.querySelector('img');
        
        if (!indicator || !fill) {
            console.warn('Selection indicator elements not found', { indicator: !!indicator, fill: !!fill });
            return;
        }
        
        if (indicator && fill) {
            if (isSelected) {
                // Large green checkmark badge
                indicator.style.width          = '48px';
                indicator.style.height         = '48px';
                indicator.style.background     = '#059669';
                indicator.style.borderColor    = '#059669';
                indicator.style.borderWidth    = '0';
                indicator.style.boxShadow      = '0 3px 10px rgba(5,150,105,0.45)';
                fill.style.width  = '0';
                fill.style.height = '0';
                fill.innerHTML    = '<span style="color:#fff;font-size:1.5rem;font-weight:900;line-height:1;pointer-events:none;">&#10003;</span>';
                // Card — thick green outline
                card.style.borderColor  = '#059669';
                card.style.borderWidth  = '4px';
                card.style.background   = '#f0fdf4';
                card.style.outline      = '4px solid #059669';
                card.style.outlineOffset = '3px';
                card.style.boxShadow    = '0 0 0 6px rgba(5,150,105,0.15)';
                // Photo
                if (image) { image.style.borderColor = '#059669'; image.style.filter = ''; }
            } else {
                // Reset badge
                indicator.style.width          = '34px';
                indicator.style.height         = '34px';
                indicator.style.background     = '#f8fafc';
                indicator.style.borderColor    = '#dde3eb';
                indicator.style.borderWidth    = '3px';
                indicator.style.boxShadow      = '';
                fill.style.width  = '0';
                fill.style.height = '0';
                fill.innerHTML    = '';
                // Card
                card.style.borderColor   = '#e8edf2';
                card.style.borderWidth   = '3px';
                card.style.background    = '#fff';
                card.style.outline       = 'none';
                card.style.outlineOffset = '0';
                card.style.boxShadow     = '';
                // Photo
                if (image) { image.style.borderColor = '#e8edf2'; image.style.filter = ''; }
            }
        }
    }
    
    function updateCardStyles() {
        // Update checkbox cards (Presbyters elections)
        femaleChecks.forEach(function(check) {
            updateSelectionIndicator(check, check.checked);
        });
        
        maleChecks.forEach(function(check) {
            updateSelectionIndicator(check, check.checked);
        });
        
        // Update radio button cards (Group elections)
        var radioButtons = document.querySelectorAll('input[type="radio"].candidate-radio');
        radioButtons.forEach(function(radio) {
            updateSelectionIndicator(radio, radio.checked);
        });
    }
    
    // Initialize images — full color always, no grayscale
    function initializeImages() {
        document.querySelectorAll('.candidate-card .candidate-image').forEach(function(img) {
            img.style.filter = '';
        });
    }
    
    // Handle checkbox changes for Presbyters elections
    // Labels automatically handle clicks - we just listen for changes
    femaleChecks.forEach(function(check) {
        console.log('Attaching change listener to female checkbox:', check.value);
        check.addEventListener('change', function() {
            console.log('Female checkbox changed:', check.value, 'checked:', check.checked);
            var checkedCount = Array.from(femaleChecks).filter(ch => ch.checked).length;
            // Enforce max: if we're over the required, uncheck this one (last clicked)
            if (check.checked && checkedCount > requiredFemales) {
                check.checked = false;
                checkedCount = requiredFemales;
            }
            updateSelectionIndicator(check, check.checked);
            // Cap at required: disable unchecked when at max (simulation and real)
            if (checkedCount >= requiredFemales) {
                femaleChecks.forEach(function(ch) {
                    if (!ch.checked) {
                        ch.disabled = true;
                        var chCard = ch.closest('label');
                        if (chCard) {
                            chCard.style.opacity = '0.5';
                            chCard.style.pointerEvents = 'none';
                        }
                    }
                });
            } else {
                femaleChecks.forEach(function(ch) {
                    ch.disabled = false;
                    var chCard = ch.closest('label');
                    if (chCard) {
                        chCard.style.opacity = '1';
                        chCard.style.pointerEvents = 'auto';
                    }
                });
            }
            updateCounts();
        });
    });
    
    maleChecks.forEach(function(check) {
        console.log('Attaching change listener to male checkbox:', check.value);
        check.addEventListener('change', function() {
            console.log('Male checkbox changed:', check.value, 'checked:', check.checked);
            var checkedCount = Array.from(maleChecks).filter(ch => ch.checked).length;
            // Enforce max: if we're over the required, uncheck this one (last clicked)
            if (check.checked && checkedCount > requiredMales) {
                check.checked = false;
                checkedCount = requiredMales;
            }
            updateSelectionIndicator(check, check.checked);
            // Cap at required: disable unchecked when at max (simulation and real)
            if (checkedCount >= requiredMales) {
                maleChecks.forEach(function(ch) {
                    if (!ch.checked) {
                        ch.disabled = true;
                        var chCard = ch.closest('label');
                        if (chCard) {
                            chCard.style.opacity = '0.5';
                            chCard.style.pointerEvents = 'none';
                        }
                    }
                });
            } else {
                maleChecks.forEach(function(ch) {
                    ch.disabled = false;
                    var chCard = ch.closest('label');
                    if (chCard) {
                        chCard.style.opacity = '1';
                        chCard.style.pointerEvents = 'auto';
                    }
                });
            }
            updateCounts();
        });
    });
    
    // Handle radio button changes for Group elections
    var radioButtons = document.querySelectorAll('input[type="radio"].candidate-radio');
    console.log('Found radio buttons:', radioButtons.length);
    radioButtons.forEach(function(radio) {
        console.log('Attaching change listener to radio:', radio.name, radio.value);
        radio.addEventListener('change', function() {
            console.log('Radio changed:', radio.name, radio.value, 'checked:', radio.checked);
            // Update all radios in the same group
            var groupName = radio.name;
            document.querySelectorAll('input[name="' + groupName + '"]').forEach(function(r) {
                updateSelectionIndicator(r, r.checked);
            });
        });
    });
    
    // Also add click listeners directly to labels as backup
    document.querySelectorAll('.candidate-card').forEach(function(card) {
        var input = card.querySelector('input');
        if (!input) return;
        
        card.addEventListener('click', function(e) {
            console.log('Card clicked, input type:', input.type, 'current checked:', input.checked);
            // Let the label handle it naturally, but ensure change fires
            setTimeout(function() {
                if (input.type === 'checkbox') {
                    console.log('After click - checkbox checked:', input.checked);
                    updateSelectionIndicator(input, input.checked);
                    updateCounts();
                } else if (input.type === 'radio') {
                    console.log('After click - radio checked:', input.checked);
                    var groupName = input.name;
                    document.querySelectorAll('input[name="' + groupName + '"]').forEach(function(r) {
                        updateSelectionIndicator(r, r.checked);
                    });
                }
            }, 10);
        });
    });
    
    // Initialize styles
    initializeImages();
    updateCounts();
    updateCardStyles();
    // Sync disable state on load (e.g. after browser restore or if any pre-checked)
    (function syncDisableState() {
        var fChecked = Array.from(femaleChecks).filter(function(c) { return c.checked; }).length;
        var mChecked = Array.from(maleChecks).filter(function(c) { return c.checked; }).length;
        femaleChecks.forEach(function(ch) {
            ch.disabled = !ch.checked && fChecked >= requiredFemales;
            var card = ch.closest('label');
            if (card) card.style.opacity = ch.disabled ? '0.5' : '1', card.style.pointerEvents = ch.disabled ? 'none' : 'auto';
        });
        maleChecks.forEach(function(ch) {
            ch.disabled = !ch.checked && mChecked >= requiredMales;
            var card = ch.closest('label');
            if (card) card.style.opacity = ch.disabled ? '0.5' : '1', card.style.pointerEvents = ch.disabled ? 'none' : 'auto';
        });
    })();
});
