games_app/prediqo_mobile/lib/features/auth/presentation/login_screen.dart
2026-11-15 19:48:21 +02:00

502 lines
22 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/app_snackbar.dart';
import '../../../shared/widgets/pred_button.dart';
import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_text_field.dart';
import '../../../shared/widgets/prediqo_logo.dart';
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../../../shared/widgets/turnstile_captcha.dart';
import '../../welcome/utils/welcome_navigation.dart';
import '../bloc/auth_bloc.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key, this.showVerifyEmailHint = false});
final bool showVerifyEmailHint;
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _totpController = TextEditingController();
final _mathAnswerController = TextEditingController();
bool _obscurePassword = true;
/// Only kept on screen for EMAIL_NOT_VERIFIED (needs resend action).
String? _verifyBanner;
late bool _showVerifyHint;
Timer? _bannerTimer;
/// Local captcha UI state (survives AuthClearFeedback).
bool _captchaRequired = false;
String? _captchaProvider; // 'math' | 'turnstile'
String? _mathPrompt;
String? _mathChallengeToken;
String? _turnstileSiteKey;
String? _turnstileToken;
int _turnstileRemountKey = 0;
@override
void initState() {
super.initState();
_showVerifyHint = widget.showVerifyEmailHint;
if (_showVerifyHint) {
_bannerTimer = scheduleMessageClear(setState, () {
_showVerifyHint = false;
}, duration: const Duration(seconds: 6));
}
}
@override
void dispose() {
_bannerTimer?.cancel();
_emailController.dispose();
_passwordController.dispose();
_totpController.dispose();
_mathAnswerController.dispose();
super.dispose();
}
void _consumeFeedback() {
context.read<AuthBloc>().add(const AuthClearFeedback());
}
void _clearCaptchaUi({required bool remountTurnstile}) {
_mathPrompt = null;
_mathChallengeToken = null;
_mathAnswerController.clear();
_turnstileToken = null;
if (remountTurnstile) {
_turnstileRemountKey++;
}
}
void _applyCaptchaChallenge(Map<String, dynamic>? captcha) {
final provider = captcha?['provider']?.toString();
final prompt = captcha?['prompt']?.toString();
final token = captcha?['challengeToken']?.toString();
final siteKey = captcha?['siteKey']?.toString();
setState(() {
_captchaRequired = true;
_clearCaptchaUi(remountTurnstile: provider == 'turnstile');
if (provider == 'turnstile') {
_captchaProvider = 'turnstile';
_turnstileSiteKey =
(siteKey != null && siteKey.isNotEmpty) ? siteKey : null;
return;
}
if (provider == 'math' &&
prompt != null &&
token != null &&
token.isNotEmpty) {
_captchaProvider = 'math';
_turnstileSiteKey = null;
_mathPrompt = prompt;
_mathChallengeToken = token;
return;
}
// Keep any existing challenge when the error has no captcha payload.
});
}
String? _buildCaptchaToken() {
if (!_captchaRequired) return null;
if (_captchaProvider == 'turnstile') {
final token = _turnstileToken?.trim();
if (token == null || token.isEmpty) return null;
return token;
}
final token = _mathChallengeToken;
final answer = _mathAnswerController.text.trim();
if (token == null || token.isEmpty || answer.isEmpty) return null;
return 'math:$token:$answer';
}
void _submitLogin() {
final bloc = context.read<AuthBloc>();
if (bloc.state.isSubmitting) return;
final s = context.strings;
final email = _emailController.text.trim();
final password = _passwordController.text;
if (email.isEmpty || password.isEmpty) {
showErrorSnackBar(context, s.loginFieldsRequired);
return;
}
final captchaToken = _buildCaptchaToken();
if (_captchaRequired && (captchaToken == null || captchaToken.isEmpty)) {
showErrorSnackBar(context, s.captchaTurnstileHelper);
return;
}
setState(() => _verifyBanner = null);
bloc.add(AuthLoginRequested(
email: email,
password: password,
totpCode: _totpController.text.isEmpty ? null : _totpController.text,
captchaToken: captchaToken,
));
}
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final bottomInset = MediaQuery.paddingOf(context).bottom;
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('login_screen'),
body: Column(
children: [
TlotoGradientAppBar(
title: s.signIn,
showBack: true,
backButtonKey: const Key('login_back'),
onBack: () => popToWelcomeOrPrevious(context),
),
Expanded(
child: Center(
child: SingleChildScrollView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset + keyboardInset,
),
child: BlocConsumer<AuthBloc, AuthState>(
listenWhen: (prev, curr) =>
prev.status != curr.status ||
prev.errorMessage != curr.errorMessage ||
prev.registerMessage != curr.registerMessage ||
prev.captcha != curr.captcha,
listener: (context, state) {
if (!isCurrentRoute(context)) return;
if (state.status == AuthStatus.authenticated) {
setState(() {
_verifyBanner = null;
_captchaRequired = false;
_captchaProvider = null;
_turnstileSiteKey = null;
_clearCaptchaUi(remountTurnstile: false);
});
_consumeFeedback();
context.go('/home');
return;
}
if (state.status == AuthStatus.verificationResent) {
final msg =
state.registerMessage ?? s.verificationEmailSent;
setState(() {
_verifyBanner = null;
_showVerifyHint = true;
});
_bannerTimer = scheduleMessageClear(
setState,
() => _showVerifyHint = false,
duration: const Duration(seconds: 6),
previous: _bannerTimer,
);
showSuccessSnackBar(context, msg);
_consumeFeedback();
return;
}
if (state.status == AuthStatus.error &&
state.errorMessage != null) {
final msg = state.errorMessage!
.replaceFirst('Exception: ', '');
if (state.isCaptchaChallenge) {
_applyCaptchaChallenge(state.captcha);
} else if (_captchaRequired) {
_applyCaptchaChallenge(state.captcha);
}
if (state.isEmailNotVerified) {
setState(() => _verifyBanner = msg);
_bannerTimer = scheduleMessageClear(
setState,
() => _verifyBanner = null,
duration: const Duration(seconds: 8),
previous: _bannerTimer,
);
} else {
setState(() => _verifyBanner = null);
showErrorSnackBar(context, msg);
}
_consumeFeedback();
}
},
builder: (context, state) {
final loading = state.isSubmitting;
return AutofillGroup(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
PredCard(
gradient: AppColors.heroGradient(isDark),
child: Column(
children: [
const PrediqoLogo(
size: 56,
showWordmark: false,
),
const SizedBox(height: 12),
Text(
s.appName,
style: Theme.of(context)
.textTheme
.headlineMedium
?.copyWith(fontWeight: FontWeight.w800),
),
const SizedBox(height: 6),
Text(
s.tagline,
textAlign: TextAlign.center,
style:
Theme.of(context).textTheme.bodySmall,
),
],
),
)
.animate()
.fadeIn(duration: 400.ms)
.slideY(begin: 0.05, end: 0),
const SizedBox(height: 16),
if (_showVerifyHint) ...[
PredCard(
padding: const EdgeInsets.all(14),
child: Text(s.registerSuccessVerify),
),
const SizedBox(height: 12),
],
if (_verifyBanner != null) ...[
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const Icon(
Icons.error_outline,
color: AppColors.danger,
size: 20,
),
const SizedBox(width: 10),
Expanded(
child: Text(
_verifyBanner!,
style: const TextStyle(
color: AppColors.danger,
fontWeight: FontWeight.w600,
),
),
),
],
),
const SizedBox(height: 8),
Text(
s.emailNotVerifiedHint,
style: Theme.of(context)
.textTheme
.bodySmall,
),
TextButton(
onPressed: loading
? null
: () {
final email =
_emailController.text.trim();
if (email.isEmpty) {
showErrorSnackBar(
context,
s.emailCannotBeEmpty,
);
return;
}
context.read<AuthBloc>().add(
AuthResendVerificationRequested(
email,
),
);
},
child: Text(s.resendVerification),
),
],
),
),
const SizedBox(height: 12),
],
PredCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
PredTextField(
key: const Key('login_email'),
controller: _emailController,
label: s.email,
keyboardType: TextInputType.emailAddress,
prefixIcon: Icons.email_outlined,
enabled: !loading,
textInputAction: TextInputAction.next,
autofillHints: const [AutofillHints.email],
),
const SizedBox(height: 14),
PredTextField(
key: const Key('login_password'),
controller: _passwordController,
label: s.password,
obscure: _obscurePassword,
prefixIcon: Icons.lock_outline,
enabled: !loading,
textInputAction: TextInputAction.next,
autofillHints: const [
AutofillHints.password
],
suffix: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
),
onPressed: loading
? null
: () => setState(
() => _obscurePassword =
!_obscurePassword,
),
),
),
const SizedBox(height: 14),
PredTextField(
controller: _totpController,
label: s.totpCode,
keyboardType: TextInputType.number,
prefixIcon: Icons.security_outlined,
maxLength: 6,
enabled: !loading,
textInputAction: _captchaRequired
? TextInputAction.next
: TextInputAction.done,
onSubmitted:
loading ? null : (_) => _submitLogin(),
),
if (_captchaRequired &&
_captchaProvider == 'turnstile') ...[
const SizedBox(height: 14),
Text(
s.captchaTurnstileHelper,
style: Theme.of(context)
.textTheme
.bodySmall,
),
const SizedBox(height: 8),
if (_turnstileSiteKey != null)
TurnstileCaptcha(
key: ValueKey(
'login_turnstile_$_turnstileRemountKey',
),
siteKey: _turnstileSiteKey!,
onToken: (token) {
if (!mounted) return;
setState(
() => _turnstileToken = token,
);
},
)
else
Text(
s.captchaTurnstileUnavailable,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: Theme.of(context)
.colorScheme
.error,
),
),
],
if (_captchaRequired &&
_captchaProvider == 'math' &&
_mathPrompt != null) ...[
const SizedBox(height: 14),
PredTextField(
key: const Key('login_captcha_math'),
controller: _mathAnswerController,
label: s.captchaMathLabel(_mathPrompt!),
keyboardType: TextInputType.number,
prefixIcon:
Icons.verified_user_outlined,
enabled: !loading,
textInputAction: TextInputAction.done,
onSubmitted: loading
? null
: (_) => _submitLogin(),
),
const SizedBox(height: 4),
Text(
s.captchaMathHelper,
style: Theme.of(context)
.textTheme
.bodySmall,
),
],
const SizedBox(height: 4),
Align(
alignment: Alignment.centerRight,
child: TextButton(
key: const Key('forgot_password_link'),
onPressed: loading
? null
: () => context
.push('/forgot-password'),
child: Text(s.forgotPassword),
),
),
const SizedBox(height: 8),
PredPrimaryButton(
key: const Key('login_submit'),
label: s.signIn,
loading: loading,
onPressed: _submitLogin,
),
const SizedBox(height: 8),
TextButton(
onPressed: loading
? null
: () => context.go('/register'),
child: Text(s.signUp),
),
],
),
),
],
),
);
},
),
),
),
),
],
),
),
);
}
}