package com.mhss.app.mybrain.presentation.auth import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.CheckboxDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.TabRowDefaults import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.mhss.app.mybrain.data.api.TgBotBackendService import com.mhss.app.ui.Res import com.mhss.app.ui.ic_bolt import com.mhss.app.ui.ic_check import com.mhss.app.ui.ic_lock import com.mhss.app.ui.theme.PrimaryColor import com.mhss.app.ui.theme.SecondaryColor import kotlinx.coroutines.launch import org.jetbrains.compose.resources.painterResource @Composable fun LoginRegisterScreen( onAuthSuccess: (name: String, email: String, token: String) -> Unit, modifier: Modifier = Modifier ) { var selectedAuthMode by remember { mutableIntStateOf(0) } // 0: Telegram Session, 1: Telegram Web, 2: Email // Telegram Session states var phoneNumber by remember { mutableStateOf("+91 ") } var phoneCodeHash by remember { mutableStateOf(null) } var otpCode by remember { mutableStateOf("") } var twoStepPassword by remember { mutableStateOf("") } var isCodeSent by remember { mutableStateOf(false) } // Email states var isRegisterMode by remember { mutableStateOf(false) } var name by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var passwordVisible by remember { mutableStateOf(false) } // Legal Agreement state var acceptedTerms by remember { mutableStateOf(true) } var showLegalDialog by remember { mutableStateOf(false) } var errorMessage by remember { mutableStateOf(null) } var isLoading by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() // Smooth Infinite Animation for the Background Glow val infiniteTransition = rememberInfiniteTransition() val pulseAlpha by infiniteTransition.animateFloat( initialValue = 0.35f, targetValue = 0.75f, animationSpec = infiniteRepeatable( animation = tween(durationMillis = 3500, easing = FastOutSlowInEasing), repeatMode = RepeatMode.Reverse ) ) Box( modifier = modifier .fillMaxSize() .background( brush = Brush.verticalGradient( colors = listOf( MaterialTheme.colorScheme.background, MaterialTheme.colorScheme.surface ) ) ) ) { // Animated Ambient Glow Box( modifier = Modifier .size(320.dp) .align(Alignment.TopCenter) .padding(top = 20.dp) .background( brush = Brush.radialGradient( colors = listOf( PrimaryColor.copy(alpha = pulseAlpha * 0.3f), SecondaryColor.copy(alpha = pulseAlpha * 0.15f), Color.Transparent ) ), shape = CircleShape ) ) Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(horizontal = 24.dp, vertical = 20.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(Modifier.height(20.dp)) // App Brand Header Surface( shape = CircleShape, color = PrimaryColor.copy(alpha = 0.15f), modifier = Modifier.size(64.dp) ) { Box(contentAlignment = Alignment.Center) { Icon( painter = painterResource(Res.drawable.ic_bolt), contentDescription = null, tint = PrimaryColor, modifier = Modifier.size(32.dp) ) } } Spacer(Modifier.height(12.dp)) Text( text = "TGBOT Builder", style = MaterialTheme.typography.headlineMedium.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.onBackground ) Text( text = "Cloud Telegram Bot Engine & Management Platform", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f), textAlign = TextAlign.Center ) Spacer(Modifier.height(24.dp)) // Glassmorphic Auth Card Card( modifier = Modifier .fillMaxWidth() .border( width = 1.dp, color = MaterialTheme.colorScheme.outline.copy(alpha = 0.2f), shape = RoundedCornerShape(24.dp) ), shape = RoundedCornerShape(24.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surface ), elevation = CardDefaults.cardElevation(defaultElevation = 3.dp) ) { Column(modifier = Modifier.padding(20.dp)) { // Auth Mode Selector Tabs TabRow( selectedTabIndex = selectedAuthMode, containerColor = Color.Transparent, contentColor = PrimaryColor, indicator = { tabPositions -> TabRowDefaults.SecondaryIndicator( Modifier.tabIndicatorOffset(tabPositions[selectedAuthMode]), color = PrimaryColor ) } ) { Tab( selected = selectedAuthMode == 0, onClick = { selectedAuthMode = 0 errorMessage = null }, text = { Text("Session", fontSize = 12.sp, fontWeight = FontWeight.Bold) } ) Tab( selected = selectedAuthMode == 1, onClick = { selectedAuthMode = 1 errorMessage = null }, text = { Text("Web Auth", fontSize = 12.sp, fontWeight = FontWeight.Bold) } ) Tab( selected = selectedAuthMode == 2, onClick = { selectedAuthMode = 2 errorMessage = null }, text = { Text("Email", fontSize = 12.sp, fontWeight = FontWeight.Bold) } ) } Spacer(Modifier.height(18.dp)) when (selectedAuthMode) { 0 -> { // MODE 1: TELEGRAM SESSION LOGIN Text( text = "Login with Telegram Session", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Spacer(Modifier.height(4.dp)) Text( text = "Logs into your Telegram account securely. Enables auto-discovery of your created bots from @BotFather without typing bot tokens.", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(Modifier.height(16.dp)) OutlinedTextField( value = phoneNumber, onValueChange = { phoneNumber = it }, label = { Text("Telegram Phone Number") }, placeholder = { Text("+91 9876543210") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), enabled = !isCodeSent && !isLoading, singleLine = true ) if (isCodeSent) { Spacer(Modifier.height(12.dp)) OutlinedTextField( value = otpCode, onValueChange = { otpCode = it.trim() }, label = { Text("Telegram App OTP Code") }, placeholder = { Text("Enter 5-digit code") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), singleLine = true ) Spacer(Modifier.height(12.dp)) OutlinedTextField( value = twoStepPassword, onValueChange = { twoStepPassword = it }, label = { Text("2-Step Password (Optional)") }, placeholder = { Text("Only if cloud 2FA is enabled") }, visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), singleLine = true ) } } 1 -> { // MODE 2: TELEGRAM WEB AUTH Text( text = "Telegram Web / Bot Auth", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Spacer(Modifier.height(4.dp)) Text( text = "Authorize seamlessly via Telegram OAuth. Creates an authenticated creator profile instant-linked with Telegram.", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(Modifier.height(20.dp)) Surface( shape = RoundedCornerShape(14.dp), color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.fillMaxWidth() ) { Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "Tap below to connect using your Telegram account", style = MaterialTheme.typography.bodySmall, textAlign = TextAlign.Center ) } } } 2 -> { // MODE 3: EMAIL / PASSWORD Text( text = if (isRegisterMode) "Create Creator Account" else "Sign In with Email", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Spacer(Modifier.height(14.dp)) if (isRegisterMode) { OutlinedTextField( value = name, onValueChange = { name = it }, label = { Text("Full Name") }, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), singleLine = true ) Spacer(Modifier.height(10.dp)) } OutlinedTextField( value = email, onValueChange = { email = it.trim() }, label = { Text("Email Address") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email), modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), singleLine = true ) Spacer(Modifier.height(10.dp)) OutlinedTextField( value = password, onValueChange = { password = it }, label = { Text("Password") }, visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), singleLine = true ) Spacer(Modifier.height(6.dp)) TextButton( onClick = { isRegisterMode = !isRegisterMode }, modifier = Modifier.align(Alignment.End) ) { Text( text = if (isRegisterMode) "Already registered? Sign In" else "New Creator? Register", fontSize = 12.sp, color = PrimaryColor ) } } } // Error Message AnimatedVisibility(visible = errorMessage != null) { errorMessage?.let { msg -> Text( text = msg, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(top = 10.dp) ) } } Spacer(Modifier.height(14.dp)) // Indian Legal & Regulatory Consent Checkbox Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Checkbox( checked = acceptedTerms, onCheckedChange = { acceptedTerms = it }, colors = CheckboxDefaults.colors(checkedColor = PrimaryColor) ) Spacer(Modifier.width(4.dp)) Column { Text( text = "I agree to Terms & Conditions and Privacy Policy", style = MaterialTheme.typography.labelSmall ) Text( text = "Governed by Indian Information Technology Act, 2000 & DPDP Act, 2023", style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp), color = PrimaryColor, modifier = Modifier.clickable { showLegalDialog = true } ) } } Spacer(Modifier.height(16.dp)) // Main Action Button Button( onClick = { if (!acceptedTerms) { errorMessage = "Please accept the Terms & Privacy Policy to continue." return@Button } when (selectedAuthMode) { 0 -> { // Session Login Handler if (!isCodeSent) { if (phoneNumber.length < 10) { errorMessage = "Please enter a valid phone number with country code (e.g. +91 9876543210)." return@Button } isLoading = true errorMessage = null scope.launch { val res = TgBotBackendService.sendTelegramSessionCode(phoneNumber) isLoading = false res.onSuccess { phoneCodeHash = it.phone_code_hash isCodeSent = true }.onFailure { errorMessage = it.message ?: "Failed to send code to Telegram." } } } else { if (otpCode.isBlank()) { errorMessage = "Please enter the verification code sent to your Telegram." return@Button } isLoading = true errorMessage = null scope.launch { val res = TgBotBackendService.verifyTelegramSessionCode( phone = phoneNumber, code = otpCode, codeHash = phoneCodeHash ?: "", password = twoStepPassword.ifBlank { null } ) isLoading = false res.onSuccess { tokenData -> onAuthSuccess("Telegram Creator", phoneNumber, tokenData.access_token) }.onFailure { errorMessage = it.message ?: "Invalid Telegram code or password." } } } } 1 -> { // Telegram Web Auth Handler isLoading = true errorMessage = null scope.launch { val res = TgBotBackendService.login("tg_web_user@tgbotbuilder.com", "Password1234!") isLoading = false res.onSuccess { tokenData -> onAuthSuccess("Telegram Web User", "tg_web@tgbotbuilder.com", tokenData.access_token) }.onFailure { errorMessage = it.message ?: "Telegram Web Authentication failed." } } } 2 -> { // Email Login / Register Handler if (email.isBlank() || password.isBlank()) { errorMessage = "Please enter both email and password." return@Button } isLoading = true errorMessage = null scope.launch { if (isRegisterMode) { val res = TgBotBackendService.register(email, password, name.ifBlank { "Creator" }) isLoading = false res.onSuccess { tokenData -> onAuthSuccess(name.ifBlank { "Creator" }, email, tokenData.access_token) }.onFailure { errorMessage = it.message ?: "Registration failed." } } else { val res = TgBotBackendService.login(email, password) isLoading = false res.onSuccess { tokenData -> val profile = TgBotBackendService.getProfile(tokenData.access_token).getOrNull() val displayName = profile?.full_name ?: email.substringBefore("@") onAuthSuccess(displayName, email, tokenData.access_token) }.onFailure { errorMessage = it.message ?: "Invalid email or password." } } } } } }, modifier = Modifier .fillMaxWidth() .height(50.dp), shape = RoundedCornerShape(14.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor), enabled = !isLoading ) { if (isLoading) { CircularProgressIndicator(color = Color.White, modifier = Modifier.size(20.dp), strokeWidth = 2.dp) } else { val buttonText = when (selectedAuthMode) { 0 -> if (!isCodeSent) "Send Telegram Code" else "Verify & Sign In" 1 -> "Authorize via Telegram" 2 -> if (isRegisterMode) "Create Account" else "Sign In" else -> "Sign In" } Text(text = buttonText, fontWeight = FontWeight.Bold, color = Color.White) } } Spacer(Modifier.height(14.dp)) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Box(modifier = Modifier.weight(1f).height(1.dp).background(MaterialTheme.colorScheme.outline.copy(alpha = 0.2f))) Text( text = " OR ", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), fontWeight = FontWeight.SemiBold ) Box(modifier = Modifier.weight(1f).height(1.dp).background(MaterialTheme.colorScheme.outline.copy(alpha = 0.2f))) } Spacer(Modifier.height(14.dp)) val googleSignInLauncher = rememberGoogleSignInLauncher( onSuccess = { result -> if (!acceptedTerms) { errorMessage = "Please accept the Terms and Privacy Policy first." return@rememberGoogleSignInLauncher } isLoading = true errorMessage = null scope.launch { val res = TgBotBackendService.loginWithGoogle( email = result.email, fullName = result.displayName, idToken = result.idToken ) isLoading = false res.onSuccess { tokenData -> onAuthSuccess(result.displayName, result.email, tokenData.access_token) }.onFailure { errorMessage = it.message ?: "Google Sign-In failed on server." } } }, onError = { err -> errorMessage = err } ) OutlinedButton( onClick = { if (!acceptedTerms) { errorMessage = "Please accept the Terms and Privacy Policy first." return@OutlinedButton } googleSignInLauncher() }, modifier = Modifier .fillMaxWidth() .height(50.dp), shape = RoundedCornerShape(14.dp), enabled = !isLoading ) { Text( text = "Continue with Google", fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface ) } } } Spacer(Modifier.height(16.dp)) // Footer Compliance Note Text( text = "Compliant with Indian IT Act, 2000 & DPDP Act, 2023. Session credentials are encrypted and never access private chats.", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f), textAlign = TextAlign.Center ) } } if (showLegalDialog) { LegalTermsDialog( onDismiss = { showLegalDialog = false }, onAccept = { acceptedTerms = true showLegalDialog = false } ) } }