/**
 * Advanced Marks Distribution System
 * Enhanced JavaScript functionality for modern UI/UX
 */

class AdvancedMarksSystem {
    constructor() {
        this.totalMarks = 0;
        this.distributedMarks = 0;
        this.markInputs = [];
        this.progressRing = null;
        this.notifications = [];
        
        this.init();
    }
    
    init() {
        this.setupElements();
        this.bindEvents();
        this.initializeAnimations();
        this.setupNotificationSystem();
        this.loadSavedData();
    }
    
    setupElements() {
        this.markInputs = document.querySelectorAll('.mark-input');
        this.totalMarksInput = document.getElementById('total_marks');
        this.progressRing = document.getElementById('progress-circle');
        this.distributedSpan = document.getElementById('total-distributed');
        this.summaryDiv = document.getElementById('marks-summary');
        this.statusDiv = document.getElementById('distribution-status');
    }
    
    bindEvents() {
        // Mark input events
        this.markInputs.forEach(input => {
            input.addEventListener('input', (e) => this.handleMarkInput(e));
            input.addEventListener('focus', (e) => this.handleInputFocus(e));
            input.addEventListener('blur', (e) => this.handleInputBlur(e));
        });
        
        // Total marks input
        if (this.totalMarksInput) {
            this.totalMarksInput.addEventListener('input', (e) => this.handleTotalMarksChange(e));
        }
        
        // Form submission
        const form = document.querySelector('form');
        if (form) {
            form.addEventListener('submit', (e) => this.handleFormSubmit(e));
        }
        
        // Edit buttons
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.handleEditClick(e));
        });
        
        // Auto-save functionality
        this.setupAutoSave();
        
        // Keyboard shortcuts
        this.setupKeyboardShortcuts();
    }
    
    handleMarkInput(event) {
        const input = event.target;
        
        // Add visual feedback
        this.addInputAnimation(input, 'pulse');
        
        // Validate input
        this.validateMarkInput(input);
        
        // Update calculations
        this.updateMarksCalculation();
        
        // Update progress visualization
        this.updateProgressVisualization();
        
        // Save to localStorage
        this.saveToLocalStorage();
    }
    
    handleInputFocus(event) {
        const input = event.target;
        input.parentElement.classList.add('focused');
        this.addInputAnimation(input, 'fadeIn');
    }
    
    handleInputBlur(event) {
        const input = event.target;
        input.parentElement.classList.remove('focused');
        this.validateMarkInput(input);
    }
    
    handleTotalMarksChange(event) {
        const total = parseInt(event.target.value) || 0;
        this.totalMarks = total;
        
        // Auto-calculate pass marks (40% of total)
        const passMarksInput = document.getElementById('overall_pass_marks');
        if (passMarksInput) {
            const passMarks = Math.ceil(total * 0.4);
            passMarksInput.value = passMarks;
            this.addInputAnimation(passMarksInput, 'bounce');
        }
        
        this.updateMarksCalculation();
        this.updateProgressVisualization();
        this.saveToLocalStorage();
    }
    
    validateMarkInput(input) {
        const value = parseInt(input.value) || 0;
        const max = parseInt(input.getAttribute('max')) || 1000;
        const min = parseInt(input.getAttribute('min')) || 0;
        
        input.classList.remove('is-invalid', 'is-valid');
        
        if (value < min || value > max) {
            input.classList.add('is-invalid');
            this.showNotification('অবৈধ মান! সঠিক পরিসরে মান দিন।', 'error');
        } else if (value > 0) {
            input.classList.add('is-valid');
        }
    }
    
    updateMarksCalculation() {
        let total = 0;
        
        this.markInputs.forEach(input => {
            total += parseInt(input.value) || 0;
        });
        
        this.distributedMarks = total;
        
        if (this.distributedSpan) {
            this.distributedSpan.textContent = total;
        }
        
        this.updateSummaryStatus();
        this.updateMarksChart();
    }
    
    updateSummaryStatus() {
        if (!this.summaryDiv || !this.statusDiv) return;
        
        const total = this.totalMarks;
        const distributed = this.distributedMarks;
        
        // Remove existing classes
        this.summaryDiv.className = 'marks-summary';
        
        if (distributed === total && total > 0) {
            this.summaryDiv.classList.add('success');
            this.statusDiv.innerHTML = '<i class="fas fa-check-circle"></i> সঠিক বিভাজন';
            this.addAnimation(this.summaryDiv, 'pulse');
        } else if (distributed > total) {
            this.summaryDiv.classList.add('danger');
            this.statusDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> অতিরিক্ত নম্বর';
            this.addAnimation(this.summaryDiv, 'shakeX');
        } else if (distributed > 0) {
            this.summaryDiv.classList.add('warning');
            this.statusDiv.innerHTML = '<i class="fas fa-clock"></i> আরো নম্বর প্রয়োজন';
            this.addAnimation(this.summaryDiv, 'bounce');
        } else {
            this.statusDiv.innerHTML = 'নম্বর বিভাজন করুন';
        }
    }
    
    updateProgressVisualization() {
        if (!this.progressRing) return;
        
        const percentage = this.totalMarks > 0 ? (this.distributedMarks / this.totalMarks) * 100 : 0;
        const circumference = 2 * Math.PI * 50; // radius = 50
        const strokeDasharray = Math.min((percentage / 100) * circumference, circumference);
        
        this.progressRing.style.strokeDasharray = `${strokeDasharray} ${circumference}`;
        
        // Change color based on status
        if (percentage === 100) {
            this.progressRing.style.stroke = '#56ab2f';
        } else if (percentage > 100) {
            this.progressRing.style.stroke = '#e74c3c';
        } else if (percentage > 0) {
            this.progressRing.style.stroke = '#f39c12';
        } else {
            this.progressRing.style.stroke = '#667eea';
        }
    }
    
    updateMarksChart() {
        const chartContainer = document.getElementById('marks-chart');
        if (!chartContainer) return;
        
        const marks = {
            cq: parseInt(document.getElementById('cq_marks')?.value) || 0,
            mcq: parseInt(document.getElementById('mcq_marks')?.value) || 0,
            practical: parseInt(document.getElementById('practical_marks')?.value) || 0,
            assignment: parseInt(document.getElementById('assignment_marks')?.value) || 0,
            attendance: parseInt(document.getElementById('attendance_marks')?.value) || 0
        };
        
        const total = this.totalMarks || 1;
        
        let chartHTML = '<div class="marks-chart"><h6>নম্বর বিভাজন চার্ট</h6>';
        
        Object.entries(marks).forEach(([type, value]) => {
            if (value > 0) {
                const percentage = (value / total) * 100;
                const label = this.getMarkTypeLabel(type);
                
                chartHTML += `
                    <div class="mb-2">
                        <div class="d-flex justify-content-between">
                            <span>${label}</span>
                            <span>${value} (${percentage.toFixed(1)}%)</span>
                        </div>
                        <div class="chart-bar">
                            <div class="chart-fill ${type}" style="width: ${percentage}%"></div>
                        </div>
                    </div>
                `;
            }
        });
        
        chartHTML += '</div>';
        chartContainer.innerHTML = chartHTML;
    }
    
    getMarkTypeLabel(type) {
        const labels = {
            cq: 'সৃজনশীল প্রশ্ন',
            mcq: 'বহুনির্বাচনি',
            practical: 'ব্যবহারিক',
            assignment: 'অ্যাসাইনমেন্ট',
            attendance: 'উপস্থিতি'
        };
        return labels[type] || type;
    }
    
    handleEditClick(event) {
        const btn = event.target.closest('.edit-btn');
        if (!btn) return;
        
        // Show loading state
        const originalHTML = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
        
        setTimeout(() => {
            this.populateFormFromData(btn.dataset);
            
            // Restore button
            btn.innerHTML = originalHTML;
            btn.disabled = false;
            
            // Scroll to form
            this.scrollToForm();
            
            // Show success notification
            this.showNotification('ডেটা লোড করা হয়েছে', 'success');
        }, 500);
    }
    
    populateFormFromData(data) {
        const fields = [
            'subject_id', 'class_id', 'session', 'group_name', 'exam_type',
            'total_marks', 'cq_marks', 'mcq_marks', 'practical_marks',
            'assignment_marks', 'attendance_marks', 'overall_pass_marks',
            'cq_pass_marks', 'mcq_pass_marks', 'practical_pass_marks', 'grade_system'
        ];
        
        fields.forEach(field => {
            const element = document.getElementById(field);
            if (element && data[field.replace('_', '')]) {
                element.value = data[field.replace('_', '')];
                this.addInputAnimation(element, 'fadeIn');
            }
        });
        
        this.updateMarksCalculation();
        this.updateProgressVisualization();
    }
    
    scrollToForm() {
        const formSection = document.querySelector('.form-section');
        if (formSection) {
            formSection.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
            
            // Add highlight animation
            this.addAnimation(formSection, 'pulse');
        }
    }
    
    handleFormSubmit(event) {
        const form = event.target;
        
        // Validate marks distribution
        if (this.distributedMarks !== this.totalMarks && this.totalMarks > 0) {
            event.preventDefault();
            this.showNotification(
                `মোট নম্বর (${this.totalMarks}) এবং বিভাজিত নম্বর (${this.distributedMarks}) সমান নয়!`,
                'error'
            );
            return false;
        }
        
        // Show loading state
        const submitBtn = form.querySelector('button[type="submit"]');
        if (submitBtn) {
            const originalHTML = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> সেভ হচ্ছে...';
            submitBtn.disabled = true;
            
            // Re-enable after form submission
            setTimeout(() => {
                submitBtn.innerHTML = originalHTML;
                submitBtn.disabled = false;
            }, 2000);
        }
        
        // Clear localStorage on successful submit
        this.clearLocalStorage();
        
        this.showNotification('ফর্ম সাবমিট করা হচ্ছে...', 'info');
    }
    
    setupAutoSave() {
        let autoSaveTimeout;
        
        const inputs = document.querySelectorAll('input, select');
        inputs.forEach(input => {
            input.addEventListener('change', () => {
                clearTimeout(autoSaveTimeout);
                autoSaveTimeout = setTimeout(() => {
                    this.saveToLocalStorage();
                    this.showAutoSaveIndicator();
                }, 2000);
            });
        });
    }
    
    showAutoSaveIndicator() {
        const indicator = document.createElement('div');
        indicator.className = 'notification info show';
        indicator.innerHTML = `
            <i class="fas fa-save"></i>
            <strong>অটো-সেভ</strong>
            <p>ডেটা স্থানীয়ভাবে সংরক্ষিত হয়েছে</p>
        `;
        
        document.body.appendChild(indicator);
        
        setTimeout(() => {
            indicator.classList.remove('show');
            setTimeout(() => indicator.remove(), 300);
        }, 2000);
    }
    
    saveToLocalStorage() {
        const formData = {};
        const inputs = document.querySelectorAll('input, select');
        
        inputs.forEach(input => {
            if (input.id) {
                formData[input.id] = input.value;
            }
        });
        
        localStorage.setItem('marks_distribution_draft', JSON.stringify(formData));
    }
    
    loadSavedData() {
        const savedData = localStorage.getItem('marks_distribution_draft');
        if (savedData) {
            try {
                const data = JSON.parse(savedData);
                
                Object.entries(data).forEach(([id, value]) => {
                    const element = document.getElementById(id);
                    if (element && value) {
                        element.value = value;
                    }
                });
                
                this.updateMarksCalculation();
                this.updateProgressVisualization();
                
                this.showNotification('পূর্বের ডেটা লোড করা হয়েছে', 'info');
            } catch (e) {
                console.error('Error loading saved data:', e);
            }
        }
    }
    
    clearLocalStorage() {
        localStorage.removeItem('marks_distribution_draft');
    }
    
    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Ctrl+S to save
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                const form = document.querySelector('form');
                if (form) {
                    form.dispatchEvent(new Event('submit'));
                }
            }
            
            // Ctrl+R to reset
            if (e.ctrlKey && e.key === 'r') {
                e.preventDefault();
                const resetBtn = document.querySelector('button[type="reset"]');
                if (resetBtn) {
                    resetBtn.click();
                }
            }
            
            // Escape to clear form
            if (e.key === 'Escape') {
                this.clearForm();
            }
        });
    }
    
    clearForm() {
        const form = document.querySelector('form');
        if (form) {
            form.reset();
            this.updateMarksCalculation();
            this.updateProgressVisualization();
            this.clearLocalStorage();
            this.showNotification('ফর্ম ক্লিয়ার করা হয়েছে', 'info');
        }
    }
    
    setupNotificationSystem() {
        // Create notification container if it doesn't exist
        if (!document.getElementById('notification-container')) {
            const container = document.createElement('div');
            container.id = 'notification-container';
            container.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                max-width: 400px;
            `;
            document.body.appendChild(container);
        }
    }
    
    showNotification(message, type = 'info', duration = 3000) {
        const container = document.getElementById('notification-container');
        if (!container) return;
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        const icons = {
            success: 'fas fa-check-circle',
            error: 'fas fa-exclamation-triangle',
            warning: 'fas fa-exclamation-circle',
            info: 'fas fa-info-circle'
        };
        
        notification.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="${icons[type]} me-2"></i>
                <span>${message}</span>
                <button type="button" class="btn-close ms-auto" onclick="this.parentElement.parentElement.remove()"></button>
            </div>
        `;
        
        container.appendChild(notification);
        
        // Show notification
        setTimeout(() => notification.classList.add('show'), 100);
        
        // Auto remove
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, duration);
        
        this.notifications.push(notification);
    }
    
    addAnimation(element, animationName) {
        element.classList.add('animate__animated', `animate__${animationName}`);
        
        const handleAnimationEnd = () => {
            element.classList.remove('animate__animated', `animate__${animationName}`);
            element.removeEventListener('animationend', handleAnimationEnd);
        };
        
        element.addEventListener('animationend', handleAnimationEnd);
    }
    
    addInputAnimation(input, animationName) {
        this.addAnimation(input, animationName);
    }
    
    initializeAnimations() {
        // Stagger animation for table rows
        const tableRows = document.querySelectorAll('tbody tr');
        tableRows.forEach((row, index) => {
            row.style.animationDelay = `${index * 0.1}s`;
        });
        
        // Add hover effects to stats cards
        const statsCards = document.querySelectorAll('.stats-card');
        statsCards.forEach(card => {
            card.addEventListener('mouseenter', () => {
                this.addAnimation(card, 'pulse');
            });
        });
        
        // Initialize progress ring
        this.updateProgressVisualization();
    }
    
    // Utility methods
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    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);
            }
        };
    }
}

// Initialize the system when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.advancedMarksSystem = new AdvancedMarksSystem();
});

// Floating Action Button functionality
function scrollToTop() {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AdvancedMarksSystem;
}