File size: 2,848 Bytes
7b3aac2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// ========================================
// FIREBASE CONFIGURATION
// ========================================
const firebaseConfig = {
    apiKey: "AIzaSyBIQ-4MVpOHCaCI9qoAjvJPfSDdGaK-hEg",
    authDomain: "m-txtile-lasted-web.firebaseapp.com",
    projectId: "m-txtile-lasted-web",
    storageBucket: "m-txtile-lasted-web.firebasestorage.app",
    messagingSenderId: "164555967777",
    appId: "1:164555967777:web:65ef2c62e3b332f1698260",
    measurementId: "G-9EWB1LJ3CZ"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const googleProvider = new firebase.auth.GoogleAuthProvider();

// Google Sign In
async function signInWithGoogle() {
    try {
        const result = await auth.signInWithPopup(googleProvider);
        const user = result.user;

        // Save to MongoDB via API
        const authApiUrl = (window.location.hostname === '127.0.0.1' || window.location.port === '5500')
            ? 'http://localhost:3000/api/auth/google-login'
            : '/api/auth/google-login';

        const res = await fetch(authApiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                uid: user.uid,
                name: user.displayName || 'Foydalanuvchi',
                email: user.email,
                phone: user.phoneNumber || '',
                photoURL: user.photoURL || ''
            })
        });
        const data = await res.json();

        if (data.success) {
            // Save session locally
            localStorage.setItem('mtextile_session', JSON.stringify(data.user));
            document.dispatchEvent(new CustomEvent('authChanged', { detail: { user: data.user } }));
            showToast("Muvaffaqiyat", `Xush kelibsiz, ${data.user.name}!`, "success");

            // Close login modal
            const overlay = document.getElementById('loginOverlay');
            if (overlay) overlay.classList.remove('active');

            // Update UI
            if (typeof updateAuthUI === 'function') updateAuthUI();
            return data.user;
        } else {
            showToast("Xatolik", data.message || "Kirishda xatolik", "error");
            return null;
        }
    } catch (error) {
        if (error.code === 'auth/popup-closed-by-user') {
            return null; // User closed popup, no error needed
        }
        console.error('Google sign-in error:', error);
        showToast("Xatolik", error.message || "Google orqali kirishda xatolik yuz berdi", "error");
        return null;
    }
}

// Sign Out from Firebase
async function firebaseSignOut() {
    try {
        await auth.signOut();
    } catch (e) {
        console.warn('Firebase sign out error:', e);
    }
}