// ========== AUTHENTICATION SYSTEM ==========
// Global Variables
let currentUser = JSON.parse(localStorage.getItem('stickerlink_current_user')) || null;
let isLoggedIn = !!currentUser;
let currentOtp = '';
let otpTimer = null;
let otpEmail = '';

// ========== LOGIN FUNCTION ==========
function handleLogin() {
    const identifier = document.getElementById('loginIdentifier')?.value.trim();
    const password = document.getElementById('loginPassword')?.value;

    if (!identifier || !password) {
        showNotification('Harap isi semua field', 'error');
        return;
    }

    const usersDB = JSON.parse(localStorage.getItem('stickerlink_users') || '{}');
    let foundUser = null;

    for (let id in usersDB) {
        if (usersDB[id].email === identifier || usersDB[id].username === identifier) {
            if (usersDB[id].password === password) {
                foundUser = usersDB[id];
            }
            break;
        }
    }

    if (foundUser) {
        currentUser = foundUser;
        isLoggedIn = true;
        localStorage.setItem('stickerlink_current_user', JSON.stringify(foundUser));
        showNotification('Login berhasil! Selamat datang kembali!', 'success');
        showPage('home');
        updateSidebar();
        updateProfileUI();
        updateStats();
        updateNotificationBadge();
        updateChatBadge();
        updateVerificationStatus();
    } else {
        showNotification('Email/username atau password salah', 'error');
    }
}

// ========== REGISTER FUNCTION ==========
function handleRegister() {
    const username = document.getElementById('registerUsername')?.value.trim().toLowerCase();
    const email = document.getElementById('registerEmail')?.value.trim().toLowerCase();
    const password = document.getElementById('registerPassword')?.value;
    const confirm = document.getElementById('registerConfirm')?.value;

    if (!username || !email || !password || !confirm) {
        showNotification('Harap isi semua field', 'error');
        return;
    }

    if (username.length < 3) {
        showNotification('Username minimal 3 karakter', 'error');
        return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        showNotification('Format email tidak valid', 'error');
        return;
    }

    if (password.length < 6) {
        showNotification('Password minimal 6 karakter', 'error');
        return;
    }

    if (password !== confirm) {
        showNotification('Password tidak cocok', 'error');
        return;
    }

    const usersDB = JSON.parse(localStorage.getItem('stickerlink_users') || '{}');

    for (let id in usersDB) {
        if (usersDB[id].username === username) {
            showNotification('Username sudah digunakan', 'error');
            return;
        }
        if (usersDB[id].email === email) {
            showNotification('Email sudah terdaftar', 'error');
            return;
        }
    }

    const userId = 'user_' + Date.now();
    const newUser = {
        id: userId,
        username: username,
        email: email,
        password: password,
        fullName: '',
        bio: '',
        avatar: '',
        balance: 0,
        danaName: '',
        danaPhone: '',
        verified: false,
        verificationPending: false,
        ktpImage: null,
        selfieImage: null,
        createdAt: new Date().toISOString()
    };

    usersDB[userId] = newUser;
    localStorage.setItem('stickerlink_users', JSON.stringify(usersDB));

    // Initialize store
    const storesDB = JSON.parse(localStorage.getItem('stickerlink_stores') || '{}');
    storesDB[userId] = {
        name: username + "'s Sticker Shop",
        description: 'Toko stiker digital berkualitas',
        category: 'art',
        email: email,
        avatar: '',
        banner: '',
        visits: 0
    };
    localStorage.setItem('stickerlink_stores', JSON.stringify(storesDB));

    // Initialize products
    const productsDB = JSON.parse(localStorage.getItem('stickerlink_products') || '{}');
    productsDB[userId] = [];
    localStorage.setItem('stickerlink_products', JSON.stringify(productsDB));

    // Initialize orders
    const ordersDB = JSON.parse(localStorage.getItem('stickerlink_orders') || '{}');
    ordersDB[userId] = [];
    localStorage.setItem('stickerlink_orders', JSON.stringify(ordersDB));

    // Initialize withdrawals
    const withdrawalsDB = JSON.parse(localStorage.getItem('stickerlink_withdrawals') || '{}');
    withdrawalsDB[userId] = [];
    localStorage.setItem('stickerlink_withdrawals', JSON.stringify(withdrawalsDB));

    // Initialize affiliate
    const affiliateDB = JSON.parse(localStorage.getItem('stickerlink_affiliate') || '{}');
    affiliateDB[userId] = {
        totalViews: 0,
        totalShares: 0,
        affiliateSales: 0,
        pendingCommission: 0,
        storeLink: `https://stickerlink.id/toko/${username}`
    };
    localStorage.setItem('stickerlink_affiliate', JSON.stringify(affiliateDB));

    // Initialize notifications
    const notificationsDB = JSON.parse(localStorage.getItem('stickerlink_notifications') || '{}');
    notificationsDB[userId] = [
        {
            id: 'notif_' + Date.now(),
            title: 'Selamat Datang!',
            message: 'Selamat bergabung di StickerLink! Mulai jualan stiker sekarang.',
            timestamp: new Date().toISOString(),
            read: false
        }
    ];
    localStorage.setItem('stickerlink_notifications', JSON.stringify(notificationsDB));

    // Initialize settings
    const settingsDB = JSON.parse(localStorage.getItem('stickerlink_settings') || '{}');
    settingsDB[userId] = {
        notifications: { email: true, sales: true, withdrawal: true, promo: true },
        twoFactor: false
    };
    localStorage.setItem('stickerlink_settings', JSON.stringify(settingsDB));

    currentUser = newUser;
    isLoggedIn = true;
    localStorage.setItem('stickerlink_current_user', JSON.stringify(newUser));

    showNotification('Pendaftaran berhasil! Selamat datang di StickerLink!', 'success');
    showPage('home');
    updateSidebar();
    updateProfileUI();
    updateStats();
    updateNotificationBadge();

    // Request notification permission
    if (Notification.permission === 'default') {
        Notification.requestPermission();
    }
}

