/**
 * Estreka Ratsaklubi - Main JavaScript
 * 🔧 PARANDATUD: ID konflikt lahendatud + Multi-day toe lisamine + Null-safe editResult
 */

// DOM Content Loaded
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

/**
 * App initialization
 */
function initializeApp() {
    setupNavigation();
    setupForms();
    setupModals();
    setupToasts();
    setupTableSorting();
    setupLazyLoading();
    setupMultiDisciplineHandlers();
    setupMultiDayHandlers(); // UUENDATUD: Multi-day funktsioonid
    
    console.log('🐴 Estreka Ratsaklubi App initialized');
}

/**
 * Navigation functions
 */
function setupNavigation() {
    // Mobile menu toggle
    const mobileToggle = document.querySelector('.mobile-menu-toggle');
    const mobileNav = document.querySelector('.mobile-nav');
    
    if (mobileToggle && mobileNav) {
        mobileToggle.addEventListener('click', function() {
            toggleMobileMenu();
        });
    }
    
    // User menu toggle
    const userToggle = document.querySelector('.user-menu-toggle');
    const userDropdown = document.querySelector('.user-menu-dropdown');
    
    if (userToggle && userDropdown) {
        userToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleUserMenu();
        });
        
        // Close dropdown when clicking outside
        document.addEventListener('click', function() {
            closeUserMenu();
        });
    }
    
    // Smooth scroll for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
}

function toggleMobileMenu() {
    const mobileNav = document.querySelector('.mobile-nav');
    const toggle = document.querySelector('.mobile-menu-toggle');
    
    if (mobileNav && toggle) {
        mobileNav.classList.toggle('show');
        toggle.classList.toggle('active');
        document.body.classList.toggle('menu-open');
    }
}

function toggleUserMenu() {
    const dropdown = document.querySelector('.user-menu-dropdown');
    if (dropdown) {
        dropdown.classList.toggle('show');
    }
}

function closeUserMenu() {
    const dropdown = document.querySelector('.user-menu-dropdown');
    if (dropdown) {
        dropdown.classList.remove('show');
    }
}

/**
 * Form handling
 */
function setupForms() {
    // Form validation
    const forms = document.querySelectorAll('form[data-validate]');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
            }
        });
    });
    
    // Password toggle
    document.querySelectorAll('.password-toggle').forEach(toggle => {
        toggle.addEventListener('click', function() {
            const input = this.parentElement.querySelector('input');
            const icon = this.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.className = 'icon-eye-off';
            } else {
                input.type = 'password';
                icon.className = 'icon-eye';
            }
        });
    });
    
    // Auto-submit filters
    document.querySelectorAll('.filter-select').forEach(select => {
        select.addEventListener('change', function() {
            setTimeout(() => this.closest('form').submit(), 100);
        });
    });
}

function validateForm(form) {
    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            showFieldError(field, 'See väli on kohustuslik');
            isValid = false;
        } else {
            clearFieldError(field);
        }
    });
    
    // Email validation
    const emailFields = form.querySelectorAll('input[type="email"]');
    emailFields.forEach(field => {
        if (field.value && !isValidEmail(field.value)) {
            showFieldError(field, 'Sisesta kehtiv e-maili aadress');
            isValid = false;
        }
    });
    
    return isValid;
}

function showFieldError(field, message) {
    clearFieldError(field);
    
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.textContent = message;
    
    field.classList.add('error');
    field.parentNode.appendChild(errorDiv);
}

function clearFieldError(field) {
    field.classList.remove('error');
    const errorDiv = field.parentNode.querySelector('.field-error');
    if (errorDiv) {
        errorDiv.remove();
    }
}

function isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

/**
 * Modal functionality
 */
function setupModals() {
    // Modal triggers
    document.querySelectorAll('[data-modal]').forEach(trigger => {
        trigger.addEventListener('click', function(e) {
            e.preventDefault();
            const modalId = this.getAttribute('data-modal');
            openModal(modalId);
        });
    });
    
    // Close modal buttons
    document.querySelectorAll('.modal-close').forEach(closeBtn => {
        closeBtn.addEventListener('click', function() {
            const modal = this.closest('.modal');
            closeModal(modal.id);
        });
    });
    
    // Close on overlay click
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', function(e) {
            if (e.target === this) {
                const modal = this.closest('.modal');
                closeModal(modal.id);
            }
        });
    });
    
    // ESC key to close modal
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal.show');
            if (openModal) {
                closeModal(openModal.id);
            }
        }
    });
}

function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('show');
        document.body.classList.add('modal-open');
        
        // Focus first input
        setTimeout(() => {
            const firstInput = modal.querySelector('input, select, textarea');
            if (firstInput) {
                firstInput.focus();
            }
        }, 100);
        
        // Trigger custom event
        const event = new CustomEvent('show');
        modal.dispatchEvent(event);
    }
}

