package com.mhss.app.mybrain.presentation.auth import android.app.Activity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException @Composable actual fun rememberGoogleSignInLauncher( onSuccess: (GoogleSignInResult) -> Unit, onError: (String) -> Unit ): () -> Unit { val context = LocalContext.current val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestProfile() .build() val googleSignInClient = GoogleSignIn.getClient(context, gso) val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK && result.data != null) { val task = GoogleSignIn.getSignedInAccountFromIntent(result.data) try { val account = task.getResult(ApiException::class.java) val email = account?.email ?: "" val name = account?.displayName ?: if (email.isNotEmpty()) email.substringBefore("@") else "User" val idToken = account?.idToken if (email.isNotEmpty()) { onSuccess(GoogleSignInResult(email = email, displayName = name, idToken = idToken)) } else { onError("Could not retrieve Google account email.") } } catch (e: Exception) { onError(e.message ?: "Google Sign-In failed.") } } else if (result.resultCode == Activity.RESULT_CANCELED) { onError("Google Sign-In was cancelled.") } else { onError("Google Sign-In encountered an error.") } } return { // Sign out first to always show account picker if user wants to switch accounts try { googleSignInClient.signOut() } catch (_: Exception) {} launcher.launch(googleSignInClient.signInIntent) } }