games_app/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart

845 lines
30 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../data/models/prediction_models.dart';
import '../../../../data/models/candle_predict_instrument.dart';
import '../../../../l10n/app_strings.dart';
import '../../../../shared/widgets/pred_card.dart';
import '../../../../shared/widgets/pred_text_field.dart';
import '../../../../shared/widgets/adaptive_space_between_row.dart';
import '../../auth/bloc/auth_bloc.dart';
import '../bloc/prediction_bloc.dart';
import '../utils/server_adjusted_countdown.dart';
import 'widgets/candle_chart_widget.dart';
import 'widgets/multi_sequence_progress.dart';
import 'widgets/prediction_bet_panel.dart';
import '../../share_cards/presentation/share_result_widgets.dart';
class PredictionScreen extends StatefulWidget {
const PredictionScreen({super.key});
@override
State<PredictionScreen> createState() => _PredictionScreenState();
}
class _PredictionScreenState extends State<PredictionScreen> {
late final PredictionBloc _bloc;
Timer? _uiClock;
@override
void initState() {
super.initState();
_bloc = context.read<PredictionBloc>();
_bloc.add(const PredictionResumed());
// Rebuild bet gating as the open window expires (canBet uses DateTime.now).
_uiClock = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
_uiClock?.cancel();
_bloc.add(const PredictionPaused());
super.dispose();
}
void _setHistoryFilters({String? wallet, String? status}) {
_bloc.add(PredictionHistoryFilterChanged(
walletFilter: wallet,
statusFilter: status,
));
}
@override
Widget build(BuildContext context) {
final s = context.strings;
return BlocConsumer<PredictionBloc, PredictionState>(
listenWhen: (p, c) =>
(c.errorMessage != null && c.errorMessage != p.errorMessage) ||
(c.betPlaced && !p.betPlaced),
listener: (context, state) {
if (state.errorMessage != null) {
final raw = state.errorMessage!.replaceFirst('Exception: ', '');
final message = _formatPredictionError(s, raw);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(
message,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
),
backgroundColor: AppColors.danger,
behavior: SnackBarBehavior.floating,
),
);
context.read<PredictionBloc>().add(const PredictionFeedbackConsumed());
}
if (state.betPlaced) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(
s.predictionPlaced,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
),
backgroundColor: AppColors.success,
behavior: SnackBarBehavior.floating,
),
);
context.read<PredictionBloc>().add(const PredictionFeedbackConsumed());
}
},
builder: (context, state) {
if (state.status == PredictionStatus.loading && state.gameState == null) {
return PredLoadingView(message: s.loading);
}
if (state.status == PredictionStatus.error && state.gameState == null) {
return PredErrorView(
message: state.errorMessage ?? s.error,
onRetry: () => context.read<PredictionBloc>().add(const PredictionLoadRequested()),
);
}
final gs = state.gameState;
final round = gs?.round;
return KeyedSubtree(
key: const Key('prediction_screen'),
child: RefreshIndicator(
onRefresh: () async {
context.read<PredictionBloc>().add(const PredictionLoadRequested());
},
child: ListView(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 100),
children: [
Row(
children: [
Expanded(
child: Text(s.predictTitle, style: Theme.of(context).textTheme.headlineMedium),
),
_LiveBadge(status: state.realtimeStatus),
],
).animate().fadeIn(duration: 300.ms),
const SizedBox(height: 4),
Text(s.tagline, style: Theme.of(context).textTheme.bodySmall),
const SizedBox(height: 20),
if (!state.isRealtimeHealthy) ...[
PredCard(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(top: 2),
child: Icon(Icons.wifi_tethering_error_rounded, color: AppColors.warning),
),
const SizedBox(width: 10),
Expanded(
child: Text(
s.realtimeRecoveryHint,
style: Theme.of(context).textTheme.bodySmall,
),
),
],
),
),
const SizedBox(height: 12),
],
PredCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
// Web parity: `round.status` is already the authoritative,
// baked-in effective status (see `mergeRound` /
// `_withEffectiveStatus`). Re-deriving it here from a second,
// independent `DateTime.now()` clock (out of sync with
// `_LiveCountdown`'s own ticking clock below) is exactly what
// caused the badge and the big countdown number to briefly
// disagree. Trust the single source of truth instead.
_StatusChip(round?.status ?? 'waiting'),
const Spacer(),
if (round != null)
_LiveCountdown(
key: ValueKey(
'${state.selectedIntervalMinutes}-${round.id}',
),
round: round,
openLabel: s.timeLeft,
waitLabel: s.waitingRound,
),
],
),
const SizedBox(height: 16),
CandleChartWidget(
candles: state.candles,
isLoadingOlder: state.isLoadingOlderCandles,
hasMoreOlder: state.hasMoreOlderCandles,
instrument: gs?.config.instrument ?? defaultCandlePredictInstrument,
),
if (context.watch<AuthBloc>().state.isAdmin &&
round != null &&
round.longPoolPercent != null &&
round.shortPoolPercent != null) ...[
const SizedBox(height: 16),
PoolBarWidget(
longPercent: round.longPoolPercent!,
shortPercent: round.shortPoolPercent!,
),
],
],
),
),
const SizedBox(height: 16),
if (gs != null && gs.intervals.isNotEmpty)
AdaptiveSpaceBetweenRow(
height: 42,
children: [
for (final item in gs.intervals.where((i) => i.isActive))
ChoiceChip(
label: Text(item.label),
selected: item.intervalMinutes == state.selectedIntervalMinutes,
onSelected: (_) => context.read<PredictionBloc>().add(
PredictionIntervalChanged(item.intervalMinutes),
),
),
],
),
const SizedBox(height: 16),
if (gs?.autoSettings?.enabled == true) ...[
_AutoActiveBanner(
settings: gs!.autoSettings!,
currentInterval: gs.selectedIntervalMinutes,
onOpenAuto: () => context.read<PredictionBloc>().add(
const PredictionPlayModeChanged(PredictionPlayMode.auto),
),
),
const SizedBox(height: 12),
],
PredictionBetPanel(state: state),
const SizedBox(height: 20),
Text(s.recentPredictions, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 10),
_HistoryFilterBar(
walletFilter: state.historyWalletFilter,
statusFilter: state.historyStatusFilter,
onAll: () => _setHistoryFilters(),
onWallet: (kind) => _setHistoryFilters(
wallet: state.historyWalletFilter == kind ? null : kind,
status: state.historyStatusFilter,
),
onStatus: (status) => _setHistoryFilters(
wallet: state.historyWalletFilter,
status: state.historyStatusFilter == status ? null : status,
),
),
const SizedBox(height: 12),
Builder(
builder: (context) {
final filtered = state.history.where((p) {
if (state.historyWalletFilter != null &&
p.stakeAccountKind != state.historyWalletFilter) {
return false;
}
if (state.historyStatusFilter != null &&
p.status != state.historyStatusFilter) {
return false;
}
return true;
}).toList();
final canLoadMore = state.historyPage < state.historyTotalPages;
final hasFilters = state.historyWalletFilter != null ||
state.historyStatusFilter != null;
// End label only after a multi-page history was fully loaded.
final showEndLabel = !canLoadMore &&
state.historyTotalPages > 1 &&
filtered.isNotEmpty;
// While a filter has no matches, auto-load hides the manual button.
final showLoadMore = canLoadMore &&
!(hasFilters && filtered.isEmpty);
if (state.isLoadingHistory && state.history.isEmpty) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 24),
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
);
}
if (state.history.isEmpty) {
return PredCard(
child: Text(
s.noPredictionsYet,
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (filtered.isEmpty)
PredCard(
child: Column(
children: [
Text(
hasFilters ? s.noFilteredPredictions : s.noPredictionsYet,
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
if (hasFilters && canLoadMore && state.isLoadingHistory) ...[
const SizedBox(height: 12),
const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
],
],
),
)
else
...filtered.map(
(p) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: _PredictionHistoryCard(prediction: p),
),
),
if (showLoadMore) ...[
const SizedBox(height: 4),
TextButton(
onPressed: state.isLoadingHistory
? null
: () => context.read<PredictionBloc>().add(
PredictionHistoryPageRequested(
state.historyPage + 1,
append: true,
),
),
child: state.isLoadingHistory
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(s.loadMore),
),
] else if (showEndLabel) ...[
const SizedBox(height: 8),
Text(
s.historyEndReached,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textMuted,
fontWeight: FontWeight.w600,
),
),
],
],
);
},
),
],
),
),
);
},
);
}
}
class _HistoryFilterBar extends StatelessWidget {
const _HistoryFilterBar({
required this.walletFilter,
required this.statusFilter,
required this.onAll,
required this.onWallet,
required this.onStatus,
});
final String? walletFilter;
final String? statusFilter;
final VoidCallback onAll;
final ValueChanged<String> onWallet;
final ValueChanged<String> onStatus;
@override
Widget build(BuildContext context) {
final s = context.strings;
final allSelected = walletFilter == null && statusFilter == null;
final chips = <Widget>[
_HistoryFilterChip(
label: s.filterAll,
selected: allSelected,
color: AppColors.primary,
onTap: onAll,
),
_HistoryFilterChip(
label: s.walletMain,
selected: walletFilter == 'main',
color: AppColors.textMuted,
onTap: () => onWallet('main'),
),
_HistoryFilterChip(
label: s.walletBonus,
selected: walletFilter == 'bonus',
color: AppColors.warning,
onTap: () => onWallet('bonus'),
),
_HistoryFilterChip(
label: s.walletTest,
selected: walletFilter == 'test',
color: AppColors.info,
onTap: () => onWallet('test'),
),
_HistoryFilterChip(
label: s.predictionStatus('won'),
selected: statusFilter == 'won',
color: AppColors.candleGreen,
onTap: () => onStatus('won'),
),
_HistoryFilterChip(
label: s.predictionStatus('lost'),
selected: statusFilter == 'lost',
color: AppColors.candleRed,
onTap: () => onStatus('lost'),
),
];
return AdaptiveSpaceBetweenRow(
height: 36,
children: chips,
);
}
}
class _HistoryFilterChip extends StatelessWidget {
const _HistoryFilterChip({
required this.label,
required this.selected,
required this.color,
required this.onTap,
});
final String label;
final bool selected;
final Color color;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: selected ? color.withValues(alpha: 0.22) : AppColors.surfaceElevated,
borderRadius: BorderRadius.circular(20),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: selected ? color.withValues(alpha: 0.7) : AppColors.border,
),
),
child: Text(
label,
style: TextStyle(
color: selected ? color : AppColors.textSecondary,
fontWeight: FontWeight.w700,
fontSize: 12,
),
),
),
),
);
}
}
class _AutoActiveBanner extends StatelessWidget {
const _AutoActiveBanner({
required this.settings,
required this.currentInterval,
required this.onOpenAuto,
});
final AutoSettingsModel settings;
final int currentInterval;
final VoidCallback onOpenAuto;
@override
Widget build(BuildContext context) {
final s = context.strings;
final dir = settings.direction == 'short' ? s.short : s.long;
final sameInterval = settings.periodMinutes == currentInterval;
return Material(
color: AppColors.info.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
child: InkWell(
onTap: onOpenAuto,
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(14),
child: Row(
children: [
const Icon(Icons.autorenew_rounded, color: AppColors.info),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(s.autoActiveTitle, style: const TextStyle(fontWeight: FontWeight.w800)),
Text(
s.autoActiveDetail(
direction: dir,
stake: '${settings.stakeDisplay}',
wallet: switch (settings.stakeAccountKind) {
'bonus' => s.walletBonus,
'test' => s.walletTest,
_ => s.walletMain,
},
mode: settings.mode == 'interval' ? s.autoModeInterval : s.autoModeEachRound,
interval: '${settings.periodMinutes}m',
),
style: Theme.of(context).textTheme.bodySmall,
),
if (!sameInterval)
Text(
'${s.interval}: ${settings.periodMinutes}m',
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: AppColors.warning),
),
],
),
),
const Icon(Icons.chevron_right),
],
),
),
),
);
}
}
class _PredictionHistoryCard extends StatelessWidget {
const _PredictionHistoryCard({required this.prediction});
final PredictionModel prediction;
@override
Widget build(BuildContext context) {
final s = context.strings;
final p = prediction;
final isLong = p.direction == 'long';
final dirColor = isLong ? AppColors.candleGreen : AppColors.candleRed;
final placedAt = _formatPlacedAt(p.createdAt);
return PredCard(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
isLong ? Icons.trending_up : Icons.trending_down,
color: dirColor,
),
const SizedBox(width: 10),
Expanded(
child: Text(
p.isMulti
? '${s.modeMulti} L${p.level ?? p.sequenceDirections.length} · ${p.stakeDisplay}'
: '${isLong ? s.long : s.short} · ${p.stakeDisplay}',
style: const TextStyle(fontWeight: FontWeight.w700),
),
),
Text(
p.payoutDisplay > 0 ? '+${p.payoutDisplay}' : '',
style: const TextStyle(color: AppColors.success, fontWeight: FontWeight.w700),
),
ShareResultIconButton(
betId: p.id,
status: p.status,
stakeAccountKind: p.stakeAccountKind,
),
],
),
const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_ModeChip(
label: p.isMulti
? s.modeMultiLevel(p.level ?? p.sequenceDirections.length)
: s.modeSingle,
color: p.isMulti ? AppColors.info : AppColors.textMuted,
),
_ModeChip(
label: _walletLabel(s, p.stakeAccountKind),
color: _walletColor(p.stakeAccountKind),
),
if (p.isAuto) _ModeChip(label: s.modeAuto, color: AppColors.warning),
_ModeChip(
label: s.predictionStatus(p.status),
color: _statusColor(p.status),
),
if (placedAt != null)
Text(
placedAt,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textMuted,
fontWeight: FontWeight.w600,
),
),
],
),
if (p.isMulti && p.sequenceDirections.isNotEmpty) ...[
const SizedBox(height: 10),
MultiSequenceProgress(
directions: p.sequenceDirections,
step: p.sequenceStep,
status: p.status,
),
const SizedBox(height: 6),
Text(
s.multiProgressLabel(
current: (p.sequenceStep + 1).clamp(1, p.sequenceDirections.length),
total: p.sequenceDirections.length,
status: p.status,
),
style: Theme.of(context).textTheme.bodySmall,
),
],
],
),
);
}
String? _formatPlacedAt(String iso) {
if (iso.isEmpty) return null;
final dt = DateTime.tryParse(iso)?.toLocal();
if (dt == null) return null;
final d = dt.day.toString().padLeft(2, '0');
final m = dt.month.toString().padLeft(2, '0');
final h = dt.hour.toString().padLeft(2, '0');
final min = dt.minute.toString().padLeft(2, '0');
return '$d/$m/${dt.year} $h:$min';
}
String _walletLabel(AppStrings s, String kind) {
switch (kind) {
case 'bonus':
return s.walletBonus;
case 'test':
return s.walletTest;
default:
return s.walletMain;
}
}
Color _walletColor(String kind) {
switch (kind) {
case 'bonus':
return AppColors.warning;
case 'test':
return AppColors.info;
default:
return AppColors.textMuted;
}
}
Color _statusColor(String status) {
switch (status) {
case 'won':
return AppColors.candleGreen;
case 'lost':
return AppColors.candleRed;
case 'in_progress':
return AppColors.info;
case 'refunded':
return AppColors.warning;
default:
return AppColors.textMuted;
}
}
}
class _ModeChip extends StatelessWidget {
const _ModeChip({required this.label, required this.color});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withValues(alpha: 0.35)),
),
child: Text(
label,
style: TextStyle(color: color, fontWeight: FontWeight.w700, fontSize: 11),
),
);
}
}
class _LiveBadge extends StatelessWidget {
const _LiveBadge({required this.status});
final PredictionRealtimeStatus status;
@override
Widget build(BuildContext context) {
final s = context.strings;
final (label, color) = switch (status) {
PredictionRealtimeStatus.live => (s.liveConnected, AppColors.success),
PredictionRealtimeStatus.syncing => (s.liveSyncing, AppColors.info),
PredictionRealtimeStatus.reconnecting => (s.liveReconnecting, AppColors.warning),
PredictionRealtimeStatus.polling => (s.livePolling, AppColors.warning),
};
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: color.withValues(alpha: 0.4)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.circle, size: 8, color: color),
const SizedBox(width: 6),
Text(
label,
style: TextStyle(color: color, fontWeight: FontWeight.w700, fontSize: 11),
),
],
),
);
}
}
class _StatusChip extends StatelessWidget {
const _StatusChip(this.status);
final String status;
@override
Widget build(BuildContext context) {
final s = context.strings;
Color color;
switch (status) {
case 'betting':
color = AppColors.primary;
case 'locked':
color = AppColors.warning;
case 'settled':
color = AppColors.textMuted;
default:
color = AppColors.info;
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: color.withValues(alpha: 0.4)),
),
child: Text(
s.roundStatusLabel(status),
style: TextStyle(color: color, fontWeight: FontWeight.w700, fontSize: 11),
),
);
}
}
/// Smooth local countdown using serverNowMs skew (web parity).
///
/// Always derives from the LATEST [widget.round] (already de-duplicated and
/// made monotonic upstream by [mergeRound] / [roundUiChanged] in the bloc) plus
/// a locally ticking clock — exactly like the web `useServerAdjustedCountdown`
/// hook. Deliberately does **not** keep a separate frozen "anchor" snapshot:
/// an earlier version did, and because that anchor was reset independently
/// from the bloc's own change-detection, the two layers could disagree and
/// produce the "55 → 0 → 52 → 0 → 49 → 0" jump bug. A single source of truth
/// (the round passed down) avoids that entirely.
class _LiveCountdown extends StatefulWidget {
const _LiveCountdown({
super.key,
required this.round,
required this.openLabel,
required this.waitLabel,
});
final RoundModel round;
final String openLabel;
final String waitLabel;
@override
State<_LiveCountdown> createState() => _LiveCountdownState();
}
class _LiveCountdownState extends State<_LiveCountdown> {
Timer? _timer;
int _nowMs = DateTime.now().millisecondsSinceEpoch;
@override
void initState() {
super.initState();
_timer = Timer.periodic(const Duration(milliseconds: 200), (_) {
if (!mounted) return;
setState(() => _nowMs = DateTime.now().millisecondsSinceEpoch);
});
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final adjusted = serverAdjustedCountdown(widget.round, clientNowMs: _nowMs);
final isOpen = adjusted.bettingOpen;
final seconds =
isOpen ? adjusted.secondsToBettingEnd : adjusted.secondsToBettingStart;
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
isOpen ? widget.openLabel : widget.waitLabel,
style: Theme.of(context).textTheme.bodySmall,
),
Text(
'${seconds}s',
style: Theme.of(context).textTheme.titleLarge?.copyWith(color: AppColors.primary),
),
],
);
}
}
String _formatPredictionError(AppStrings s, String raw) {
const prefix = PredictionBloc.insufficientBalanceCode;
if (raw == prefix || raw.startsWith('$prefix:')) {
final kind = raw.contains(':') ? raw.split(':').last : 'main';
final wallet = switch (kind) {
'bonus' => s.walletBonus,
'test' => s.walletTest,
_ => s.walletMain,
};
return s.insufficientBalanceOn(wallet);
}
return raw;
}