games_app/prediqo_mobile/lib/features/home/presentation/home_screen.dart
2026-07-27 09:29:50 +02:00

687 lines
22 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.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/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/language_toggle_button.dart';
import '../../../shared/widgets/pred_card.dart';
import '../utils/home_navigation.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> {
bool _loading = true;
String? _error;
List<AdvertisementModel> _heroAds = [];
List<GameCatalogItem> _games = [];
ReferralDashboardModel? _referral;
int _unreadNotifications = 0;
bool _updateAvailable = false;
bool _totpEnabled = true;
@override
void initState() {
super.initState();
_load();
_checkAppUpdate();
}
Future<void> _checkAppUpdate() async {
final available = await checkAppUpdateAvailable();
if (!mounted) return;
setState(() => _updateAvailable = available);
}
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
try {
// Soft-wrap so parallel 401s (expired session) are not reported as
// unhandled async errors before we await them.
Future<T?> soft<T>(Future<T> future) async {
try {
return await future;
} catch (_) {
return null;
}
}
final adsFuture = soft(sl<AdvertisementRepository>().list(placement: 'home_hero'));
final gamesFuture = soft(sl<GameCatalogRepository>().list());
final referralFuture = soft(sl<ReferralRepository>().getDashboard(maxDepth: 1));
final notifFuture = soft(sl<NotificationRepository>().list(limit: 1));
final profileFuture = soft(sl<AuthRepository>().getProfile());
final ads = await adsFuture;
final games = await gamesFuture;
final referral = await referralFuture;
final notifPage = await notifFuture;
final profile = await profileFuture;
if (!mounted) return;
setState(() {
_heroAds = ads ?? const [];
_games = games ?? const [];
_referral = referral;
_unreadNotifications = notifPage?.unreadCount ?? 0;
_totpEnabled = profile?.totpEnabled ?? false;
_loading = false;
if (ads == null && games == null) {
_error = AppException.connectionFailedMessage;
}
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
_loading = false;
});
}
}
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));
}
@override
Widget build(BuildContext context) {
final s = context.strings;
return RefreshIndicator(
onRefresh: _load,
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
slivers: [
SliverAppBar(
floating: true,
pinned: false,
centerTitle: false,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.appName,
style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: 0.2),
),
Text(
s.tagline,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: AppColors.textMuted,
),
),
],
),
actions: [
const LanguageToggleButton(),
_HeaderIconButton(
tooltip: s.appUpdate,
icon: Icons.system_update_alt_rounded,
showBadge: _updateAvailable,
badgeColor: AppColors.warning,
onPressed: _onUpdateTap,
),
_HeaderIconButton(
tooltip: s.notificationsTitle,
icon: Icons.notifications_none_rounded,
showBadge: _unreadNotifications > 0,
badgeLabel: _unreadNotifications > 9 ? '9+' : '$_unreadNotifications',
onPressed: () async {
await context.push('/notifications');
if (mounted) _load();
},
),
const SizedBox(width: 4),
],
),
if (_error != null && !_loading)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 12),
FilledButton(onPressed: _load, child: Text(s.retry)),
],
),
),
),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
sliver: SliverList(
delegate: SliverChildListDelegate([
HomeAdCarousel(ads: _heroAds, loading: _loading)
.animate()
.fadeIn(duration: 350.ms)
.slideY(begin: 0.04, end: 0),
const SizedBox(height: 22),
_SectionTitle(title: s.playNow, subtitle: s.playNowSubtitle),
const SizedBox(height: 12),
if (_loading)
const SizedBox(
height: 110,
child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
)
else if (_games.isEmpty)
_FeaturedPredictCard(onTap: () => context.go('/predict'))
else
..._games.take(4).map(
(g) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _GameCard(game: g, onTap: () => _openGame(g)),
),
),
const SizedBox(height: 8),
_SectionTitle(title: s.shortcuts, subtitle: s.shortcutsSubtitle),
const SizedBox(height: 12),
_ShortcutGrid(
items: [
_Shortcut(
icon: predictionGamesNavIcon,
label: s.navPredict,
color: AppColors.primary,
onTap: () => context.go('/predict'),
),
_Shortcut(
icon: Icons.add_rounded,
label: s.deposit,
color: AppColors.info,
onTap: () => context.push('/deposit'),
),
_Shortcut(
icon: Icons.groups_rounded,
label: s.referralTitle,
color: AppColors.accentGold,
onTap: () => context.push('/referral'),
),
_Shortcut(
icon: Icons.help_outline_rounded,
label: s.helpCenter,
color: AppColors.walletBonus,
onTap: _openHelp,
),
],
),
if (!_loading && !_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) _load();
},
),
],
if (_referral != null) ...[
const SizedBox(height: 22),
_SectionTitle(
title: s.yourNetwork,
subtitle: s.yourNetworkSubtitle,
),
const SizedBox(height: 12),
_ReferralTeaser(
dashboard: _referral!,
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,
});
final IconData icon;
final VoidCallback onPressed;
final String? tooltip;
final bool showBadge;
final String? badgeLabel;
final Color badgeColor;
@override
Widget build(BuildContext context) {
return IconButton(
tooltip: tooltip,
onPressed: onPressed,
icon: Stack(
clipBehavior: Clip.none,
children: [
Icon(icon),
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) {
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: AppColors.textMuted,
),
),
],
],
);
}
}
class _FeaturedPredictCard extends StatelessWidget {
const _FeaturedPredictCard({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = context.strings;
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(18),
gradient: LinearGradient(
colors: [
AppColors.primary.withValues(alpha: 0.2),
AppColors.surfaceCard,
],
),
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: AppColors.textSecondary,
),
),
],
),
),
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
],
),
);
}
}
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 _Shortcut {
const _Shortcut({
required this.icon,
required this.label,
required this.color,
required this.onTap,
});
final IconData icon;
final String label;
final Color color;
final VoidCallback onTap;
}
class _ShortcutGrid extends StatelessWidget {
const _ShortcutGrid({required this.items});
final List<_Shortcut> items;
@override
Widget build(BuildContext context) {
return GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 1.55,
children: [
for (final item in items)
PredCard(
onTap: item.onTap,
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(item.icon, color: item.color),
const Spacer(),
Text(item.label, style: const TextStyle(fontWeight: FontWeight.w700)),
],
),
),
],
);
}
}
class _TwoFaPromptCard extends StatelessWidget {
const _TwoFaPromptCard({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final s = context.strings;
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(16),
gradient: LinearGradient(
colors: [
AppColors.warning.withValues(alpha: 0.18),
AppColors.surfaceCard,
],
),
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: AppColors.textSecondary,
),
),
const SizedBox(height: 8),
Text(
s.homeTwoFaCta,
style: const TextStyle(
color: AppColors.warning,
fontWeight: FontWeight.w700,
fontSize: 13,
),
),
],
),
),
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
],
),
);
}
}
class _ReferralTeaser extends StatelessWidget {
const _ReferralTeaser({required this.dashboard, required this.onTap});
final ReferralDashboardModel dashboard;
final VoidCallback onTap;
@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: '${dashboard.directReferrals}',
),
),
Expanded(
child: _MiniStat(
label: s.networkSize,
value: '${dashboard.networkSize}',
),
),
Expanded(
child: _MiniStat(
label: s.totalEarned,
value: rawAmountToHuman(dashboard.totalEarnedRaw, 6),
),
),
],
),
);
}
}
class _MiniStat extends StatelessWidget {
const _MiniStat({required this.label, required this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(value, style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 16)),
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),
],
),
);
}
}