games_app/prediqo_mobile/lib/features/home/presentation/home_screen.dart
2026-11-06 18:43:07 +02:00

956 lines
32 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/di/injection.dart';
import '../../../core/errors/app_exception.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/amount_utils.dart';
import '../../../data/models/advertisement_models.dart';
import '../../../data/models/balance_model.dart';
import '../../../data/models/game_catalog_models.dart';
import '../../../data/models/referral_models.dart';
import '../../../domain/repositories/advertisement_repository.dart';
import '../../../domain/repositories/game_catalog_repository.dart';
import '../../../domain/repositories/notification_repository.dart';
import '../../../domain/repositories/referral_repository.dart';
import '../../../domain/repositories/repositories.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/utils/app_update.dart';
import '../../../shared/widgets/app_snackbar.dart';
import '../../../shared/widgets/balance_hero_card.dart';
import '../../../shared/widgets/language_toggle_button.dart';
import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_skeleton.dart';
import '../../../shared/widgets/prediqo_logo.dart';
import '../../../shared/widgets/section_error.dart';
import '../utils/home_navigation.dart';
import '../../prediction/bloc/prediction_bloc.dart';
import '../../wallet/bloc/wallet_bloc.dart';
import '../../prediction/utils/game_catalog_ui.dart';
import 'widgets/home_ad_carousel.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<AdvertisementModel> _heroAds = [];
List<GameCatalogItem> _games = [];
ReferralDashboardModel? _referral;
int _unreadNotifications = 0;
bool _updateAvailable = false;
bool _totpEnabled = true;
bool _totpKnown = false;
bool _adsLoading = true;
bool _gamesLoading = true;
bool _referralLoading = false;
bool _gamesRetrying = false;
bool _referralRetrying = false;
String? _gamesError;
String? _referralError;
Future<void>? _adsInFlight;
Future<void>? _gamesInFlight;
Future<void>? _referralInFlight;
/// Privacy-first: amount hidden until the user reveals it (synced with Wallet).
bool _hideBalance = true;
@override
void initState() {
super.initState();
final cachedGames = sl<GameCatalogRepository>().peekLast();
if (cachedGames != null && cachedGames.isNotEmpty) {
_games = cachedGames;
_gamesLoading = false;
}
final cachedAds = sl<AdvertisementRepository>().peekLast(
placement: 'home_hero',
);
if (cachedAds != null && cachedAds.isNotEmpty) {
_heroAds = cachedAds;
_adsLoading = false;
}
_loadHideBalancePreference();
_load();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.read<PredictionBloc>().add(
const PredictionLoadRequested(ifStale: true),
);
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_checkAppUpdate();
});
}
Future<void> _loadHideBalancePreference() async {
final prefs = await SharedPreferences.getInstance();
if (!mounted) return;
setState(() {
_hideBalance = prefs.getBool(kHideBalancePrefsKey) ?? true;
});
}
Future<void> _toggleHideBalance() async {
final next = !_hideBalance;
setState(() => _hideBalance = next);
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(kHideBalancePrefsKey, next);
}
Future<void> _checkAppUpdate() async {
final available = await checkAppUpdateAvailable();
if (!mounted) return;
setState(() => _updateAvailable = available);
}
Future<T?> _soft<T>(Future<T> future) async {
try {
return await future;
} catch (_) {
return null;
}
}
Future<void> _refreshUnread() async {
final page = await _soft(sl<NotificationRepository>().list(limit: 1));
if (!mounted || page == null) return;
setState(() => _unreadNotifications = page.unreadCount);
}
Future<void> _refreshTotp() async {
final profile = await _soft(sl<AuthRepository>().getProfile());
if (!mounted || profile == null) return;
setState(() {
_totpEnabled = profile.totpEnabled;
_totpKnown = true;
});
}
Future<void> _loadAds({bool force = false}) {
if (_adsInFlight != null) return _adsInFlight!;
final keep = _heroAds.isNotEmpty && !force;
final future = () async {
if (!keep) {
setState(() {
_adsLoading = true;
});
}
try {
final ads = await sl<AdvertisementRepository>().list(
placement: 'home_hero',
force: force,
);
if (!mounted) return;
setState(() {
_heroAds = ads;
_adsLoading = false;
});
} catch (_) {
if (!mounted) return;
// Soft-fail: keep last ads or empty carousel placeholder.
setState(() => _adsLoading = false);
}
}();
_adsInFlight = future.whenComplete(() => _adsInFlight = null);
return _adsInFlight!;
}
Future<void> _loadGames({bool force = false}) {
if (_gamesInFlight != null) return _gamesInFlight!;
final keep = _games.isNotEmpty && !force;
final future = () async {
if (!keep) {
setState(() {
_gamesLoading = true;
_gamesError = null;
_gamesRetrying = force;
});
}
try {
final games = await sl<GameCatalogRepository>().list(force: force);
if (!mounted) return;
setState(() {
_games = games;
_gamesLoading = false;
_gamesError = null;
_gamesRetrying = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_gamesLoading = false;
_gamesRetrying = false;
if (_games.isEmpty) {
_gamesError = AppException.connectionFailedMessage;
}
});
}
}();
_gamesInFlight = future.whenComplete(() => _gamesInFlight = null);
return _gamesInFlight!;
}
Future<void> _loadReferral({bool force = false}) {
if (_referralInFlight != null) return _referralInFlight!;
final future = () async {
setState(() {
if (_referral == null) _referralLoading = true;
_referralError = null;
_referralRetrying = force || _referral == null;
});
try {
final referral = await sl<ReferralRepository>().getDashboard(
maxDepth: 1,
);
if (!mounted) return;
setState(() {
_referral = referral;
_referralLoading = false;
_referralError = null;
_referralRetrying = false;
});
} catch (_) {
if (!mounted) return;
setState(() {
_referralLoading = false;
_referralRetrying = false;
if (_referral == null) {
_referralError = AppException.connectionFailedMessage;
}
});
}
}();
_referralInFlight = future.whenComplete(() => _referralInFlight = null);
return _referralInFlight!;
}
Future<void> _loadExtras() async {
final notifFuture = _soft(sl<NotificationRepository>().list(limit: 1));
final profileFuture = _soft(sl<AuthRepository>().getProfile());
final referralFuture = _loadReferral();
final notifPage = await notifFuture;
final profile = await profileFuture;
await referralFuture;
if (!mounted) return;
setState(() {
if (notifPage != null) _unreadNotifications = notifPage.unreadCount;
if (profile != null) {
_totpEnabled = profile.totpEnabled;
_totpKnown = true;
}
});
}
Future<void> _load({bool force = false}) async {
if (force && mounted) {
context.read<WalletBloc>().add(const WalletLoadRequested());
}
await Future.wait([
_loadAds(force: force),
_loadGames(force: force),
_loadExtras(),
]);
}
Future<void> _onUpdateTap() =>
handleAppUpdateTap(context, updateAvailable: _updateAvailable);
void _openHelp() => context.push('/faq?category=predictions');
void _openGame(GameCatalogItem game) {
if (!game.isPlayable) {
showSuccessSnackBar(context, context.strings.gameComingSoon);
return;
}
context.go(gamePlayRoute(game));
}
BalanceModel? _usdtBalance(List<BalanceModel> balances) {
for (final b in balances) {
if (b.walletType.code.toUpperCase().contains('USDT')) return b;
}
return balances.isEmpty ? null : balances.first;
}
@override
Widget build(BuildContext context) {
final s = context.strings;
final bottomInset = MediaQuery.paddingOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.light,
statusBarBrightness: Brightness.dark,
),
child: Column(
children: [
DecoratedBox(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFF059669),
Color(0xFF047857),
Color(0xFF0F172A),
],
),
),
child: SafeArea(
bottom: false,
child: SizedBox(
height: kToolbarHeight,
child: Padding(
padding: const EdgeInsets.only(left: 16, right: 4),
child: Row(
children: [
const PrediqoLogo(size: 28, showWordmark: false),
const SizedBox(width: 10),
Text(
s.appName,
style: const TextStyle(
fontWeight: FontWeight.w900,
letterSpacing: 0.4,
color: Colors.white,
fontSize: 20,
),
),
const Spacer(),
const LanguageToggleButton(),
_HeaderIconButton(
tooltip: s.appUpdate,
icon: Icons.system_update_alt_rounded,
foregroundColor: Colors.white,
showBadge: _updateAvailable,
badgeColor: AppColors.warning,
onPressed: _onUpdateTap,
),
_HeaderIconButton(
tooltip: s.notificationsTitle,
icon: Icons.notifications_none_rounded,
foregroundColor: Colors.white,
showBadge: _unreadNotifications > 0,
badgeLabel: _unreadNotifications > 9
? '9+'
: '$_unreadNotifications',
onPressed: () async {
await context.push('/notifications');
if (mounted) _refreshUnread();
},
),
],
),
),
),
),
),
Expanded(
child: RefreshIndicator(
onRefresh: () => _load(force: true),
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
slivers: [
SliverPadding(
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
sliver: SliverList(
delegate: SliverChildListDelegate([
BlocBuilder<WalletBloc, WalletState>(
builder: (context, wallet) {
final balance = _usdtBalance(wallet.balances);
final loading =
wallet.isLoading && wallet.balances.isEmpty;
if (loading) {
return const PredSkeletonCard(height: 64);
}
//final code = balance?.walletType.code ?? 'USDT';
final code = 'USDT';
final decimals = balance?.walletType.decimals ?? 6;
final amountLabel = _hideBalance
? '****** $code'
: balance == null
? '— $code'
: '${rawAmountToHuman(balance.available, decimals)} $code';
return BalanceHeroCard(
amountLabel: amountLabel,
obscured: _hideBalance,
onVisibilityToggle: _toggleHideBalance,
);
},
),
if ((_adsLoading && _heroAds.isEmpty) ||
_heroAds.isNotEmpty) ...[
const SizedBox(height: 12),
HomeAdCarousel(
ads: _heroAds,
loading: _adsLoading && _heroAds.isEmpty,
),
const SizedBox(height: 22),
],
_SectionTitle(
title: s.playNow,
subtitle: s.playNowSubtitle,
),
const SizedBox(height: 12),
if (_gamesError != null && _games.isEmpty)
SectionError(
message: _gamesError!,
retrying: _gamesRetrying,
onRetry: () => _loadGames(force: true),
)
else if (_games.isNotEmpty)
..._games
.take(4)
.map(
(g) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _GameCard(
game: g,
onTap: () => _openGame(g),
),
),
)
else if (_gamesLoading)
const Column(
children: [
PredSkeletonCard(height: 88),
SizedBox(height: 10),
PredSkeletonCard(height: 88),
],
)
else
_FeaturedPredictCard(
onTap: () => context.go('/predict'),
),
const SizedBox(height: 12),
// Single quick action — Predict / Referral / Help live in
// Play Now, Your Network, How it Works (and bottom nav).
PredCard(
key: const Key('home_deposit_shortcut'),
onTap: () => context.push('/deposit'),
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 14,
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColors.info.withValues(alpha: 0.16),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.add_rounded,
color: AppColors.info,
),
),
const SizedBox(width: 14),
Expanded(
child: Text(
s.deposit,
style: const TextStyle(
fontWeight: FontWeight.w800,
fontSize: 16,
),
),
),
const Icon(
Icons.chevron_right_rounded,
color: AppColors.textMuted,
),
],
),
),
if (_totpKnown && !_totpEnabled) ...[
const SizedBox(height: 22),
_SectionTitle(
title: s.homeSecurity,
subtitle: s.homeTwoFaTitle,
),
const SizedBox(height: 12),
_TwoFaPromptCard(
onTap: () async {
await context.push('/totp-setup');
if (mounted) _refreshTotp();
},
),
],
if (_referralError != null && _referral == null) ...[
const SizedBox(height: 22),
_SectionTitle(
title: s.yourNetwork,
subtitle: s.yourNetworkSubtitle,
),
const SizedBox(height: 12),
SectionError(
message: _referralError!,
compact: true,
retrying: _referralRetrying,
onRetry: () => _loadReferral(force: true),
),
] else if (_referralLoading && _referral == null) ...[
const SizedBox(height: 22),
_SectionTitle(
title: s.yourNetwork,
subtitle: s.yourNetworkSubtitle,
),
const SizedBox(height: 12),
const PredSkeletonCard(height: 96),
] else if (_referral != null) ...[
const SizedBox(height: 22),
_SectionTitle(
title: s.yourNetwork,
subtitle: s.yourNetworkSubtitle,
),
const SizedBox(height: 12),
_ReferralTeaser(
dashboard: _referral!,
obscured: _hideBalance,
onTap: () => context.push('/referral'),
),
],
const SizedBox(height: 22),
_HowItWorksCard(onTap: _openHelp),
]),
),
),
],
),
),
),
],
),
);
}
}
class _HeaderIconButton extends StatelessWidget {
const _HeaderIconButton({
required this.icon,
required this.onPressed,
this.tooltip,
this.showBadge = false,
this.badgeLabel,
this.badgeColor = AppColors.danger,
this.foregroundColor,
});
final IconData icon;
final VoidCallback onPressed;
final String? tooltip;
final bool showBadge;
final String? badgeLabel;
final Color badgeColor;
final Color? foregroundColor;
@override
Widget build(BuildContext context) {
return IconButton(
tooltip: tooltip,
onPressed: onPressed,
icon: Stack(
clipBehavior: Clip.none,
children: [
Icon(icon, color: foregroundColor),
if (showBadge)
Positioned(
right: -4,
top: -4,
child: Container(
constraints: const BoxConstraints(minWidth: 16, minHeight: 16),
padding: badgeLabel != null
? const EdgeInsets.symmetric(horizontal: 4)
: EdgeInsets.zero,
decoration: BoxDecoration(
color: badgeColor,
borderRadius: BorderRadius.circular(999),
),
alignment: Alignment.center,
child: badgeLabel != null
? Text(
badgeLabel!,
style: const TextStyle(
color: Colors.white,
fontSize: 9,
fontWeight: FontWeight.w800,
),
)
: const SizedBox(width: 8, height: 8),
),
),
],
),
);
}
}
class _SectionTitle extends StatelessWidget {
const _SectionTitle({required this.title, this.subtitle});
final String title;
final String? subtitle;
@override
Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w800),
),
if (subtitle != null) ...[
const SizedBox(height: 2),
Text(
subtitle!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: isDark ? AppColors.textMuted : const Color(0xFF64748B),
),
),
],
],
);
}
}
class _FeaturedPredictCard extends StatelessWidget {
const _FeaturedPredictCard({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final endColor = isDark ? AppColors.surfaceCard : Colors.white;
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(18),
gradient: LinearGradient(
colors: [
AppColors.primary.withValues(alpha: isDark ? 0.2 : 0.12),
endColor,
],
),
child: Row(
children: [
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: AppColors.primary.withValues(alpha: 0.18),
),
child: Icon(predictionGamesNavIcon, color: AppColors.primary),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.predictionGamesTitle,
style: const TextStyle(fontWeight: FontWeight.w800),
),
const SizedBox(height: 4),
Text(
s.predictionGamesSubtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: isDark
? AppColors.textSecondary
: const Color(0xFF475569),
),
),
],
),
),
Icon(
Icons.chevron_right_rounded,
color: isDark ? AppColors.textMuted : const Color(0xFF94A3B8),
),
],
),
);
}
}
class _GameCard extends StatelessWidget {
const _GameCard({required this.game, required this.onTap});
final GameCatalogItem game;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = context.strings;
final accent = parseHexColor(game.accentColor);
final statusLabel = switch (game.status) {
'coming_soon' => s.gameComingSoon,
'maintenance' => s.gameMaintenance,
_ => s.play,
};
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(16),
child: Row(
children: [
Container(
width: 52,
height: 52,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14),
gradient: LinearGradient(
colors: [accent, accent.withValues(alpha: 0.55)],
),
),
clipBehavior: Clip.antiAlias,
child: game.thumbnailUrl != null && game.thumbnailUrl!.isNotEmpty
? Image.network(
game.thumbnailUrl!,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
Icon(gameCatalogIcon(game), color: Colors.white),
)
: Icon(gameCatalogIcon(game), color: Colors.white),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
game.title,
style: const TextStyle(fontWeight: FontWeight.w800),
),
if (game.description != null &&
game.description!.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
game.description!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textSecondary,
),
),
],
],
),
),
const SizedBox(width: 8),
Text(
statusLabel,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 12,
color: game.isPlayable ? AppColors.primary : AppColors.textMuted,
),
),
],
),
);
}
}
class _TwoFaPromptCard extends StatelessWidget {
const _TwoFaPromptCard({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final endColor = isDark ? AppColors.surfaceCard : Colors.white;
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(16),
gradient: LinearGradient(
colors: [
AppColors.warning.withValues(alpha: isDark ? 0.18 : 0.12),
endColor,
],
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColors.warning.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.shield_outlined, color: AppColors.warning),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.homeTwoFaTitle,
style: const TextStyle(fontWeight: FontWeight.w800),
),
const SizedBox(height: 4),
Text(
s.homeTwoFaSubtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: isDark
? AppColors.textSecondary
: const Color(0xFF475569),
),
),
const SizedBox(height: 8),
Text(
s.homeTwoFaCta,
style: const TextStyle(
color: AppColors.warning,
fontWeight: FontWeight.w700,
fontSize: 13,
),
),
],
),
),
Icon(
Icons.chevron_right_rounded,
color: isDark ? AppColors.textMuted : const Color(0xFF94A3B8),
),
],
),
);
}
}
class _ReferralTeaser extends StatelessWidget {
const _ReferralTeaser({
required this.dashboard,
required this.onTap,
this.obscured = true,
});
final ReferralDashboardModel dashboard;
final VoidCallback onTap;
final bool obscured;
@override
Widget build(BuildContext context) {
final s = context.strings;
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: _MiniStat(
label: s.directReferrals,
value: obscured ? '*****' : '${dashboard.directReferrals}',
obscured: obscured,
),
),
Expanded(
child: _MiniStat(
label: s.networkSize,
value: obscured ? '*****' : '${dashboard.networkSize}',
obscured: obscured,
),
),
Expanded(
child: _MiniStat(
label: s.totalEarned,
value: obscured
? '*****'
: rawAmountToHuman(dashboard.totalEarnedRaw, 6),
obscured: obscured,
),
),
],
),
);
}
}
class _MiniStat extends StatelessWidget {
const _MiniStat({
required this.label,
required this.value,
this.obscured = false,
});
final String label;
final String value;
final bool obscured;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(
value,
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 16,
letterSpacing: obscured ? 1.5 : 0,
),
),
const SizedBox(height: 2),
Text(
label,
textAlign: TextAlign.center,
style: Theme.of(
context,
).textTheme.labelSmall?.copyWith(color: AppColors.textMuted),
),
],
);
}
}
class _HowItWorksCard extends StatelessWidget {
const _HowItWorksCard({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = context.strings;
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(
Icons.lightbulb_outline_rounded,
color: AppColors.accentGold,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.howItWorks,
style: const TextStyle(fontWeight: FontWeight.w800),
),
const SizedBox(height: 4),
Text(
s.howItWorksSubtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textSecondary,
),
),
],
),
),
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
],
),
);
}
}