import { initializeApp } from 'firebase/app';
import {
    getAuth,
    GoogleAuthProvider,
    signInWithPopup,
    signInWithRedirect,
    getRedirectResult
} from 'firebase/auth';

const firebaseConfig = {
    apiKey: "AIzaSyAG8nmGLHYmXGkl018NjW2sMcIiutM4ne0",
    authDomain: "sibu2-0-transport-2026.firebaseapp.com",
    projectId: "sibu2-0-transport-2026",
    storageBucket: "sibu2-0-transport-2026.firebasestorage.app",
    messagingSenderId: "1015760260932",
    appId: "1:1015760260932:web:5657b544bc8099ab54d111"
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();

// Detect if the user is on a mobile device
const isMobile = () => {
    return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent);
};

/**
 * Signs in with Google.
 * - Uses signInWithPopup on desktop (fast, no page reload)
 * - Uses signInWithRedirect on mobile (avoids popup blocking on mobile browsers)
 */
export const signInWithGoogle = async (): Promise<{ user: any; token: string }> => {
    if (isMobile()) {
        // On mobile, redirect flow is more reliable
        await signInWithRedirect(auth, googleProvider);
        // The page will reload; the result is handled by getGoogleRedirectResult() on app load
        // We return a never-resolving promise to keep the UI in loading state
        return new Promise(() => { });
    } else {
        // On desktop, use popup
        const result = await signInWithPopup(auth, googleProvider);
        const token = await result.user.getIdToken();
        return { user: result.user, token };
    }
};

/**
 * Call this once when the app loads (e.g., in App.vue or main.ts) to
 * handle the result from a Google redirect login on mobile.
 * Returns null if there is no pending redirect result.
 */
export const getGoogleRedirectResult = async (): Promise<{ user: any; token: string } | null> => {
    try {
        const result = await getRedirectResult(auth);
        if (result && result.user) {
            const token = await result.user.getIdToken();
            return { user: result.user, token };
        }
        return null;
    } catch (error) {
        console.error("Error getting redirect result:", error);
        return null;
    }
};
