// Simplified Judge Panels JavaScript

$(document).ready(function() {
    // Initialize the panel
    initializePanel();
    
    // Auto-save functionality
    setupAutoSave();
    
    // Keyboard shortcuts
    setupKeyboardShortcuts();
    
    // Score validation
    setupScoreValidation();
});

function initializePanel() {
    console.log('Initializing simplified judge panel...');
    
    // Add fade-in animation
    $('.panel-container').addClass('fade-in');
    
    // Focus first input
    $('.score-input:first').focus();
    
    // Setup landed/crashed toggle buttons
    setupLandedControls();
    
    // Setup submit button
    setupSubmitButton();
}

function setupLandedControls() {
    $('.btn-landed, .btn-crashed').click(function() {
        const $parent = $(this).closest('.score-input-group');
        const $landedBtn = $parent.find('.btn-landed');
        const $crashedBtn = $parent.find('.btn-crashed');
        
        if ($(this).hasClass('btn-landed')) {
            $landedBtn.addClass('active');
            $crashedBtn.removeClass('active');
            $parent.attr('data-landed', 'true');
        } else {
            $crashedBtn.addClass('active');
            $landedBtn.removeClass('active');
            $parent.attr('data-landed', 'false');
        }
        
        // Add visual feedback
        $parent.addClass('active');
        setTimeout(() => $parent.removeClass('active'), 300);
        
        updateSubmitButton();
    });
}

function setupSubmitButton() {
    $('#submit-scores').click(function(e) {
        e.preventDefault();
        
        if (validateScores()) {
            submitScores();
        }
    });
}

function setupScoreValidation() {
    $('.score-input').on('input blur', function() {
        const value = parseFloat($(this).val());
        const min = parseFloat($(this).attr('min')) || 0;
        const max = parseFloat($(this).attr('max')) || 10;
        
        if (value < min || value > max) {
            $(this).addClass('is-invalid');
            $(this).closest('.score-input-group').addClass('has-error');
        } else {
            $(this).removeClass('is-invalid');
            $(this).closest('.score-input-group').removeClass('has-error');
        }
        
        updateSubmitButton();
    });
    
    // Allow only numbers and decimal point
    $('.score-input').on('keypress', function(e) {
        const char = String.fromCharCode(e.which);
        if (!/[0-9\.]/.test(char) && e.which !== 8) {
            e.preventDefault();
        }
    });
}

function setupAutoSave() {
    let autoSaveTimer;
    
    $('.score-input').on('input', function() {
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(() => {
            saveToLocalStorage();
        }, 2000);
    });
    
    // Load from localStorage on page load
    loadFromLocalStorage();
}

function setupKeyboardShortcuts() {
    $(document).keydown(function(e) {
        // Tab navigation
        if (e.key === 'Tab') {
            // Let default tab behavior work
            return;
        }
        
        // Enter to submit
        if (e.key === 'Enter' && e.ctrlKey) {
            e.preventDefault();
            $('#submit-scores').click();
        }
        
        // Quick landed/crashed toggles
        if (e.key === 'l' && e.ctrlKey) {
            e.preventDefault();
            $('.score-input:focus').closest('.score-input-group').find('.btn-landed').click();
        }
        
        if (e.key === 'c' && e.ctrlKey) {
            e.preventDefault();
            $('.score-input:focus').closest('.score-input-group').find('.btn-crashed').click();
        }
    });
}

function validateScores() {
    let isValid = true;
    let errors = [];
    
    $('.score-input').each(function() {
        const $input = $(this);
        const value = $input.val().trim();
        
        if (value === '') {
            errors.push('All score fields must be filled');
            $input.addClass('is-invalid');
            isValid = false;
            return false; // Break the loop
        }
        
        const numValue = parseFloat(value);
        const min = parseFloat($input.attr('min')) || 0;
        const max = parseFloat($input.attr('max')) || 10;
        
        if (numValue < min || numValue > max) {
            errors.push(`Score must be between ${min} and ${max}`);
            $input.addClass('is-invalid');
            isValid = false;
        }
    });
    
    if (errors.length > 0) {
        showAlert('error', errors.join('<br>'));
    }
    
    return isValid;
}

