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

795 lines
29 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/network/connectivity_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../data/models/advertisement_models.dart';
import '../../../data/models/game_catalog_models.dart';
import '../../../data/models/marketing_models.dart';
import '../../../domain/repositories/advertisement_repository.dart';
import '../../../domain/repositories/game_catalog_repository.dart';
import '../../../domain/repositories/marketing_repository.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/utils/app_update.dart';
import '../../../shared/widgets/language_toggle_button.dart';
import '../../../shared/widgets/offline_banner.dart';
import '../../../shared/widgets/pred_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 '../../home/presentation/widgets/home_ad_carousel.dart';
import '../../home/utils/home_navigation.dart';
import '../../prediction/utils/game_catalog_ui.dart';
import '../utils/marketing_fallback.dart';
import 'widgets/welcome_activity_ticker.dart';
/// Public marketing landing for guests (casino-vibrant Tloto density).
class WelcomeScreen extends StatefulWidget {
const WelcomeScreen({super.key});
@override
State<WelcomeScreen> createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
/// Defaults when API omits refresh hints (offline fallback).
static const _defaultPollSeconds = 30;
static const _defaultRotateSeconds = 8;
static const _activityWindowSize = 5;
bool _updateAvailable = false;
List<AdvertisementModel> _heroAds = [];
List<GameCatalogItem> _games = [];
List<MarketingActivityItem> _activityPool = [];
List<MarketingActivityItem> _activityVisible = [];
List<MarketingWithdrawalItem> _withdrawals = [];
int _activePlayersCount = 0;
int _activityGeneration = 0;
final Set<String> _recentlyShownIds = {};
int _pollSeconds = _defaultPollSeconds;
int _rotateSeconds = _defaultRotateSeconds;
bool _adsLoading = true;
bool _gamesLoading = true;
bool _activityLoading = true;
bool _withdrawalsLoading = true;
bool _gamesRetrying = false;
bool _activityRetrying = false;
bool _withdrawalsRetrying = false;
String? _adsError;
String? _gamesError;
String? _activityError;
String? _withdrawalsError;
Future<void>? _adsInFlight;
Future<void>? _gamesInFlight;
Future<void>? _activityInFlight;
Future<void>? _withdrawalsInFlight;
Timer? _marketingPoll;
Timer? _activityRotate;
static int _clampPollSeconds(int? value) {
final v = value ?? _defaultPollSeconds;
return v.clamp(10, 120);
}
static int _clampRotateSeconds(int? value) {
final v = value ?? _defaultRotateSeconds;
return v.clamp(5, 60);
}
void _restartMarketingTimers({int? pollSeconds, int? rotateSeconds}) {
final nextPoll = _clampPollSeconds(pollSeconds ?? _pollSeconds);
final nextRotate = _clampRotateSeconds(rotateSeconds ?? _rotateSeconds);
final pollChanged = nextPoll != _pollSeconds || _marketingPoll == null;
final rotateChanged = nextRotate != _rotateSeconds || _activityRotate == null;
_pollSeconds = nextPoll;
_rotateSeconds = nextRotate;
if (pollChanged) {
_marketingPoll?.cancel();
_marketingPoll = Timer.periodic(Duration(seconds: _pollSeconds), (_) {
if (!mounted) return;
_loadMarketing(force: false);
});
}
if (rotateChanged) {
_activityRotate?.cancel();
_activityRotate = Timer.periodic(Duration(seconds: _rotateSeconds), (_) {
if (!mounted || _activityPool.isEmpty) return;
setState(_rotateActivityVisible);
});
}
}
@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;
}
if (sl.isRegistered<MarketingRepository>()) {
final m = sl<MarketingRepository>();
final feed = m.peekLastActivityFeed();
if (feed != null && feed.items.isNotEmpty) {
_activityPool = feed.items;
_activePlayersCount = feed.activePlayersCount;
_pollSeconds = _clampPollSeconds(feed.clientRefreshSeconds);
_rotateSeconds = _clampRotateSeconds(feed.listRotateSeconds);
_rotateActivityVisible();
_activityLoading = false;
}
final withdrawals = m.peekLastWithdrawals();
if (withdrawals != null && withdrawals.isNotEmpty) {
_withdrawals = withdrawals;
_withdrawalsLoading = false;
}
}
_load();
_restartMarketingTimers();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_checkAppUpdate();
});
}
@override
void dispose() {
_marketingPoll?.cancel();
_activityRotate?.cancel();
super.dispose();
}
void _rotateActivityVisible() {
_activityGeneration++;
final next = rotateActivityWindow(
pool: _activityPool,
windowSize: _activityWindowSize,
generation: _activityGeneration,
recentlyShown: _recentlyShownIds,
);
_activityVisible = next;
_recentlyShownIds
..clear()
..addAll(next.map((e) => e.publicId));
}
Future<void> _checkAppUpdate() async {
final available = await checkAppUpdateAvailable();
if (!mounted) return;
setState(() => _updateAvailable = available);
}
Future<void> _loadAds({bool force = false}) {
if (_adsInFlight != null) return _adsInFlight!;
final keep = _heroAds.isNotEmpty && !force;
final future = () async {
if (!keep) {
setState(() {
_adsLoading = true;
_adsError = null;
});
}
try {
final ads = await sl<AdvertisementRepository>().list(
placement: 'home_hero',
force: force,
);
if (!mounted) return;
setState(() {
_heroAds = ads;
_adsLoading = false;
_adsError = null;
});
} catch (_) {
if (!mounted) return;
setState(() {
_adsLoading = false;
if (_heroAds.isEmpty) {
_adsError = AppException.connectionFailedMessage;
}
});
}
}();
_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 (_) {
if (!mounted) return;
setState(() {
_gamesLoading = false;
_gamesRetrying = false;
if (_games.isEmpty) {
_gamesError = AppException.connectionFailedMessage;
}
});
}
}();
_gamesInFlight = future.whenComplete(() => _gamesInFlight = null);
return _gamesInFlight!;
}
Future<void> _loadActivity({bool force = false}) {
if (!sl.isRegistered<MarketingRepository>()) {
setState(() {
_activityPool = const [];
_activePlayersCount = 0;
_activityVisible = const [];
_activityLoading = false;
_activityRetrying = false;
_activityError = null;
});
return Future.value();
}
if (_activityInFlight != null) return _activityInFlight!;
final keep = _activityPool.isNotEmpty && !force;
final future = () async {
setState(() {
if (!keep) _activityLoading = true;
if (force) {
_activityRetrying = true;
_activityError = null;
}
});
try {
final feed =
await sl<MarketingRepository>().getActivityFeed(force: force);
if (!mounted) return;
setState(() {
_activityPool = feed.items;
_activePlayersCount = feed.activePlayersCount;
_rotateActivityVisible();
_activityLoading = false;
_activityRetrying = false;
_activityError = null;
});
_restartMarketingTimers(
pollSeconds: feed.clientRefreshSeconds,
rotateSeconds: feed.listRotateSeconds,
);
} catch (_) {
if (!mounted) return;
// Keep last good pool if any; otherwise show section error (no invented fictives).
setState(() {
_activityLoading = false;
_activityRetrying = false;
if (_activityPool.isEmpty) {
_activityError = AppException.connectionFailedMessage;
}
});
}
}();
_activityInFlight = future.whenComplete(() => _activityInFlight = null);
return _activityInFlight!;
}
Future<void> _loadWithdrawals({bool force = false}) {
if (!sl.isRegistered<MarketingRepository>()) {
setState(() {
_withdrawals = const [];
_withdrawalsLoading = false;
_withdrawalsRetrying = false;
_withdrawalsError = null;
});
return Future.value();
}
if (_withdrawalsInFlight != null) return _withdrawalsInFlight!;
final keep = _withdrawals.isNotEmpty && !force;
final future = () async {
setState(() {
if (!keep) _withdrawalsLoading = true;
if (force) {
_withdrawalsRetrying = true;
_withdrawalsError = null;
}
});
try {
final items =
await sl<MarketingRepository>().getWithdrawalFeed(force: force);
if (!mounted) return;
setState(() {
_withdrawals = items;
_withdrawalsLoading = false;
_withdrawalsRetrying = false;
_withdrawalsError = null;
});
} catch (_) {
if (!mounted) return;
setState(() {
_withdrawalsLoading = false;
_withdrawalsRetrying = false;
if (_withdrawals.isEmpty) {
_withdrawalsError = AppException.connectionFailedMessage;
}
});
}
}();
_withdrawalsInFlight =
future.whenComplete(() => _withdrawalsInFlight = null);
return _withdrawalsInFlight!;
}
Future<void> _loadMarketing({bool force = false}) {
return Future.wait([
_loadActivity(force: force),
_loadWithdrawals(force: force),
]);
}
Future<void> _load({bool force = false}) async {
await Future.wait([
_loadAds(force: force),
_loadGames(force: force),
_loadMarketing(force: force),
]);
}
void _goLogin() => context.go('/login');
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final bottomInset = MediaQuery.paddingOf(context).bottom;
// Gradient fills under the status bar; SafeArea only insets AppBar content.
// OfflineBanner stays sticky below the chrome (outside the scroll view).
return AnnotatedRegion<SystemUiOverlayStyle>(
value: const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.light,
statusBarBrightness: Brightness.dark,
),
child: Scaffold(
key: const Key('welcome_screen'),
body: 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(),
IconButton(
key: const Key('welcome_app_update'),
tooltip: s.appUpdate,
onPressed: () => handleAppUpdateTap(
context,
updateAvailable: _updateAvailable,
),
icon: Badge(
isLabelVisible: _updateAvailable,
smallSize: 8,
backgroundColor: AppColors.warning,
child: const Icon(
Icons.system_update_alt_rounded,
color: Colors.white,
),
),
),
],
),
),
),
),
),
OfflineBanner(controller: sl<ConnectivityController>()),
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([
// Get Started hero — logo only in AppBar (no duplicate).
Container(
key: const Key('welcome_get_started_card'),
width: double.infinity,
padding: const EdgeInsets.fromLTRB(22, 24, 22, 22),
decoration: BoxDecoration(
gradient: AppColors.heroGradient(isDark),
borderRadius: BorderRadius.circular(22),
border: Border.all(
color: isDark
? AppColors.primary.withValues(alpha: 0.28)
: AppColors.primary.withValues(alpha: 0.22),
),
boxShadow: [
BoxShadow(
color: AppColors.primary.withValues(
alpha: isDark ? 0.16 : 0.10,
),
blurRadius: 28,
offset: const Offset(0, 12),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.tagline.toUpperCase(),
style: TextStyle(
color: isDark
? AppColors.accentGold
: AppColors.primaryDark,
fontSize: 11,
fontWeight: FontWeight.w800,
letterSpacing: 1.1,
),
),
const SizedBox(height: 14),
Text(
s.welcomeHeroTitle,
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(
fontWeight: FontWeight.w900,
height: 1.18,
letterSpacing: -0.3,
color: isDark
? AppColors.textPrimary
: const Color(0xFF0F172A),
),
),
const SizedBox(height: 12),
Text(
s.welcomeHeroSubtitle,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
height: 1.45,
color: isDark
? AppColors.textSecondary
: const Color(0xFF475569),
),
),
const SizedBox(height: 24),
PredPrimaryButton(
key: const Key('welcome_get_started'),
label: s.welcomeGetStarted,
icon: Icons.rocket_launch_rounded,
onPressed: _goLogin,
),
],
),
).animate().fadeIn(duration: 400.ms).slideY(begin: 0.04, end: 0),
if ((_adsLoading &&
_heroAds.isEmpty &&
_adsError == null) ||
_heroAds.isNotEmpty) ...[
const SizedBox(height: 18),
// Soft-fail ads: never a connection banner; hide when none published.
HomeAdCarousel(
ads: _heroAds,
loading: _adsLoading &&
_heroAds.isEmpty &&
_adsError == null,
onAdTap: (_) => _goLogin(),
),
const SizedBox(height: 22),
],
Text(
s.welcomeGamesTitle,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 4),
Text(
s.welcomeGamesSubtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textMuted,
),
),
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: _WelcomeGameCard(
game: g,
onTap: _goLogin,
),
),
)
else if (_gamesLoading) ...[
const PredSkeletonCard(height: 72),
const SizedBox(height: 10),
const PredSkeletonCard(height: 72),
] else
PredCard(
onTap: _goLogin,
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(predictionGamesNavIcon, color: AppColors.primary),
const SizedBox(width: 12),
Expanded(child: Text(s.predictionGamesSubtitle)),
Text(
s.welcomeOpen,
style: const TextStyle(
color: AppColors.primary,
fontWeight: FontWeight.w700,
fontSize: 12,
),
),
],
),
),
const SizedBox(height: 22),
WelcomeActivityTicker(
items: _activityVisible,
activePlayersCount: _activePlayersCount,
loading: _activityLoading,
listGeneration: _activityGeneration,
error: _activityError,
retrying: _activityRetrying,
onRetry: () => _loadActivity(force: true),
),
const SizedBox(height: 18),
WelcomeWithdrawalTicker(
items: _withdrawals,
loading: _withdrawalsLoading,
error: _withdrawalsError,
retrying: _withdrawalsRetrying,
onRetry: () => _loadWithdrawals(force: true),
),
const SizedBox(height: 22),
Text(
s.welcomeWhyTitle,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 12),
_BenefitTile(
icon: predictionGamesNavIcon,
color: AppColors.primary,
title: s.navPredict,
body: s.welcomeWhyPredict,
),
const SizedBox(height: 10),
_BenefitTile(
icon: Icons.account_balance_wallet_rounded,
color: AppColors.info,
title: s.navWallet,
body: s.welcomeWhyWallet,
),
const SizedBox(height: 10),
_BenefitTile(
icon: Icons.groups_rounded,
color: AppColors.accentGold,
title: s.referralTitle,
body: s.welcomeWhyReferral,
),
const SizedBox(height: 18),
PredCard(
key: const Key('welcome_faq_card'),
onTap: () => context.push('/faq'),
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(
Icons.help_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.welcomeFaqCta,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: AppColors.textSecondary,
),
),
],
),
),
const Icon(
Icons.chevron_right_rounded,
color: AppColors.textMuted,
),
],
),
),
const SizedBox(height: 28),
]),
),
),
],
),
),
),
],
),
),
);
}
}
class _BenefitTile extends StatelessWidget {
const _BenefitTile({
required this.icon,
required this.color,
required this.title,
required this.body,
});
final IconData icon;
final Color color;
final String title;
final String body;
@override
Widget build(BuildContext context) {
return PredCard(
padding: const EdgeInsets.all(14),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: color),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: const TextStyle(fontWeight: FontWeight.w800)),
const SizedBox(height: 4),
Text(
body,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textSecondary,
),
),
],
),
),
],
),
);
}
}
class _WelcomeGameCard extends StatelessWidget {
const _WelcomeGameCard({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);
return PredCard(
onTap: onTap,
padding: const EdgeInsets.all(14),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: accent.withValues(alpha: 0.18),
borderRadius: BorderRadius.circular(12),
),
child: Icon(predictionGamesNavIcon, color: accent),
),
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: 2),
Text(
game.description!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textMuted,
),
),
],
],
),
),
Text(
s.welcomeOpen,
style: TextStyle(
color: accent,
fontWeight: FontWeight.w700,
fontSize: 12,
),
),
],
),
);
}
}