/**
 * NOGO POINT OF SALE SYSTEM
 * Premium Compact Login JavaScript
 * 
 * @author System Administrator
 * @version 2.0.0
 */

(function() {
    'use strict';

    // DOM Elements
    const loginForm = document.getElementById('loginForm');
    const loginButton = document.getElementById('loginButton');
    const passwordField = document.getElementById('password');
    const togglePassword = document.getElementById('togglePassword');
    const usernameField = document.getElementById('username');
    const twoFactorGroup = document.getElementById('twoFactorGroup');
    const twoFactorInput = document.getElementById('two_factor_code');

    // Password Toggle
    if (togglePassword && passwordField) {
        togglePassword.addEventListener('click', function() {
            const type = passwordField.type === 'password' ? 'text' : 'password';
            passwordField.type = type;
            
            // Toggle icon
            const icon = this.querySelector('i');
            icon.classList.toggle('fa-eye-slash');
            icon.classList.toggle('fa-eye');
        });
    }

    // Form Submission with Loading State
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            if (!loginForm.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
                loginForm.classList.add('was-validated');
                return;
            }

            // Show loading state
            loginButton.classList.add('loading');
            loginButton.disabled = true;
            
            const btnText = loginButton.querySelector('.btn-text');
            const spinner = loginButton.querySelector('.spinner-border');
            
            if (btnText && spinner) {
                btnText.style.opacity = '0';
                spinner.classList.remove('d-none');
            }
        });
    }

    // 2FA Detection
    if (usernameField && twoFactorGroup) {
        let typingTimer;
        const doneTypingInterval = 500;

        usernameField.addEventListener('input', function() {
            clearTimeout(typingTimer);
            
            if (this.value.length > 2) {
                typingTimer = setTimeout(() => {
                    checkTwoFactorStatus(this.value);
                }, doneTypingInterval);
            }
        });
    }

    /**
     * Check if user has 2FA enabled
     */
    function checkTwoFactorStatus(username) {
        fetch('check_2fa.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username: username })
        })
        .then(response => response.json())
        .then(data => {
            if (data.two_factor_enabled) {
                twoFactorGroup.classList.remove('d-none');
                twoFactorInput.required = true;
                
                // Animate in
                twoFactorGroup.style.animation = 'fadeInUp 0.3s ease forwards';
                
                // Focus after animation
                setTimeout(() => twoFactorInput.focus(), 300);
            } else {
                twoFactorGroup.classList.add('d-none');
                twoFactorInput.required = false;
            }
        })
        .catch(error => {
            console.log('2FA check failed:', error);
        });
    }

    // Input focus effects
    const inputs = document.querySelectorAll('.form-control');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.closest('.input-group').classList.add('focused');
        });
        
        input.addEventListener('blur', function() {
            this.closest('.input-group').classList.remove('focused');
        });
    });

    // Auto-focus username field
    setTimeout(() => {
        if (usernameField && !usernameField.value) {
            usernameField.focus();
        }
    }, 500);

    // Prevent double submission
    let submitted = false;
    loginForm.addEventListener('submit', function(e) {
        if (submitted) {
            e.preventDefault();
            return;
        }
        submitted = true;
    });

    // Keyboard shortcut: Ctrl+Shift+L to focus username
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.shiftKey && e.key === 'L') {
            e.preventDefault();
            usernameField.focus();
        }
        
        // Ctrl+Shift+P to focus password
        if (e.ctrlKey && e.shiftKey && e.key === 'P') {
            e.preventDefault();
            passwordField.focus();
        }
    });

    // Smooth reveal animation for form elements
    const formElements = document.querySelectorAll('.form-group, .btn, .form-check, .demo-credentials');
    formElements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.animation = `fadeInUp 0.4s ease forwards ${index * 0.05 + 0.2}s`;
    });

    // Particle effect on background (optional)
    function createParticle() {
        const particle = document.createElement('div');
        particle.className = 'particle';
        particle.style.cssText = `
            position: fixed;
            width: 2px;
            height: 2px;
            background: rgba(255,255,255,0.3);
            border-radius: 50%;
            pointer-events: none;
            z-index: -1;
            left: ${Math.random() * 100}%;
            top: -10px;
            animation: fall ${Math.random() * 5 + 5}s linear forwards;
        `;
        
        document.body.appendChild(particle);
        
        setTimeout(() => {
            particle.remove();
        }, 10000);
    }

    // Add particle animation style
    const style = document.createElement('style');
    style.textContent = `
        @keyframes fall {
            to {
                transform: translateY(100vh);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(style);

    // Create particles every 500ms (optional - remove if too heavy)
    // setInterval(createParticle, 500);
})();

// Add CSS for focused state
const focusStyle = document.createElement('style');
focusStyle.textContent = `
    .input-group.focused {
        border-color: var(--primary) !important;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1) !important;
    }
    
    .input-group.focused .input-group-text i {
        color: var(--primary) !important;
    }
`;
document.head.appendChild(focusStyle);