let googleInitialized = false;

window.initGoogleSignIn = function(clientId) {
    if (googleInitialized) {
        console.log("Google Sign-In already initialized");
        return;
    }

    console.log("🔐 Initializing Google Sign-In (ID Token flow)");
    console.log("📋 Received clientId:", clientId);
    console.log("📋 ClientId type:", typeof clientId);
    console.log("📋 ClientId length:", clientId ? clientId.length : 0);

    if (!clientId || clientId === '' || clientId === 'null' || clientId === 'undefined') {
        console.error("❌ Invalid clientId received:", clientId);
        throw new Error("ClientId is null, empty, or invalid");
    }

    // Check if Google library is loaded
    if (typeof google === 'undefined' || !google.accounts || !google.accounts.id) {
        console.error("❌ Google Sign-In library not loaded yet!");
        throw new Error("Google Sign-In library not ready");
    }

    // Używamy google.accounts.id - zwraca ID token (JWT credential)
    google.accounts.id.initialize({
        client_id: clientId,
        callback: handleCredentialResponse,
        auto_select: false,
        cancel_on_tap_outside: true
    });

    googleInitialized = true;
    console.log("✅ Google Sign-In initialized successfully");
};

window.requestGoogleSignIn = function() {
    console.log("🚀 Requesting Google Sign-In...");

    // Pokaż One Tap prompt (without deprecated notification callbacks for FedCM compatibility)
    google.accounts.id.prompt();
};

function handleCredentialResponse(response) {
    console.log("=== 🎉 Google Credential Response ===");
    
    try {
        if (!response.credential) {
            throw new Error("No credential in response");
        }
        
        const tokenParts = response.credential.split('.');
        console.log("📝 ID Token parts:", tokenParts.length); // Should be 3 (JWT)
        console.log("📏 ID Token length:", response.credential.length);
        
        if (tokenParts.length !== 3) {
            throw new Error("Invalid JWT format - expected 3 parts (header.payload.signature)");
        }
        
        // Dekoduj payload JWT aby wyciągnąć user info
        const payload = decodeJwtPayload(response.credential);
        
        const fullName = payload.name || `${payload.given_name || ''} ${payload.family_name || ''}`.trim();
        const email = payload.email;
        const avatarUrl = payload.picture || '';
        
        console.log("👤 User info from JWT:", { fullName, email });
        console.log("📧 Email verified:", payload.email_verified);
        
        // Wywołaj Blazor - przekaż ID token JWT (nie access token!)
        DotNet.invokeMethodAsync('DiunaBI.UI.Shared', 'OnGoogleSignInSuccess', 
            response.credential,  // <--- To jest ID token JWT dla backendu
            fullName, 
            email, 
            avatarUrl)
            .then(() => {
                console.log("✅ Successfully sent ID token to Blazor");
            })
            .catch(err => {
                console.error("❌ Error calling Blazor:", err);
                DotNet.invokeMethodAsync('DiunaBI.UI.Shared', 'OnGoogleSignInError', err.toString());
            });
    } catch (error) {
        console.error("❌ Error processing Google credential:", error);
        DotNet.invokeMethodAsync('DiunaBI.UI.Shared', 'OnGoogleSignInError', error.toString());
    }
}

function decodeJwtPayload(token) {
    try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(
            atob(base64)
                .split('')
                .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
                .join('')
        );
        return JSON.parse(jsonPayload);
    } catch (error) {
        console.error("Error decoding JWT:", error);
        throw new Error("Invalid JWT format");
    }
}