// ========== GOOGLE SIGN IN ==========
window.handleGoogleSignIn = function(response) {
    console.log('Google Sign-In Response:', response);
    
    try {
        const base64Url = response.credential.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
        
        const userInfo = JSON.parse(jsonPayload);
        
        const usersDB = JSON.parse(localStorage.getItem('stickerlink_users') || '{}');
        let foundUser = null;
        let foundUserId = null;
        
        for (let id in usersDB) {
            if (usersDB[id].email === userInfo.email) {
                foundUser = usersDB[id];
                foundUserId = id;
                break;
            }
        }
        
        if (foundUser) {
            currentUser = foundUser;
            isLoggedIn = true;
            localStorage.setItem('stickerlink_current_user', JSON.stringify(foundUser));
            showNotification('Login Google berhasil! Selamat datang kembali!', 'success');
        } else {
            // Create new user with Google
            const username = userInfo.email.split('@')[0].replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
            const userId = 'user_' + Date.now();
            const newUser = {
                id: userId,
                username: username + '_' + Math.floor(Math.random() * 1000),
                email: userInfo.email,
                password: 'google_' + Math.random().toString(36).substring(2),
                fullName: userInfo.name || '',
                bio: '',
                avatar: userInfo.picture || '',
                balance: 0,
                danaName: '',
                danaPhone: '',
                verified: false,
                verificationPending: false,
                ktpImage: null,
                selfieImage: null,
                createdAt: new Date().toISOString(),
                googleId: userInfo.sub
            };
            
            usersDB[userId] = newUser;
            localStorage.setItem('stickerlink_users', JSON.stringify(usersDB));
            
            // Initialize store
            const storesDB = JSON.parse(localStorage.getItem('stickerlink_stores') || '{}');
            storesDB[userId] = {
                name: newUser.username + "'s Sticker Shop",
                description: 'Toko stiker digital berkualitas',
                category: 'art',
                email: userInfo.email,
                avatar: userInfo.picture || '',
                banner: '',
                visits: 0
            };
            localStorage.setItem('stickerlink_stores', JSON.stringify(storesDB));
            
            // Initialize empty arrays for other data
            const productsDB = JSON.parse(localStorage.getItem('stickerlink_products') || '{}');
            productsDB[userId] = [];
            localStorage.setItem('stickerlink_products', JSON.stringify(productsDB));
            
            const ordersDB = JSON.parse(localStorage.getItem('stickerlink_orders') || '{}');
            ordersDB[userId] = [];
            localStorage.setItem('stickerlink_orders', JSON.stringify(ordersDB));
            
            const withdrawalsDB = JSON.parse(localStorage.getItem('stickerlink_withdrawals') || '{}');
            withdrawalsDB[userId] = [];
            localStorage.setItem('stickerlink_withdrawals', JSON.stringify(withdrawalsDB));
            
            const affiliateDB = JSON.parse(localStorage.getItem('stickerlink_affiliate') || '{}');
            affiliateDB[userId] = {
                totalViews: 0,
                totalShares: 0,
                affiliateSales: 0,
                pendingCommission: 0,
                storeLink: `https://stickerlink.id/toko/${newUser.username}`
            };
            localStorage.setItem('stickerlink_affiliate', JSON.stringify(affiliateDB));
            
            const notificationsDB = JSON.parse(localStorage.getItem('stickerlink_notifications') || '{}');
            notificationsDB[userId] = [
                {
                    id: 'notif_' + Date.now(),
                    title: 'Selamat Datang!',
                    message: 'Selamat bergabung di StickerLink melalui Google!',
                    timestamp: new Date().toISOString(),
                    read: false
                }
            ];
            localStorage.setItem('stickerlink_notifications', JSON.stringify(notificationsDB));
            
            const settingsDB = JSON.parse(localStorage.getItem('stickerlink_settings') || '{}');
            settingsDB[userId] = {
                notifications: { email: true, sales: true, withdrawal: true, promo: true },
                twoFactor: false
            };
            localStorage.setItem('stickerlink_settings', JSON.stringify(settingsDB));
            
            currentUser = newUser;
            isLoggedIn = true;
            localStorage.setItem('stickerlink_current_user', JSON.stringify(newUser));
            showNotification('Pendaftaran via Google berhasil!', 'success');
        }
        
        showPage('home');
        updateSidebar();
        updateProfileUI();
        updateStats();
        updateNotificationBadge();
        updateChatBadge();
        updateVerificationStatus();
        
        if (Notification.permission === 'default') {
            Notification.requestPermission();
        }
    } catch (error) {
        console.error('Google Sign-In error:', error);
        showNotification('Gagal login dengan Google', 'error');
    }
};

