/**
 * Modern Admin Login Page JavaScript
 * Enhanced interactions and animations
 */

class ModernLoginPage {
    constructor() {
        this.init();
        this.setupEventListeners();
        this.startStatsUpdater();
        this.setupFormValidation();
        this.setupAccessibility();
    }

    init() {
        // Initialize control variables
        this.isUpdatingStats = false;
        this.statsInterval = null;

        // Initialize page elements
        this.form = document.getElementById('login-form');
        this.button = document.getElementById('login-button');
        this.buttonText = this.button?.querySelector('.button-text');
        this.statsCards = document.querySelectorAll('.stat-card');
        this.inputs = document.querySelectorAll('.form-control');

        // Add initial animations
        this.animatePageLoad();

        // Setup Persian number formatting
        this.formatPersianNumbers();
    }

    setupEventListeners() {
        // Form submission
        if (this.form) {
            this.form.addEventListener('submit', (e) => this.handleFormSubmit(e));
        }

        // Input interactions
        this.inputs.forEach(input => {
            input.addEventListener('focus', (e) => this.handleInputFocus(e));
            input.addEventListener('blur', (e) => this.handleInputBlur(e));
            input.addEventListener('input', (e) => this.handleInputChange(e));
        });

        // Stats card interactions
        this.statsCards.forEach(card => {
            card.addEventListener('mouseenter', (e) => this.handleCardHover(e));
            card.addEventListener('mouseleave', (e) => this.handleCardLeave(e));
        });

        // Keyboard navigation
        document.addEventListener('keydown', (e) => this.handleKeyboardNavigation(e));

        // Window events
        window.addEventListener('resize', () => this.handleResize());
        window.addEventListener('online', () => this.handleConnectionChange(true));
        window.addEventListener('offline', () => this.handleConnectionChange(false));

        // Cleanup on page unload
        window.addEventListener('beforeunload', () => this.cleanup());
    }

    animatePageLoad() {
        // Stagger animation for stats cards
        this.statsCards.forEach((card, index) => {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                card.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, index * 100);
        });