function closeModal(modalId) {
    let modal;
    
    if (typeof modalId === 'string') {
        modal = document.getElementById(modalId);
    } else if (modalId && modalId.nodeType) {
        // It's already a DOM element
        modal = modalId;
    }
    
    if (modal) {
        modal.classList.remove('show');
        document.body.classList.remove('modal-open');
        
        // Trigger custom event
        const event = new CustomEvent('hide');
        modal.dispatchEvent(event);
    }
}

/**
 * Toast notifications
 */
function setupToasts() {
    // Auto-dismiss alerts
    document.querySelectorAll('.alert').forEach(alert => {
        const closeBtn = alert.querySelector('.alert-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                dismissAlert(alert);
            });
        }
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => dismissAlert(alert), 5000);
    });
}

function showToast(message, type = 'info') {
    const container = document.getElementById('notifications') || createNotificationContainer();
    
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} alert-dismissible`;
    toast.innerHTML = `
        <span>${message}</span>
        <button class="alert-close" onclick="dismissAlert(this.parentElement)">&times;</button>
    `;
    
    container.appendChild(toast);
    
    // Auto-dismiss
    setTimeout(() => dismissAlert(toast), 5000);
}

function dismissAlert(alert) {
    if (alert && alert.parentElement) {
        alert.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => alert.remove(), 300);
    }
}

function createNotificationContainer() {
    const container = document.createElement('div');
    container.id = 'notifications';
    container.className = 'notifications-container';
    document.body.appendChild(container);
    return container;
}

/**
 * Table sorting
 */
function setupTableSorting() {
    document.querySelectorAll('.sortable-table th[data-sort]').forEach(header => {
        header.addEventListener('click', function() {
            const table = this.closest('table');
            const column = this.getAttribute('data-sort');
            const direction = this.classList.contains('asc') ? 'desc' : 'asc';
            
            sortTable(table, column, direction);
            
            // Update header classes
            table.querySelectorAll('th').forEach(th => th.classList.remove('asc', 'desc'));
            this.classList.add(direction);
        });
        
        header.style.cursor = 'pointer';
    });
}

function sortTable(table, column, direction) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    rows.sort((a, b) => {
        const aVal = a.querySelector(`[data-sort="${column}"]`)?.textContent?.trim() || '';
        const bVal = b.querySelector(`[data-sort="${column}"]`)?.textContent?.trim() || '';
        
        // Try to parse as numbers
        const aNum = parseFloat(aVal);
        const bNum = parseFloat(bVal);
        
        if (!isNaN(aNum) && !isNaN(bNum)) {
            return direction === 'asc' ? aNum - bNum : bNum - aNum;
        }
        
        // String comparison
        return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
    });
    
    rows.forEach(row => tbody.appendChild(row));
}

/**
 * Lazy loading for images
 */
function setupLazyLoading() {
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    observer.unobserve(img);
                }
            });
        });
        
        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }
}

/**
 * Multi-discipline handlers
 */
function setupMultiDisciplineHandlers() {
    // Competition discipline checkbox validation
    setupCompetitionDisciplineValidation();
    
    // Result discipline auto-updating
    setupResultDisciplineUpdating();
    
    // Add discipline modal handlers
    setupAddDisciplineHandlers();
    
    console.log('🎯 Multi-discipline handlers initialized');
}

function setupCompetitionDisciplineValidation() {
    // Find competition forms with discipline checkboxes
    const competitionForms = document.querySelectorAll('form');
    
    competitionForms.forEach(form => {
        const disciplineCheckboxes = form.querySelectorAll('input[name="disciplines[]"], input[name="comp_disciplines[]"]');
        
        if (disciplineCheckboxes.length > 0) {
            form.addEventListener('submit', function(e) {
                const checkedBoxes = form.querySelectorAll('input[name="disciplines[]"]:checked, input[name="comp_disciplines[]"]:checked');
                
                if (checkedBoxes.length === 0) {
                    e.preventDefault();
                    showToast('Palun vali vähemalt üks distsipliin!', 'warning');
                    
                    // Focus first checkbox
                    disciplineCheckboxes[0].focus();
                    return false;
                }
            });
        }
    });
}

function setupResultDisciplineUpdating() {
    // 🔧 PARANDATUD: ADMIN RESULTS kasutab modali ID-sid
    const adminCompetitionSelect = document.getElementById('modalCompetitionId');
    if (adminCompetitionSelect) {
        adminCompetitionSelect.addEventListener('change', updateCompetitionDisciplines);
    }
    
    // 🔧 PARANDATUD: ATHLETE ADD RESULT kasutab tavalist ID-d
    const athleteCompetitionSelect = document.getElementById('competitionId');
    if (athleteCompetitionSelect && !adminCompetitionSelect) {
        // Ainult kui ei ole admin lehel
        athleteCompetitionSelect.addEventListener('change', updateAthleteCompetitionDisciplines);
    }
    
    // Discipline field change handler - 🔧 PARANDATUD: kontrollime mõlemat
    const adminDisciplineSelect = document.getElementById('modalDiscipline');
    const athleteDisciplineSelect = document.getElementById('discipline');
    
    if (adminDisciplineSelect) {
        adminDisciplineSelect.addEventListener('change', toggleDisciplineFields);
    }
    
    if (athleteDisciplineSelect && !adminDisciplineSelect) {
        athleteDisciplineSelect.addEventListener('change', toggleDisciplineFields);
    }
}

function setupAddDisciplineHandlers() {
    // Make sure add discipline modal functions are available
    if (typeof showAddDisciplineModal === 'undefined') {
        window.showAddDisciplineModal = function(competitionId, discipline) {
            const disciplineName = getDisciplineName(discipline);
            
            const modal = document.getElementById('addDisciplineModal');
            if (modal) {
                document.getElementById('add_disc_competition_id').value = competitionId;
                document.getElementById('add_disc_discipline').value = discipline;
                document.getElementById('addDisciplineText').textContent = 
                    `Kas tahad lisada distsipliini "${disciplineName}" sellele võistlusele?`;
                
                openModal('addDisciplineModal');
            } else {
                // Fallback: reload page with parameters
                const url = new URL(window.location);
                url.searchParams.set('add_discipline', discipline);
                url.searchParams.set('competition_id', competitionId);
                if (confirm(`Kas tahad lisada distsipliini "${disciplineName}" sellele võistlusele?`)) {
                    window.location.href = url.toString();
                }
            }
        };
    }
}

/**
 * UUENDATUD: Multi-day handlers
 */
function setupMultiDayHandlers() {
    // Multi-day checkbox listener (admin competitions)
    const multiDayCheckbox = document.getElementById('is_multi_day');
    if (multiDayCheckbox) {
        multiDayCheckbox.addEventListener('change', toggleDateFields);
        console.log('🗓️ Multi-day handlers initialized');
    }
}

/**
 * UUENDATUD: Multi-day kuupäevade toggle funktsioon
 */
function toggleDateFields() {
    const isMultiDay = document.getElementById('is_multi_day')?.checked;
    const singleField = document.getElementById('single-date-field');
    const multiFields = document.getElementById('multi-date-fields');
    
    if (!singleField || !multiFields) {
        console.log('Date fields not found, skipping toggle');
        return;
    }
    
    if (isMultiDay) {
        singleField.style.display = 'none';
        multiFields.style.display = 'grid';
        
        // Eemalda required single date väljalt
        const dateField = document.getElementById('date');
        if (dateField) dateField.removeAttribute('required');
        
        // Lisa required multi date väljadele
        const startDateField = document.getElementById('start_date');
        const endDateField = document.getElementById('end_date');
        if (startDateField) startDateField.setAttribute('required', 'required');
        if (endDateField) endDateField.setAttribute('required', 'required');
        
        console.log('✅ Multi-day mode enabled');
    } else {
        singleField.style.display = 'block';
        multiFields.style.display = 'none';
        
        // Lisa required single date väljale
        const dateField = document.getElementById('date');
        if (dateField) dateField.setAttribute('required', 'required');
        
        // Eemalda required multi date väljadelt
        const startDateField = document.getElementById('start_date');
        const endDateField = document.getElementById('end_date');
        if (startDateField) startDateField.removeAttribute('required');
        if (endDateField) endDateField.removeAttribute('required');
        
        console.log('✅ Single-day mode enabled');
    }
}

/**
 * Utility functions
 */
function formatNumber(num, decimals = 1) {
    return Number(num).toFixed(decimals);
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('et-EE');
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

/**
 * API helpers
 */
async function apiCall(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API call failed:', error);
        showToast('Viga andmete laadimisel', 'error');
        throw error;
    }
}

/**
 * Admin specific functions
 */
function editUser(user) {
    // 🧹 Puhasta vorm enne täitmist
    document.getElementById('userForm').reset();

    // Täida vormi väljad kasutaja andmetega
    document.getElementById('user_id').value = user.id;
    document.getElementById('firstName').value = user.firstName;
    document.getElementById('lastName').value = user.lastName;
    document.getElementById('email').value = user.email;
    document.getElementById('phone').value = user.phone || '';
    document.getElementById('birthDate').value = user.birthDate;
    document.getElementById('username').value = user.username;
    document.getElementById('password').value = '';
    document.getElementById('role').value = user.role;
    document.getElementById('isActive').checked = user.isActive == 1;

    // Modal pealkiri ja nupud
    document.getElementById('modalTitle').textContent = 'Muuda kasutajat';
    document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
    document.getElementById('passwordRequired').textContent = '';
    document.getElementById('passwordHelp').textContent = 'Jäta tühjaks kui ei taha muuta';
    document.getElementById('password').removeAttribute('required');

    // Ava modal
    openModal('userModal');
}

function editCompetition(competition) {
    // Fill form with competition data
    document.getElementById('competition_id').value = competition.id;
    document.getElementById('name').value = competition.name;
    document.getElementById('location').value = competition.location || '';
    document.getElementById('description').value = competition.description || '';
    
    // UUENDATUD: Multi-day toe lisamine
    const isMultiDay = competition.is_multi_day == 1;
    const multiDayCheckbox = document.getElementById('is_multi_day');
    if (multiDayCheckbox) {
        multiDayCheckbox.checked = isMultiDay;
        
        if (isMultiDay) {
            document.getElementById('start_date').value = competition.start_date || '';
            document.getElementById('end_date').value = competition.end_date || '';
        } else {
            document.getElementById('date').value = competition.start_date || competition.date || '';
        }
        
        toggleDateFields();
    } else {
        // Fallback kui multi-day pole saadaval
        document.getElementById('date').value = competition.start_date || competition.date || '';
    }
    
    // UUENDATUD: Täida distsipliinide checkboxid
    const disciplineCheckboxes = document.querySelectorAll('input[name="disciplines[]"]');
    disciplineCheckboxes.forEach(checkbox => {
        checkbox.checked = false; // Algul kõik maha
    });
    
    // Märgi valitud distsipliinid
    if (competition.disciplines_array) {
        competition.disciplines_array.forEach(discipline => {
            const checkbox = document.querySelector(`input[name="disciplines[]"][value="${discipline}"]`);
            if (checkbox) {
                checkbox.checked = true;
            }
        });
    } else {
        // Tagasiühilduvus: kui disciplines_array puudub, kasuta vana discipline välja
        const checkbox = document.querySelector(`input[name="disciplines[]"][value="${competition.discipline}"]`);
        if (checkbox) {
            checkbox.checked = true;
        }
    }
    
    // Update modal title and button
    document.getElementById('modalTitle').textContent = 'Muuda võistlust';
    document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
    
    openModal('competitionModal');
}

// 🔧 PARANDATUD: editResult funktsioon - NULL-SAFE ja SMART DETECTION
function editResult(result) {
    console.log('✏️ Editing result:', result.id);
    
    // PARANDATUD: Kontrolli elemendide olemasolu enne kasutamist
    const resultIdField = document.getElementById('result_id');
    const placementField = document.getElementById('placement');
    const finishedField = document.getElementById('finished');
    const notesField = document.getElementById('notes');
    
    if (!resultIdField) {
        console.error('❌ result_id field not found');
        return;
    }
    
    // Fill basic form data - ainult kui elemendid on olemas
    resultIdField.value = result.id;
    
    if (placementField) {
        placementField.value = result.placement || '';
    }
    
    if (finishedField) {
        finishedField.checked = result.finished == 1;
    }
    
    if (notesField) {
        notesField.value = result.notes || '';
    }
    
    // 🔧 PARANDATUD: Kontrolli kas oleme admin või athlete lehel
    const adminCompetitionSelect = document.getElementById('modalCompetitionId');
    const athleteCompetitionSelect = document.getElementById('competitionId');
    const adminDisciplineSelect = document.getElementById('modalDiscipline');
    const athleteDisciplineSelect = document.getElementById('discipline');
    
    console.log('Elements found:', {
        adminCompetition: !!adminCompetitionSelect,
        athleteCompetition: !!athleteCompetitionSelect,
        adminDiscipline: !!adminDisciplineSelect,
        athleteDiscipline: !!athleteDisciplineSelect
    });
    
    if (adminCompetitionSelect && adminDisciplineSelect) {
        // ADMIN LEHT - kasuta modali ID-sid
        console.log('🔧 Using ADMIN modal IDs');
        
        const userIdField = document.getElementById('userId');
        if (userIdField) {
            userIdField.value = result.userId;
        }
        
        adminCompetitionSelect.value = result.competitionId;
        
        // Update competition disciplines first
        updateCompetitionDisciplines();
        
        // Then set discipline after delay
        setTimeout(() => {
            adminDisciplineSelect.value = result.discipline;
            toggleDisciplineFields();
            
            // Fill discipline-specific fields
            setTimeout(() => fillDisciplineSpecificFields(result), 100);
        }, 200);
        
    } else if (athleteCompetitionSelect && athleteDisciplineSelect) {
        // ATHLETE LEHT - kasuta tavalist ID-d
        console.log('🔧 Using ATHLETE IDs');
        
        // Leia võistlus availableCompetitions arrayist (kui see on defineeritud)
        if (typeof availableCompetitions !== 'undefined') {
            const competition = availableCompetitions.find(c => c.id == result.competitionId);
            if (competition) {
                // Kui on search mode, täida ka search field
                const searchInput = document.getElementById('competition_search');
                if (searchInput && !searchInput.style.display.includes('none')) {
                    searchInput.value = competition.name;
                }
                
                // Vali dropdown'is
                athleteCompetitionSelect.value = result.competitionId;
                
                // Näita valitud võistluse infot kui funktsioon on saadaval
                if (typeof showSelectedCompetition === 'function') {
                    showSelectedCompetition(competition);
                }
            }
        } else {
            // Fallback kui availableCompetitions ei ole defineeritud
            athleteCompetitionSelect.value = result.competitionId;
        }
        
        // Update competition disciplines
        if (typeof updateAthleteCompetitionDisciplines === 'function') {
            updateAthleteCompetitionDisciplines();
        }
        
        // Set discipline after delay
        setTimeout(() => {
            athleteDisciplineSelect.value = result.discipline;
            toggleDisciplineFields();
            
            // Fill discipline-specific fields
            setTimeout(() => fillDisciplineSpecificFields(result), 100);
        }, 200);
        
    } else {
        console.error('❌ Neither admin nor athlete elements found properly');
        console.log('Available elements:', {
            adminComp: adminCompetitionSelect?.id,
            athleteComp: athleteCompetitionSelect?.id,
            adminDisc: adminDisciplineSelect?.id,
            athleteDisc: athleteDisciplineSelect?.id
        });
        return;
    }
    
    // Update modal title and button
    const modalTitle = document.getElementById('modalTitle');
    const saveButtonText = document.getElementById('saveButtonText');
    
    if (modalTitle) {
        modalTitle.textContent = 'Muuda tulemust';
    }
    
    if (saveButtonText) {
        saveButtonText.textContent = 'Salvesta muudatused';
    }
    
    // Open modal
    openModal('resultModal');
}

// 🔧 PARANDATUD: fillDisciplineSpecificFields helper funktsioon
function fillDisciplineSpecificFields(result) {
    console.log('🔄 Filling discipline-specific fields for:', result.discipline);
    
    try {
        if (result.discipline === 'koolisoit') {
            const percentageField = document.getElementById('percentage');
            const schemeField = document.getElementById('scheme');
            
            if (percentageField) percentageField.value = result.percentage || '';
            if (schemeField) schemeField.value = result.scheme || '';
            
        } else if (result.discipline === 'takistussoit') {
            const faultPointsField = document.getElementById('faultPoints');
            const heightField = document.getElementById('height');
            
            if (faultPointsField) faultPointsField.value = result.faultPoints || '';
            if (heightField) heightField.value = result.height || '';
            
            // Aeg - kontrolli mõlemat võimalikku ID-d
            if (result.time_seconds) {
                const jumpingTimeInput = document.getElementById('time_input_jumping') || 
                                       document.getElementById('time_input');
                if (jumpingTimeInput && typeof formatSecondsToInput === 'function') {
                    jumpingTimeInput.value = formatSecondsToInput(result.time_seconds);
                }
            }
            
        } else if (result.discipline === 'kestvusratsutamine') {
            const distanceField = document.getElementById('distance');
            const pulseField = document.getElementById('pulse');
            
            if (distanceField) distanceField.value = result.distance || '';
            if (pulseField) pulseField.value = result.pulse || '';
            
            // Aeg - kontrolli mõlemat võimalikku ID-d
            if (result.time_seconds) {
                const enduranceTimeInput = document.getElementById('time_input_endurance') || 
                                          document.getElementById('time_input');
                if (enduranceTimeInput && typeof formatSecondsToInput === 'function') {
                    enduranceTimeInput.value = formatSecondsToInput(result.time_seconds, true);
                }
            }
        }
        
        console.log('✅ Discipline-specific fields filled successfully');
        
    } catch (error) {
        console.error('❌ Error filling discipline-specific fields:', error);
    }
}

// 🔧 PARANDATUD: updateCompetitionDisciplines funktsioon (admin jaoks)
function updateCompetitionDisciplines() {
    console.log('🎯 Admin updateCompetitionDisciplines called');
    
    const competitionSelect = document.getElementById('modalCompetitionId');
    const disciplineSelect = document.getElementById('modalDiscipline');
    const disciplineHelp = document.getElementById('modalDisciplineHelp');
    
    if (!competitionSelect || !disciplineSelect) {
        console.error('❌ Admin modal elements not found');
        return false;
    }
    
    const selectedOption = competitionSelect.options[competitionSelect.selectedIndex];
    
    if (selectedOption && selectedOption.value) {
        try {
            let disciplines = [];
            const disciplinesData = selectedOption.dataset.disciplines;
            const singleDiscipline = selectedOption.dataset.singleDiscipline;
            
            if (disciplinesData) {
                try {
                    disciplines = JSON.parse(disciplinesData);
                    if (!Array.isArray(disciplines)) {
                        throw new Error('Parsed data is not an array');
                    }
                } catch (parseError) {
                    console.warn('⚠️ JSON parse failed, using fallback:', parseError);
                    disciplines = singleDiscipline ? [singleDiscipline] : [];
                }
            } else if (singleDiscipline) {
                disciplines = [singleDiscipline];
            }
            
            // Clear and populate discipline dropdown
            disciplineSelect.innerHTML = '';
            
            if (disciplines.length === 0) {
                disciplineSelect.innerHTML = '<option value="">Viga distsipliinide laadimisel</option>';
                if (disciplineHelp) disciplineHelp.textContent = 'Viga võistluse distsipliinide laadimisel';
                
            } else if (disciplines.length === 1) {
                // Single discipline - auto-select
                const discipline = disciplines[0];
                const disciplineName = getDisciplineName(discipline);
                disciplineSelect.innerHTML = `<option value="${discipline}" selected>${disciplineName}</option>`;
                if (disciplineHelp) disciplineHelp.textContent = 'Automaatselt valitud (ainuke distsipliin sellel võistlusel)';
                
                // Auto-show discipline fields
                setTimeout(() => toggleDisciplineFields(), 100);
                
            } else {
                // Multiple disciplines - show selection
                disciplineSelect.innerHTML = '<option value="">Vali distsipliin</option>';
                disciplines.forEach(discipline => {
                    const option = document.createElement('option');
                    option.value = discipline;
                    option.textContent = getDisciplineName(discipline);
                    disciplineSelect.appendChild(option);
                });
                if (disciplineHelp) disciplineHelp.textContent = `Sellel võistlusel on ${disciplines.length} distsipliini. Vali sobiv.`;
            }
            
            console.log('✅ Admin disciplines updated successfully');
            return true;
            
        } catch (error) {
            console.error('❌ Error in admin updateCompetitionDisciplines:', error);
            disciplineSelect.innerHTML = '<option value="">Süsteemi viga</option>';
            if (disciplineHelp) disciplineHelp.textContent = 'Süsteemi viga distsipliinide laadimisel';
            return false;
        }
    } else {
        // No competition selected
        disciplineSelect.innerHTML = '<option value="">Vali esmalt võistlus</option>';
        if (disciplineHelp) disciplineHelp.textContent = 'Vali esmalt võistlus, siis kuvatakse selle distsipliinid';
    }
    
    // Hide all discipline fields when competition changes
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
    
    return true;
}

// 🔧 UUENDATUD: Athlete competition disciplines update (kasutab tavalist ID-d)
function updateAthleteCompetitionDisciplines() {
    console.log('🎯 Athlete updateCompetitionDisciplines called');
    
    const competitionSelect = document.getElementById('competitionId');
    const disciplineSelect = document.getElementById('discipline');
    const disciplineHelp = document.getElementById('disciplineHelp');
    
    if (!competitionSelect || !disciplineSelect) {
        console.error('❌ Athlete elements not found');
        return false;
    }
    
    const selectedOption = competitionSelect.options[competitionSelect.selectedIndex];
    
    if (selectedOption && selectedOption.value) {
        try {
            let disciplines = [];
            const disciplinesData = selectedOption.dataset.disciplines;
            const singleDiscipline = selectedOption.dataset.singleDiscipline;
            
            if (disciplinesData) {
                try {
                    disciplines = JSON.parse(disciplinesData);
                    if (!Array.isArray(disciplines)) {
                        throw new Error('Parsed data is not an array');
                    }
                } catch (parseError) {
                    console.warn('⚠️ JSON parse failed, using fallback:', parseError);
                    disciplines = singleDiscipline ? [singleDiscipline] : [];
                }
            } else if (singleDiscipline) {
                disciplines = [singleDiscipline];
            }
            
            // Clear and populate discipline dropdown
            disciplineSelect.innerHTML = '';
            
            if (disciplines.length === 0) {
                disciplineSelect.innerHTML = '<option value="">Viga distsipliinide laadimisel</option>';
                if (disciplineHelp) disciplineHelp.textContent = 'Viga võistluse distsipliinide laadimisel';
                
            } else if (disciplines.length === 1) {
                // Single discipline - auto-select
                const discipline = disciplines[0];
                const disciplineName = getDisciplineName(discipline);
                disciplineSelect.innerHTML = `<option value="${discipline}" selected>${disciplineName}</option>`;
                if (disciplineHelp) disciplineHelp.textContent = 'Automaatselt valitud (ainuke distsipliin sellel võistlusel)';
                
                // Auto-show discipline fields
                setTimeout(() => toggleDisciplineFields(), 100);
                
            } else {
                // Multiple disciplines - show selection
                disciplineSelect.innerHTML = '<option value="">Vali distsipliin</option>';
                disciplines.forEach(discipline => {
                    const option = document.createElement('option');
                    option.value = discipline;
                    option.textContent = getDisciplineName(discipline);
                    disciplineSelect.appendChild(option);
                });
                if (disciplineHelp) disciplineHelp.textContent = `Sellel võistlusel on ${disciplines.length} distsipliini. Vali sobiv.`;
            }
            
            console.log('✅ Athlete disciplines updated successfully');
            return true;
            
        } catch (error) {
            console.error('❌ Error in athlete updateCompetitionDisciplines:', error);
            disciplineSelect.innerHTML = '<option value="">Süsteemi viga</option>';
            if (disciplineHelp) disciplineHelp.textContent = 'Süsteemi viga distsipliinide laadimisel';
            return false;
        }
    } else {
        // No competition selected
        disciplineSelect.innerHTML = '<option value="">Vali esmalt võistlus</option>';
        if (disciplineHelp) disciplineHelp.textContent = 'Vali esmalt võistlus, siis kuvatakse selle distsipliinid';
    }
    
    // Hide all discipline fields when competition changes
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
    
    return true;
}

function getDisciplineName(discipline) {
    const names = {
        'koolisoit': 'Koolisõit',
        'takistussoit': 'Takistussõit', 
        'kestvusratsutamine': 'Kestvusratsutamine'
    };
    return names[discipline] || discipline;
}

function toggleDisciplineFields() {
    console.log('🔄 toggleDisciplineFields called');
    
    // 🔧 PARANDATUD: Kontrollime mõlemat lehte
    let discipline;
    const adminDisciplineSelect = document.getElementById('modalDiscipline');
    const athleteDisciplineSelect = document.getElementById('discipline');
    
    if (adminDisciplineSelect && adminDisciplineSelect.offsetParent !== null) {
        // Admin leht on aktiivne
        discipline = adminDisciplineSelect.value;
        console.log('Admin discipline selected:', discipline);
    } else if (athleteDisciplineSelect) {
        // Athlete leht
        discipline = athleteDisciplineSelect.value;
        console.log('Athlete discipline selected:', discipline);
    }
    
    if (!discipline) {
        console.log('No discipline selected, hiding all fields');
        document.querySelectorAll('.discipline-fields').forEach(field => {
            field.style.display = 'none';
        });
        return;
    }
    
    // Hide all fields first
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
    
    // Show relevant fields and set required attributes
    if (discipline === 'koolisoit') {
        const dressageFields = document.getElementById('dressageFields');
        if (dressageFields) {
            dressageFields.style.display = 'block';
            console.log('✅ Showing dressage fields');
        }
        setFieldRequired('percentage', true);
        setFieldRequired('scheme', true);
        setFieldRequired('faultPoints', false);
        setFieldRequired('distance', false);
        
    } else if (discipline === 'takistussoit') {
        const jumpingFields = document.getElementById('jumpingFields');
        if (jumpingFields) {
            jumpingFields.style.display = 'block';
            console.log('✅ Showing jumping fields');
        }
        setFieldRequired('faultPoints', true);
        setFieldRequired('percentage', false);
        setFieldRequired('scheme', false);
        setFieldRequired('distance', false);
        
    } else if (discipline === 'kestvusratsutamine') {
        const enduranceFields = document.getElementById('enduranceFields');
        if (enduranceFields) {
            enduranceFields.style.display = 'block';
            console.log('✅ Showing endurance fields');
        }
        setFieldRequired('distance', true);
        setFieldRequired('percentage', false);
        setFieldRequired('scheme', false);
        setFieldRequired('faultPoints', false);
    }
}

function setFieldRequired(fieldId, required) {
    const field = document.getElementById(fieldId);
    if (field) {
        if (required) {
            field.setAttribute('required', 'required');
        } else {
            field.removeAttribute('required');
        }
    }
}

// Time formatting functions
function parseTimeInput(timeStr, includeHours = false) {
    if (!timeStr) return null;
    
    const parts = timeStr.split(':');
    if (includeHours && parts.length === 3) {
        return parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60 + parseInt(parts[2]);
    } else if (!includeHours && parts.length === 2) {
        return parseInt(parts[0]) * 60 + parseInt(parts[1]);
    } else if (parts.length === 1 && !isNaN(parseInt(parts[0]))) {
        return parseInt(parts[0]) * 60;
    }
    return null;
}

function formatSecondsToInput(seconds, includeHours = false) {
    if (!seconds) return '';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    
    if (includeHours) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    } else {
        return `${minutes}:${secs.toString().padStart(2, '0')}`;
    }
}

/**
 * Reset form functions
 */
function resetUserForm() {
    const form = document.getElementById('userForm');
    if (form) {
        form.reset();
        document.getElementById('user_id').value = '';
        document.getElementById('modalTitle').textContent = 'Lisa kasutaja';
        document.getElementById('saveButtonText').textContent = 'Lisa kasutaja';
        document.getElementById('passwordRequired').textContent = '*';
        document.getElementById('passwordHelp').textContent = 'Vähemalt 6 tähemärki';
        document.getElementById('password').setAttribute('required', 'required');
        document.getElementById('isActive').checked = true;
    }
}

function resetCompetitionForm() {
    const form = document.getElementById('competitionForm');
    if (form) {
        form.reset();
        document.getElementById('competition_id').value = '';
        document.getElementById('modalTitle').textContent = 'Lisa võistlus';
        document.getElementById('saveButtonText').textContent = 'Lisa võistlus';
        
        // Eemalda kõik distsipliinide valikud
        const disciplineCheckboxes = document.querySelectorAll('input[name="disciplines[]"]');
        disciplineCheckboxes.forEach(checkbox => {
            checkbox.checked = false;
        });
        
        // UUENDATUD: Reset multi-day fields
        const multiDayCheckbox = document.getElementById('is_multi_day');
        if (multiDayCheckbox) {
            multiDayCheckbox.checked = false;
            toggleDateFields();
        }
    }
}

function resetResultForm() {
    const form = document.getElementById('resultForm');
    if (form) {
        form.reset();
        document.getElementById('result_id').value = '';
        document.getElementById('modalTitle').textContent = 'Lisa tulemus';
        document.getElementById('saveButtonText').textContent = 'Lisa tulemus';
        document.getElementById('finished').checked = true;
        
        // 🔧 PARANDATUD: Reset discipline dropdown õige ID-ga
        const adminDisciplineSelect = document.getElementById('modalDiscipline');
        const athleteDisciplineSelect = document.getElementById('discipline');
        const adminDisciplineHelp = document.getElementById('modalDisciplineHelp');
        const athleteDisciplineHelp = document.getElementById('disciplineHelp');
        
        if (adminDisciplineSelect) {
            // Admin leht
            adminDisciplineSelect.innerHTML = '<option value="">Vali esmalt võistlus</option>';
            if (adminDisciplineHelp) {
                adminDisciplineHelp.textContent = 'Vali esmalt võistlus, siis kuvatakse selle distsipliinid';
            }
        }
        
        if (athleteDisciplineSelect && !adminDisciplineSelect) {
            // Athlete leht
            athleteDisciplineSelect.innerHTML = '<option value="">Vali esmalt võistlus</option>';
            if (athleteDisciplineHelp) {
                athleteDisciplineHelp.textContent = 'Vali esmalt võistlus, siis kuvatakse selle distsipliinid';
            }
        }
        
        // Hide all discipline fields
        document.querySelectorAll('.discipline-fields').forEach(field => {
            field.style.display = 'none';
        });
    }
}

/**
 * Export functions for global use (both new and legacy support)
 */
window.EstrekaApp = {
    showToast,
    openModal,
    closeModal,
    toggleMobileMenu,
    toggleUserMenu,
    formatNumber,
    formatDate,
    apiCall,
    editUser,
    editCompetition,
    editResult,
    updateCompetitionDisciplines,
    updateAthleteCompetitionDisciplines,
    toggleDisciplineFields,
    toggleDateFields, // UUENDATUD: Multi-day funktsioon
    getDisciplineName,
    parseTimeInput,
    formatSecondsToInput
};

// Make modal and admin functions globally available for direct calls
window.openModal = openModal;
window.closeModal = closeModal;
window.toggleMobileMenu = toggleMobileMenu;
window.toggleUserMenu = toggleUserMenu;
window.editUser = editUser;
window.editCompetition = editCompetition;
window.editResult = editResult;
window.updateCompetitionDisciplines = updateCompetitionDisciplines;
window.updateAthleteCompetitionDisciplines = updateAthleteCompetitionDisciplines;
window.toggleDisciplineFields = toggleDisciplineFields;
window.toggleDateFields = toggleDateFields; // UUENDATUD: Multi-day funktsioon
window.getDisciplineName = getDisciplineName;
window.parseTimeInput = parseTimeInput;
window.formatSecondsToInput = formatSecondsToInput;
window.fillDisciplineSpecificFields = fillDisciplineSpecificFields;

// Close mobile menu on window resize
window.addEventListener('resize', function() {
    if (window.innerWidth > 768) {
        const mobileNav = document.querySelector('.mobile-nav');
        const toggle = document.querySelector('.mobile-menu-toggle');
        
        if (mobileNav && toggle) {
            mobileNav.classList.remove('show');
            toggle.classList.remove('active');
            document.body.classList.remove('menu-open');
        }
    }
});

// Performance monitoring
if ('performance' in window) {
    window.addEventListener('load', function() {
        const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
        console.log(`Page load time: ${loadTime}ms`);
    });
}

console.log('🔧 FIXED main.js with multi-day support and NULL-SAFE editResult loaded successfully!');