// ========== FACEBOOK LOGIN ==========
window.fbAsyncInit = function() {
    FB.init({
        appId: '934646352489645',
        cookie: true,
        xfbml: true,
        version: 'v18.0'
    });
};

function handleFacebookLogin() {
    FB.login(function(response) {
        if (response.authResponse) {
            FB.api('/me', { fields: 'id,name,email' }, function(userInfo) {
                const usersDB = JSON.parse(localStorage.getItem('stickerlink_users') || '{}');
                let foundUser = null;
                
                for (let id in usersDB) {
                    if (usersDB[id].email === userInfo.email) {
                        foundUser = usersDB[id];
                        break;
                    }
                }
                
                if (foundUser) {
                    currentUser = foundUser;
                    isLoggedIn = true;
                    localStorage.setItem('stickerlink_current_user', JSON.stringify(foundUser));
                    showNotification('Login Facebook berhasil!', 'success');
                } else {
                    const username = userInfo.email.split('@')[0].replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
                    const userId = 'user_' + Date.now();
                    const newUser = {
                        id: userId,
                        username: username + '_' + Math.floor(Math.random() * 1000),
                        email: userInfo.email,
                        password: 'fb_' + Math.random().toString(36).substring(2),
                        fullName: userInfo.name || '',
                        bio: '',
                        avatar: '',
                        balance: 0,
                        danaName: '',
                        danaPhone: '',
                        verified: false,
                        verificationPending: false,
                        ktpImage: null,
                        selfieImage: null,
                        createdAt: new Date().toISOString(),
                        facebookId: userInfo.id
                    };
                    
                    usersDB[userId] = newUser;
                    localStorage.setItem('stickerlink_users', JSON.stringify(usersDB));
                    
                    const storesDB = JSON.parse(localStorage.getItem('stickerlink_stores') || '{}');
                    storesDB[userId] = {
                        name: newUser.username + "'s Sticker Shop",
                        description: 'Toko stiker digital berkualitas',
                        category: 'art',
                        email: userInfo.email,
                        avatar: '',
                        banner: '',
                        visits: 0
                    };
                    localStorage.setItem('stickerlink_stores', JSON.stringify(storesDB));
                    
                    const productsDB = JSON.parse(localStorage.getItem('stickerlink_products') || '{}');
                    productsDB[userId] = [];
                    localStorage.setItem('stickerlink_products', JSON.stringify(productsDB));
                    
                    currentUser = newUser;
                    isLoggedIn = true;
                    localStorage.setItem('stickerlink_current_user', JSON.stringify(newUser));
                    showNotification('Pendaftaran via Facebook berhasil!', 'success');
                }
                
                showPage('home');
                updateSidebar();
                updateProfileUI();
                updateStats();
                updateNotificationBadge();
            });
        } else {
            showNotification('Login Facebook dibatalkan', 'error');
        }
    }, { scope: 'public_profile,email' });
}

