/* ============================
   Redesigned Authentication Logic (auth.js)
   ============================ */

document.addEventListener('DOMContentLoaded', () => {
    const loginTab = document.getElementById('login-tab');
    const registerTab = document.getElementById('register-tab');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const authTitle = document.getElementById('auth-title');
    const authSubtitle = document.getElementById('auth-subtitle');
    const footerText = document.getElementById('auth-footer-text');

    // Navbar state management for Auth Page
    const navbar = document.getElementById('mainNavbar');
    if (navbar) {
        navbar.classList.add('navbar-scrolled'); // Force white background
        const loginLink = navbar.querySelector('a[href="login.html"]');
        if (loginLink) {
            loginLink.classList.add('nav-active'); // Show the underline effect
        }
    }

    // Tab Switching Logic
    const showLogin = () => {
        loginTab.classList.add('active');
        registerTab.classList.remove('active');
        
        // Use opacity and visibility for smoother transition
        loginForm.style.display = 'block';
        registerForm.style.display = 'none';
        
        authTitle.textContent = 'Sign In!';
        authSubtitle.textContent = 'Welcome back! Please enter your details below.';
        footerText.innerHTML = 'Don\'t have an account? <a href="javascript:void(0)" onclick="switchToTab(\'register\')">Sign up</a>';
    };

    const showRegister = () => {
        registerTab.classList.add('active');
        loginTab.classList.remove('active');
        
        loginForm.style.display = 'none';
        registerForm.style.display = 'block';
        
        authTitle.textContent = 'Register!';
        authSubtitle.textContent = 'Create an account to track orders and save your favorites.';
        footerText.innerHTML = 'Already have an account? <a href="javascript:void(0)" onclick="switchToTab(\'login\')">Log in</a>';
    };

    loginTab.addEventListener('click', showLogin);
    registerTab.addEventListener('click', showRegister);

    // Custom Toast Notification System
    const showToast = (message, type = 'success') => {
        let toastContainer = document.getElementById('auth-toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'auth-toast-container';
            
            const isMobile = window.innerWidth < 768;
            toastContainer.style.cssText = `
                position: fixed;
                top: 25px;
                ${isMobile ? 'left: 50%; transform: translateX(-50%);' : 'right: 25px;'}
                z-index: 10000;
                width: auto;
                min-width: 280px;
                max-width: 90%;
                pointer-events: none;
            `;
            document.body.appendChild(toastContainer);

            window.addEventListener('resize', () => {
                const mobile = window.innerWidth < 768;
                toastContainer.style.left = mobile ? '50%' : 'auto';
                toastContainer.style.right = mobile ? 'auto' : '25px';
                toastContainer.style.transform = mobile ? 'translateX(-50%)' : 'none';
            });
        }

        const toast = document.createElement('div');
        toast.style.pointerEvents = 'auto';
        const bgColor = type === 'success' ? '#198754' : '#dc3545';
        const icon = type === 'success' ? 'bi-check-circle-fill' : 'bi-exclamation-circle-fill';
        
        toast.className = 'fade-in';
        toast.style.cssText = `
            background-color: ${bgColor};
            color: white;
            padding: 12px 20px;
            border-radius: 12px;
            margin-bottom: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-weight: 500;
            animation: slideInRight 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        `;

        if (!document.getElementById('toast-style')) {
            const style = document.createElement('style');
            style.id = 'toast-style';
            style.innerHTML = `
                @keyframes slideInRight {
                    from { transform: translateX(30px); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
        }

        toast.innerHTML = `
            <div style="display: flex; align-items: center; gap: 12px;">
                <i class="bi ${icon}" style="font-size: 1.2rem;"></i>
                <span>${message}</span>
            </div>
            <i class="bi bi-x" style="cursor: pointer; font-size: 1.5rem; margin-left: 20px;" onclick="this.parentElement.remove()"></i>
        `;

        toastContainer.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-10px)';
            toast.style.transition = 'all 0.5s ease';
            setTimeout(() => toast.remove(), 500);
        }, 4000);
    };

    // Form Submission Handling
    const handleAuth = (e, type) => {
        e.preventDefault();
        
        const isValid = type === 'Login' ? window.validateLoginForm() : window.validateRegisterForm();
        if (!isValid) {
            showToast('Please fix the errors in the form.', 'error');
            return;
        }

        const btn = e.target.querySelector('button[type="submit"]');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Processing...';
        btn.disabled = true;

        const url = type === 'Registration' ? 'api/register.php' : 'api/login.php';
        const formData = new FormData(e.target);
        
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                btn.innerHTML = originalText;
                btn.disabled = false;
                
                if (response.status === 'success') {
                    showToast(response.message, 'success');
                    if (type === 'Registration') {
                        setTimeout(() => showLogin(), 1000);
                    } else {
                        setTimeout(() => {
                            if (response.user && response.user.role === 'admin') {
                                window.location.href = 'admin/index.php';
                            } else {
                                window.location.href = 'index.html';
                            }
                        }, 1500);
                    }
                } else {
                    const errorMsg = type === 'Login' ? 'Invalid credentials. Please try again.' : response.message;
                    showToast(errorMsg, 'error');
                }
            },
            error: function() {
                btn.innerHTML = originalText;
                btn.disabled = false;
                showToast('Something went wrong. Please try again later.', 'error');
            }
        });
    };

    if(loginForm) loginForm.addEventListener('submit', (e) => handleAuth(e, 'Login'));
    if(registerForm) registerForm.addEventListener('submit', (e) => handleAuth(e, 'Registration'));
});