function submitScores() {
    const $submitBtn = $('#submit-scores');
    const originalText = $submitBtn.text();
    
    // Show loading state
    $submitBtn.prop('disabled', true).text('Submitting...');
    $('.panel-container').addClass('loading');
    
    // Collect scores data
    const scoresData = collectScoresData();
    
    // Submit via AJAX
    $.ajax({
        url: 'submit_scores.php',
        method: 'POST',
        data: scoresData,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                showAlert('success', 'Scores submitted successfully!');
                clearLocalStorage();
                
                // Auto-redirect or reload
                setTimeout(() => {
                    if (response.redirect_url) {
                        window.location.href = response.redirect_url;
                    } else {
                        location.reload();
                    }
                }, 1500);
            } else {
                showAlert('error', response.message || 'Error submitting scores');
            }
        },
        error: function(xhr, status, error) {
            console.error('Submit error:', error);
            showAlert('error', 'Network error. Please try again.');
        },
        complete: function() {
            $submitBtn.prop('disabled', false).text(originalText);
            $('.panel-container').removeClass('loading');
        }
    });
}

function collectScoresData() {
    const data = {
        judge_id: $('#judge_id').val(),
        event_id: $('#event_id').val(),
        participant_id: $('#participant_id').val(),
        heat_id: $('#heat_id').val(),
        scores: {}
    };
    
    $('.score-input-group').each(function() {
        const $group = $(this);
        const attemptId = $group.attr('data-attempt-id');
        const score = $group.find('.score-input').val();
        const landed = $group.attr('data-landed') === 'true';
        
        data.scores[attemptId] = {
            score: parseFloat(score),
            landed: landed
        };
    });
    
    return data;
}

function updateSubmitButton() {
    const $submitBtn = $('#submit-scores');
    let allFilled = true;
    
    $('.score-input').each(function() {
        if ($(this).val().trim() === '') {
            allFilled = false;
            return false;
        }
    });
    
    if (allFilled && $('.is-invalid').length === 0) {
        $submitBtn.prop('disabled', false).removeClass('btn-secondary').addClass('btn-success');
    } else {
        $submitBtn.prop('disabled', true).removeClass('btn-success').addClass('btn-secondary');
    }
}

function saveToLocalStorage() {
    try {
        const data = collectScoresData();
        const key = `simplified_panel_${data.judge_id}_${data.event_id}_${data.participant_id}`;
        localStorage.setItem(key, JSON.stringify(data));
        console.log('Scores auto-saved to localStorage');
    } catch (e) {
        console.warn('Could not save to localStorage:', e);
    }
}

function loadFromLocalStorage() {
    try {
        const judgeId = $('#judge_id').val();
        const eventId = $('#event_id').val();
        const participantId = $('#participant_id').val();
        const key = `simplified_panel_${judgeId}_${eventId}_${participantId}`;
        
        const savedData = localStorage.getItem(key);
        if (savedData) {
            const data = JSON.parse(savedData);
            
            // Restore scores
            Object.keys(data.scores).forEach(attemptId => {
                const $group = $(`.score-input-group[data-attempt-id="${attemptId}"]`);
                if ($group.length) {
                    const attemptData = data.scores[attemptId];
                    $group.find('.score-input').val(attemptData.score);
                    
                    if (attemptData.landed) {
                        $group.find('.btn-landed').addClass('active');
                        $group.attr('data-landed', 'true');
                    } else {
                        $group.find('.btn-crashed').addClass('active');
                        $group.attr('data-landed', 'false');
                    }
                }
            });
            
            updateSubmitButton();
            console.log('Scores restored from localStorage');
        }
    } catch (e) {
        console.warn('Could not load from localStorage:', e);
    }
}

function clearLocalStorage() {
    try {
        const judgeId = $('#judge_id').val();
        const eventId = $('#event_id').val();
        const participantId = $('#participant_id').val();
        const key = `simplified_panel_${judgeId}_${eventId}_${participantId}`;
        localStorage.removeItem(key);
    } catch (e) {
        console.warn('Could not clear localStorage:', e);
    }
}

function showAlert(type, message) {
    // Remove existing alerts
    $('.temp-alert').remove();
    
    const alertClass = type === 'error' ? 'alert-danger' : 
                     type === 'success' ? 'alert-success' : 'alert-info';
    
    const $alert = $(`
        <div class="alert ${alertClass} temp-alert" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
            <strong>${type.charAt(0).toUpperCase() + type.slice(1)}:</strong> ${message}
            <button type="button" class="close" style="float: right; margin-left: 10px;">
                <span>&times;</span>
            </button>
        </div>
    `);
    
    $('body').append($alert);
    
    // Auto-hide after 5 seconds
    setTimeout(() => {
        $alert.fadeOut(() => $alert.remove());
    }, 5000);
    
    // Manual close
    $alert.find('.close').click(() => {
        $alert.fadeOut(() => $alert.remove());
    });
}

// Utility functions
function formatScore(score) {
    return parseFloat(score).toFixed(1);
}

function calculateProgress() {
    const total = $('.score-input').length;
    const filled = $('.score-input').filter(function() {
        return $(this).val().trim() !== '';
    }).length;
    
    return Math.round((filled / total) * 100);
}