// ========== LOGOUT FUNCTION ==========
function logout() {
    currentUser = null;
    isLoggedIn = false;
    localStorage.removeItem('stickerlink_current_user');
    showNotification('Logout berhasil', 'success');
    showPage('home');
    updateSidebar();
    updateProfileUI();
    updateNotificationBadge();
    updateChatBadge();
}

// ========== SWITCH AUTH TAB ==========
function switchAuthTab(tab) {
    if (tab === 'login') {
        document.getElementById('loginTab')?.classList.add('active');
        document.getElementById('registerTab')?.classList.remove('active');
        document.getElementById('loginForm')?.style.setProperty('display', 'block');
        document.getElementById('registerForm')?.style.setProperty('display', 'none');
    } else {
        document.getElementById('registerTab')?.classList.add('active');
        document.getElementById('loginTab')?.classList.remove('active');
        document.getElementById('registerForm')?.style.setProperty('display', 'block');
        document.getElementById('loginForm')?.style.setProperty('display', 'none');
    }
}

// ========== PASSWORD TOGGLE ==========
function togglePassword(inputId, icon) {
    const input = document.getElementById(inputId);
    if (input) {
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    }
}

// ========== FORGOT PASSWORD ==========
function showForgotPasswordModal() {
    openModal('forgotPasswordModal');
    resetForgotSteps();
}

function resetForgotSteps() {
    const step1 = document.getElementById('forgotStep1');
    const step2 = document.getElementById('forgotStep2');
    const step3 = document.getElementById('forgotStep3');
    
    if (step1) step1.style.display = 'block';
    if (step2) step2.style.display = 'none';
    if (step3) step3.style.display = 'none';
    
    const forgotEmail = document.getElementById('forgotEmail');
    if (forgotEmail) forgotEmail.value = '';
    
    clearOtpInputs();
    if (otpTimer) clearInterval(otpTimer);
}

function clearOtpInputs() {
    for (let i = 1; i <= 6; i++) {
        const otpInput = document.getElementById(`otp${i}`);
        if (otpInput) otpInput.value = '';
    }
}

