// ========================================
// AUTHENTICATION SYSTEM V2 (Enhanced)
// ========================================
console.log("🔐 Loading Authentication System V2.1...");

// --- Helpers ---

function showAuthMessage(type, message) {
    if (typeof showMessage === 'function') {
        showMessage(type === 'error' ? 'Error' : 'Success', message, type);
    } else {
        // Fallback Toast
        const existing = document.getElementById('auth-toast');
        if (existing) existing.remove();

        const toast = document.createElement('div');
        toast.id = 'auth-toast';
        toast.className = `fixed top-4 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-full text-white text-sm font-bold shadow-lg z-[9999] transition-all duration-300 ${type === 'error' ? 'bg-red-500' : 'bg-green-500'}`;
        toast.style.minWidth = '200px';
        toast.style.textAlign = 'center';
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translate(-50%, -20px)';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }
}

function setAuthLoading(btn, isLoading, text = 'Processing...') {
    if (!btn) return;
    if (isLoading) {
        if (!btn.dataset.originalText) btn.dataset.originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = `<span class="material-symbols-outlined animate-spin text-sm align-middle mr-2" style="font-size: 16px;">autorenew</span> ${text}`;
        btn.classList.add('opacity-75', 'cursor-not-allowed');
    } else {
        btn.disabled = false;
        btn.innerHTML = btn.dataset.originalText || 'Submit';
        btn.classList.remove('opacity-75', 'cursor-not-allowed');
    }
}

// --- Session Logic ---

window.currentUser = null;
const storedUser = localStorage.getItem('ghadget_user');
const storedToken = localStorage.getItem('ghadget_token');

if (storedUser && storedToken) {
    try {
        window.currentUser = JSON.parse(storedUser);
        console.log("✅ User session found locally:", window.currentUser.username);

        // Verify session with backend (silent check)
        fetch('../server/auth_v2.php?action=check_session&token=' + storedToken)
            .then(res => res.json())
            .then(data => {
                if (!data.success) {
                    console.warn("❌ Session invalid on server, clearing...");
                    window.currentUser = null;
                    localStorage.removeItem('ghadget_user');
                    localStorage.removeItem('ghadget_token');
                    // Optional: redirect to login if currently on protected view?
                } else {
                    console.log("✅ Session verified with server");
                }
            })
            .catch(err => console.error("Session check failed (network):", err));
    } catch (e) {
        console.error("Failed to parse user data:", e);
        window.currentUser = null;
    }
}

// --- Auth Functions ---

window.checkAuth = function (action = "perform this action") {
    if (window.currentUser && window.currentUser.verified) {
        return true;
    }
    console.log(`🔒 Auth required for: ${action}`);
    window.showAuthModal('login');
    return false;
};

window.showAuthModal = function (mode = 'login') {
    const modal = document.getElementById('auth-modal-v2');
    if (!modal) {
        console.error("Auth modal not found!");
        return;
    }

    modal.classList.remove('hidden');
    modal.classList.add('flex');

    // Reset forms
    const inputs = modal.querySelectorAll('input');
    inputs.forEach(input => input.value = '');

    // Switch View
    const loginForm = document.getElementById('auth-login-form');
    const signupForm = document.getElementById('auth-signup-form');
    const verifyScreen = document.getElementById('auth-verify-screen');

    if (loginForm) loginForm.classList.add('hidden');
    if (signupForm) signupForm.classList.add('hidden');
    if (verifyScreen) verifyScreen.classList.add('hidden');

    if (mode === 'login' && loginForm) {
        loginForm.classList.remove('hidden');
    } else if (mode === 'signup' && signupForm) {
        signupForm.classList.remove('hidden');
    }
};

window.closeAuthModal = function () {
    const modal = document.getElementById('auth-modal-v2');
    if (modal) {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }
};

window.togglePassword = function (inputId, iconId) {
    const input = document.getElementById(inputId);
    const icon = document.getElementById(iconId);

    if (input.type === 'password') {
        input.type = 'text';
        icon.textContent = 'visibility_off';
    } else {
        input.type = 'password';
        icon.textContent = 'visibility';
    }
};

// --- Handlers ---

window.handleSignup = async function (e) {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');

    const username = document.getElementById('signup-username').value.trim();
    const email = document.getElementById('signup-email').value.trim();
    const whatsapp = document.getElementById('signup-whatsapp').value.trim();
    const password = document.getElementById('signup-password').value;
    const confirmPassword = document.getElementById('signup-confirm-password').value;

    if (!username || !email || !whatsapp || !password || !confirmPassword) {
        showAuthMessage('error', 'Please fill all fields');
        return;
    }

    if (password !== confirmPassword) {
        showAuthMessage('error', 'Passwords do not match');
        return;
    }

    if (password.length < 8) {
        showAuthMessage('error', 'Password must be at least 8 characters');
        return;
    }

    setAuthLoading(btn, true, 'Creating Account...');

    try {
        const formData = new FormData();
        formData.append('action', 'signup');
        formData.append('username', username);
        formData.append('email', email);
        formData.append('whatsapp', whatsapp);
        formData.append('password', password);

        const response = await fetch('../server/auth_v2.php', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.success) {
            showAuthMessage('success', 'Account created! Please verify email.');
            // Show verification screen
            document.getElementById('auth-signup-form').classList.add('hidden');
            document.getElementById('auth-verify-screen').classList.remove('hidden');
            document.getElementById('verify-email-display').textContent = data.email;
        } else {
            showAuthMessage('error', data.error || 'Signup failed');
        }
    } catch (error) {
        console.error('Signup error:', error);
        showAuthMessage('error', 'Network error. Please try again.');
    } finally {
        setAuthLoading(btn, false);
    }
};

window.handleLogin = async function (e) {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');

    const identifier = document.getElementById('login-identifier').value.trim();
    const password = document.getElementById('login-password').value;

    if (!identifier || !password) {
        showAuthMessage('error', 'Please enter email/username and password');
        return;
    }

    setAuthLoading(btn, true, 'Logging In...');

    try {
        const formData = new FormData();
        formData.append('action', 'login');
        formData.append('identifier', identifier);
        formData.append('password', password);

        // Add timeout to fetch
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout

        const response = await fetch('../server/auth_v2.php', {
            method: 'POST',
            body: formData,
            signal: controller.signal
        });
        clearTimeout(timeoutId);

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

        const data = await response.json();

        if (data.success) {
            showAuthMessage('success', `Welcome back, ${data.user.username}!`);

            // Store user data and token
            localStorage.setItem('ghadget_user', JSON.stringify(data.user));
            localStorage.setItem('ghadget_token', data.token);
            window.currentUser = data.user;

            console.log('✅ Login successful:', data.user.username);

            // Close modal and reload
            setTimeout(() => {
                window.closeAuthModal();
                window.location.reload();
            }, 1000);
        } else {
            // Handle verification needed specifically?
            if (data.error && data.error.includes('verify')) {
                showAuthMessage('error', 'Please verify your email first.');
            } else {
                showAuthMessage('error', data.error || 'Login failed');
            }
        }
    } catch (error) {
        console.error('Login error:', error);
        if (error.name === 'AbortError') {
            showAuthMessage('error', 'Server timed out. Please try again.');
        } else {
            showAuthMessage('error', 'Network error. Check connection.');
        }
    } finally {
        setAuthLoading(btn, false);
    }
};

window.logout = function () {
    const token = localStorage.getItem('ghadget_token');

    if (token) {
        fetch('../server/auth_v2.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=logout&token=${token}`
        }).catch(err => console.error("Logout error:", err));
    }

    window.currentUser = null;
    localStorage.removeItem('ghadget_user');
    localStorage.removeItem('ghadget_token');

    console.log("✅ Logged out");
    showAuthMessage('success', 'Logged out successfully');
    setTimeout(() => window.location.reload(), 500);
};