        // Animate form elements
        const formElements = document.querySelectorAll('.form-group');
        formElements.forEach((element, index) => {
            element.style.opacity = '0';
            element.style.transform = 'translateX(20px)';
            
            setTimeout(() => {
                element.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
                element.style.opacity = '1';
                element.style.transform = 'translateX(0)';
            }, 300 + (index * 100));
        });
    }

    handleFormSubmit(e) {
        if (!this.validateForm()) {
            e.preventDefault();
            return;
        }

        // Add loading state
        this.setLoadingState(true);

        // Add visual feedback
        this.addSubmitAnimation();
    }

    setLoadingState(loading) {
        if (!this.button || !this.buttonText) return;

        if (loading) {
            this.button.disabled = true;
            this.button.classList.add('loading');
            this.buttonText.textContent = 'در حال ورود...';
            
            // Animate stats during loading
            this.animateStatsLoading();
        } else {
            this.button.disabled = false;
            this.button.classList.remove('loading');
            this.buttonText.textContent = 'ورود';
        }
    }

    animateStatsLoading() {
        this.statsCards.forEach(card => {
            const number = card.querySelector('.stat-number');
            if (number) {
                number.style.animation = 'pulse 1s ease-in-out infinite';
            }
        });
    }

    handleInputFocus(e) {
        const inputGroup = e.target.closest('.input-group');
        if (inputGroup) {
            inputGroup.style.transform = 'scale(1.02)';
            inputGroup.style.transition = 'transform 0.2s ease';
        }

        // Add focus ring animation
        e.target.style.boxShadow = '0 0 0 3px rgba(102, 126, 234, 0.2)';
    }

    handleInputBlur(e) {
        const inputGroup = e.target.closest('.input-group');
        if (inputGroup) {
            inputGroup.style.transform = 'scale(1)';
        }

        e.target.style.boxShadow = '';
    }

    handleInputChange(e) {
        // Real-time validation
        this.validateField(e.target);

        // Update character count if needed (optional feature)
        if (this.updateCharacterCount && typeof this.updateCharacterCount === 'function') {
            this.updateCharacterCount(e.target);
        }
    }

    handleCardHover(e) {
        const card = e.currentTarget;
        card.style.transform = 'translateY(-5px) scale(1.02)';
        card.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
        
        // Add glow effect
        card.style.boxShadow = '0 10px 30px rgba(102, 126, 234, 0.3)';
    }

    handleCardLeave(e) {
        const card = e.currentTarget;
        card.style.transform = 'translateY(0) scale(1)';
        card.style.boxShadow = '';
    }

    startStatsUpdater() {
        // Prevent multiple intervals
        if (this.statsInterval) {
            clearInterval(this.statsInterval);
        }

        // Only start if not already updating
        if (this.isUpdatingStats) {
            return;
        }

        // Update stats every 60 seconds (reduced frequency)
        this.statsInterval = setInterval(() => {
            if (!this.isUpdatingStats) {
                this.updateStats();
            }
        }, 60000);

        // Initial update after 3 seconds (reduced delay)
        setTimeout(() => {
            if (!this.isUpdatingStats) {
                console.log('📊 Starting initial stats update...');
                this.updateStats();
            }
        }, 3000);
    }

    async updateStats() {
        // Prevent concurrent requests
        if (this.isUpdatingStats) {
            return;
        }

        this.isUpdatingStats = true;

        try {
            const response = await fetch('/admin/api/quick-stats');

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();

            if (data.error) {
                console.warn('Stats update failed:', data.error);
                this.handleStatsError();
                return;
            }

            this.animateStatsUpdate(data);
            this.updateConnectionStatus(true);
            console.log('✅ Stats updated successfully');
        } catch (error) {
            console.warn('⚠️ Failed to fetch stats:', error.message);
            this.handleStatsError();
            this.updateConnectionStatus(false);
        } finally {
            this.isUpdatingStats = false;
        }
    }

    handleStatsError() {
        // Show visual indication of stats update failure
        const statsCards = document.querySelectorAll('.stat-card');
        statsCards.forEach(card => {
            card.style.opacity = '0.7';
            setTimeout(() => {
                card.style.opacity = '1';
            }, 1000);
        });
    }

    updateConnectionStatus(isConnected) {
        const indicators = document.querySelectorAll('.status-indicator');
        indicators.forEach(indicator => {
            if (isConnected) {
                indicator.classList.remove('status-offline', 'status-error');
                indicator.classList.add('status-online');
            } else {
                indicator.classList.remove('status-online');
                indicator.classList.add('status-offline');
            }
        });
    }

    animateStatsUpdate(data) {
        const updates = [
            { id: 'locations-count', value: data.locations },
            { id: 'users-count', value: data.users },
            { id: 'ratings-count', value: data.ratings },
            { id: 'categories-count', value: data.categories }
        ];

        updates.forEach(({ id, value }) => {
            const element = document.getElementById(id);
            if (element && value !== undefined) {
                this.animateNumberChange(element, value);
            }
        });

        // Update timestamp
        const timestampElement = document.querySelector('.status-item:last-child span:last-child');
        if (timestampElement && data.timestamp) {
            timestampElement.textContent = data.timestamp;
        }
    }

    animateNumberChange(element, newValue) {
        const currentValue = parseInt(element.textContent) || 0;
        
        if (currentValue === newValue) return;

        // Add update animation
        element.style.transform = 'scale(1.1)';
        element.style.transition = 'transform 0.3s ease';
        
        setTimeout(() => {
            element.textContent = this.formatNumber(newValue);
            element.style.transform = 'scale(1)';
        }, 150);
    }

    formatNumber(num) {
        // Format numbers with Persian digits if needed
        const formatted = num.toLocaleString('fa-IR');
        return formatted;
    }

    formatPersianNumbers() {
        // Convert numbers to Persian if the page language is Persian
        if (document.documentElement.lang === 'fa') {
            const numbers = document.querySelectorAll('.stat-number');
            numbers.forEach(el => {
                const num = parseInt(el.textContent);
                if (!isNaN(num)) {
                    el.textContent = this.formatNumber(num);
                }
            });
        }
    }

    setupFormValidation() {
        // Setup real-time validation
        const inputs = document.querySelectorAll('#login-form input');
        inputs.forEach(input => {
            input.addEventListener('blur', () => this.validateField(input));
            input.addEventListener('input', () => this.clearFieldError(input));
        });
    }

    validateForm() {
        const username = document.getElementById('username');
        const password = document.getElementById('password');

        let isValid = true;

        // Username validation
        if (!username.value.trim()) {
            this.showFieldError(username, 'نام کاربری الزامی است');
            isValid = false;
        } else if (!/^[a-zA-Z0-9_-]+$/.test(username.value)) {
            this.showFieldError(username, 'نام کاربری نامعتبر است');
            isValid = false;
        }

        // Password validation
        if (!password.value) {
            this.showFieldError(password, 'رمز عبور الزامی است');
            isValid = false;
        } else if (password.value.length < 8) {
            this.showFieldError(password, 'رمز عبور باید حداقل 8 کاراکتر باشد');
            isValid = false;
        }

        return isValid;
    }

    validateField(field) {
        // Remove existing error states
        this.clearFieldError(field);

        // Field-specific validation
        if (field.id === 'username') {
            if (field.value && !/^[a-zA-Z0-9_-]+$/.test(field.value)) {
                this.showFieldError(field, 'فقط حروف انگلیسی، اعداد، خط تیره و زیرخط مجاز است');
            }
        }

        if (field.id === 'password') {
            if (field.value && field.value.length < 8) {
                this.showFieldError(field, 'حداقل 8 کاراکتر');
            }
        }
    }

    showFieldError(field, message) {
        field.classList.add('is-invalid');
        
        // Add shake animation
        field.style.animation = 'shake 0.5s ease-in-out';
        setTimeout(() => {
            field.style.animation = '';
        }, 500);

        // Show error message if not already shown
        let errorElement = field.parentElement.querySelector('.field-error');
        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'field-error text-danger small mt-1';
            field.parentElement.appendChild(errorElement);
        }
        errorElement.textContent = message;
    }

    clearFieldError(field) {
        field.classList.remove('is-invalid');
        const errorElement = field.parentElement.querySelector('.field-error');
        if (errorElement) {
            errorElement.remove();
        }
    }

    handleKeyboardNavigation(e) {
        // Enhanced keyboard navigation
        if (e.key === 'Enter' && e.target.tagName === 'INPUT') {
            const inputs = Array.from(this.inputs);
            const currentIndex = inputs.indexOf(e.target);
            const nextInput = inputs[currentIndex + 1];
            
            if (nextInput) {
                nextInput.focus();
            } else if (this.button) {
                this.button.focus();
            }
        }
    }

    handleResize() {
        // Responsive adjustments
        const container = document.querySelector('.main-container');
        if (window.innerWidth < 768) {
            container?.classList.add('mobile-layout');
        } else {
            container?.classList.remove('mobile-layout');
        }
    }

    handleConnectionChange(isOnline) {
        const indicators = document.querySelectorAll('.status-indicator');
        indicators.forEach(indicator => {
            if (isOnline) {
                indicator.className = 'status-indicator status-online';
            } else {
                indicator.className = 'status-indicator status-offline';
            }
        });
    }

    setupAccessibility() {
        // Add ARIA labels and roles
        this.inputs.forEach(input => {
            const label = input.getAttribute('placeholder');
            if (label) {
                input.setAttribute('aria-label', label);
            }
        });

        // Add focus management
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Tab') {
                document.body.classList.add('keyboard-navigation');
            }
        });

        document.addEventListener('mousedown', () => {
            document.body.classList.remove('keyboard-navigation');
        });
    }

    addSubmitAnimation() {
        // Add ripple effect to button
        const ripple = document.createElement('span');
        ripple.className = 'ripple';
        this.button.appendChild(ripple);

        setTimeout(() => {
            ripple.remove();
        }, 600);
    }

    showFormErrors() {
        // Show general form error if needed
        const form = this.form;
        if (form) {
            form.classList.add('error-shake');
            setTimeout(() => {
                form.classList.remove('error-shake');
            }, 500);
        }
    }

    cleanup() {
        // Clear intervals to prevent memory leaks
        if (this.statsInterval) {
            clearInterval(this.statsInterval);
            this.statsInterval = null;
        }

        // Reset flags
        this.isUpdatingStats = false;

        console.log('🧹 ModernLoginPage cleaned up');
    }
}

// Initialize when DOM is loaded (singleton pattern)
document.addEventListener('DOMContentLoaded', () => {
    // Prevent multiple instances
    if (window.ModernLoginPage) {
        console.log('🔄 ModernLoginPage already exists, cleaning up...');
        if (window.ModernLoginPage.cleanup) {
            window.ModernLoginPage.cleanup();
        }
    }

    window.ModernLoginPage = new ModernLoginPage();
    console.log('🚀 ModernLoginPage initialized');
});

// Add CSS for animations
const style = document.createElement('style');
style.textContent = `
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-5px); }
        75% { transform: translateX(5px); }
    }
    
    .ripple {
        position: absolute;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.6);
        transform: scale(0);
        animation: ripple 0.6s linear;
        pointer-events: none;
    }
    
    @keyframes ripple {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
    
    .keyboard-navigation *:focus {
        outline: 2px solid #667eea !important;
        outline-offset: 2px !important;
    }
`;
document.head.appendChild(style);