function requestOtp() {
    const email = document.getElementById('forgotEmail')?.value.trim();
    if (!email) {
        showNotification('Masukkan email', 'error');
        return;
    }
    
    const usersDB = JSON.parse(localStorage.getItem('stickerlink_users') || '{}');
    let found = false;
    for (const id in usersDB) {
        if (usersDB[id].email === email) {
            found = true;
            break;
        }
    }
    
    if (!found) {
        showNotification('Email tidak terdaftar', 'error');
        return;
    }
    
    currentOtp = Math.floor(100000 + Math.random() * 900000).toString();
    otpEmail = email;
    
    console.log('📧 Kode OTP untuk', email, ':', currentOtp);
    showNotification(`Kode OTP: ${currentOtp} (Cek console browser)`, 'info');
    
    const step1 = document.getElementById('forgotStep1');
    const step2 = document.getElementById('forgotStep2');
    if (step1) step1.style.display = 'none';
    if (step2) step2.style.display = 'block';
    
    startOtpTimer(120);
    
    const resendBtn = document.getElementById('resendOtpBtn');
    if (resendBtn) {
        resendBtn.disabled = true;
        setTimeout(() => {
            if (resendBtn) resendBtn.disabled = false;
        }, 30000);
    }
}

function startOtpTimer(seconds) {
    const timerSpan = document.getElementById('timerSeconds');
    let timeLeft = seconds;
    
    if (otpTimer) clearInterval(otpTimer);
    
    otpTimer = setInterval(() => {
        timeLeft--;
        if (timerSpan) timerSpan.textContent = timeLeft;
        
        if (timeLeft <= 0) {
            clearInterval(otpTimer);
            currentOtp = '';
        }
    }, 1000);
}

function resendOtp() {
    if (!otpEmail) return;
    currentOtp = Math.floor(100000 + Math.random() * 900000).toString();
    console.log('📧 OTP baru:', currentOtp);
    showNotification(`Kode OTP baru: ${currentOtp}`, 'info');
    
    if (otpTimer) clearInterval(otpTimer);
    startOtpTimer(120);
    
    const resendBtn = document.getElementById('resendOtpBtn');
    if (resendBtn) {
        resendBtn.disabled = true;
        setTimeout(() => {
            if (resendBtn) resendBtn.disabled = false;
        }, 30000);
    }
}

function moveToNext(current, nextId) {
    if (current.value.length >= 1 && nextId <= 6) {
        const nextInput = document.getElementById(`otp${nextId}`);
        if (nextInput) nextInput.focus();
    }
}

function verifyOtp() {
    let enteredOtp = '';
    for (let i = 1; i <= 6; i++) {
        const otpInput = document.getElementById(`otp${i}`);
        if (otpInput) enteredOtp += otpInput.value;
    }
    
    if (enteredOtp === currentOtp) {
        const step2 = document.getElementById('forgotStep2');
        const step3 = document.getElementById('forgotStep3');
        if (step2) step2.style.display = 'none';
        if (step3) step3.style.display = 'block';
        if (otpTimer) clearInterval(otpTimer);
    } else {
        showNotification('Kode OTP salah', 'error');
    }
}

function resetPassword() {
    const newPassword = document.getElementById('newPasswordForgot')?.value;
    const confirmPassword = document.getElementById('confirmNewPasswordForgot')?.value;
    
    if (!newPassword || !confirmPassword) {
        showNotification('Isi semua field', 'error');
        return;
    }
    
    if (newPassword.length < 6) {
        showNotification('Password minimal 6 karakter', 'error');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showNotification('Password tidak cocok', 'error');
        return;
    }
    
    const usersDB = JSON.parse(localStorage.getItem('stickerlink_users') || '{}');
    for (const id in usersDB) {
        if (usersDB[id].email === otpEmail) {
            usersDB[id].password = newPassword;
            localStorage.setItem('stickerlink_users', JSON.stringify(usersDB));
            break;
        }
    }
    
    showNotification('Password berhasil direset! Silakan login.', 'success');
    closeModal('forgotPasswordModal');
    resetForgotSteps();
}

function backToForgotStep1() {
    const step1 = document.getElementById('forgotStep1');
    const step2 = document.getElementById('forgotStep2');
    const step3 = document.getElementById('forgotStep3');
    
    if (step1) step1.style.display = 'block';
    if (step2) step2.style.display = 'none';
    if (step3) step3.style.display = 'none';
    
    if (otpTimer) clearInterval(otpTimer);
}
