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

1020 lines
36 KiB
Dart

import 'dart:async';
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 '../../../../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_skeleton.dart';
import '../../../../shared/widgets/section_error.dart';
import '../../../../shared/widgets/adaptive_space_between_row.dart';
import '../../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../../auth/bloc/auth_bloc.dart';
import '../../support/utils/support_ui_gate.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';
/// Whether a real background stay was observed (not sheet/IME overlays).
///
/// Android 12+ often emits `hidden` for bottom sheets — that must NOT count.
/// Resume sequences also pass through `inactive`, so callers should latch
/// [paused]/[detached] rather than inspecting only the previous state.
@visibleForTesting
bool predictionIsRealBackgroundLifecycle(AppLifecycleState state) {
return state == AppLifecycleState.paused ||
state == AppLifecycleState.detached;
}
/// True when a background stay was long enough to warrant a game-WS check.
@visibleForTesting
bool predictionBackgroundDwellAllowsReconnect(Duration? dwell) {
if (dwell == null) return false;
return dwell >= const Duration(milliseconds: 1200);
}
class PredictionScreen extends StatefulWidget {
const PredictionScreen({super.key});
@override
State<PredictionScreen> createState() => _PredictionScreenState();
}
class _PredictionScreenState extends State<PredictionScreen> with WidgetsBindingObserver {
late final PredictionBloc _bloc;
Timer? _uiClock;
/// Debounce forced `/state` while the local countdown is stuck at 0s.
int? _lastZeroResyncMs;
/// Latched when the app truly backgrounds (`paused` / `detached`).
/// Cleared on handled `resumed`. Sheet overlays often emit `hidden` /
/// `inactive` only — those must not trigger a game-socket reconnect.
bool _sawRealBackground = false;
DateTime? _backgroundedAt;
@override
void initState() {
super.initState();
_bloc = context.read<PredictionBloc>();
_bloc.add(const PredictionResumed());
// Phase-boundary resync only — countdown / bet-gate ticks live in
// RepaintBoundary children so the 1s clock does not rebuild chart/history.
_uiClock = Timer.periodic(const Duration(seconds: 1), (_) {
if (!mounted) return;
final round = _bloc.state.gameState?.round;
if (countdownStuckAtZero(round)) {
final now = DateTime.now().millisecondsSinceEpoch;
if (_lastZeroResyncMs == null || now - _lastZeroResyncMs! >= 2000) {
_lastZeroResyncMs = now;
_bloc.add(const PredictionRefreshTick(forceGameState: true));
}
} else {
_lastZeroResyncMs = null;
}
});
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_uiClock?.cancel();
_bloc.add(const PredictionPaused());
super.dispose();
}
/// Screen navigation (`initState`/`dispose`) is NOT the only way this page's
/// timers/socket can go stale — the OS backgrounding the whole app (screen
/// lock, app switcher, phone call) while the user stays on this route is
/// far more common, especially over "several minutes". Reconnect only after
/// a real background dwell — never for Support sheet / IME overlays.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (predictionIsRealBackgroundLifecycle(state)) {
_sawRealBackground = true;
_backgroundedAt ??= DateTime.now();
return;
}
if (state != AppLifecycleState.resumed) return;
final sawBackground = _sawRealBackground;
final bgAt = _backgroundedAt;
_sawRealBackground = false;
_backgroundedAt = null;
if (!sawBackground) return;
if (!predictionBackgroundDwellAllowsReconnect(
bgAt == null ? null : DateTime.now().difference(bgAt),
)) {
return;
}
// Support sheet can race lifecycle events; never tear the game WS down
// while chat is opening/open.
if (SupportUiGate.holdsGameRealtime) return;
_bloc.add(const PredictionAppResumed());
}
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) {
final gs = state.gameState;
final round = gs?.round;
final bootstrapping =
state.status == PredictionStatus.loading && gs == null;
final bootError =
state.status == PredictionStatus.error && gs == null;
final bottomInset = MediaQuery.paddingOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: KeyedSubtree(
key: const Key('prediction_screen'),
child: Column(
children: [
TlotoGradientAppBar(
title: s.predictTitle,
showBack: true,
onBack: () {
if (context.canPop()) {
context.pop();
} else {
context.go('/predict');
}
},
actions: [
Padding(
padding: const EdgeInsets.only(right: 10),
child: Center(
child: _LiveBadge(status: state.realtimeStatus),
),
),
],
),
Expanded(
child: RefreshIndicator(
onRefresh: () async {
context
.read<PredictionBloc>()
.add(const PredictionLoadRequested());
},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(
20,
12,
20,
24 + bottomInset + 72,
),
children: [
if (bootError) ...[
SectionError(
message: state.errorMessage ?? s.error,
onRetry: () => context
.read<PredictionBloc>()
.add(const PredictionLoadRequested()),
),
const SizedBox(height: 16),
],
if (!bootstrapping && !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: [
if (bootstrapping) ...[
const PredSkeletonLine(width: 120, height: 14),
const SizedBox(height: 8),
const Align(
alignment: Alignment.centerRight,
child: PredSkeletonLine(width: 64, height: 28),
),
const SizedBox(height: 16),
PredSkeleton(
width: double.infinity,
height: CandleChartWidget.chartHeight,
borderRadius: 12,
),
] else ...[
RepaintBoundary(
child: _RoundPhaseHeader(
round: round,
openLabel: s.timeLeft,
waitLabel: s.waitingRound,
),
),
const SizedBox(height: 16),
if (state.candlesError != null && state.candles.isEmpty)
SectionError(
message: state.candlesError!,
retrying: state.isLoadingOlderCandles,
onRetry: () => context
.read<PredictionBloc>()
.add(const PredictionCandlesReloadRequested()),
)
else
RepaintBoundary(
child: CandleChartWidget(
candles: state.candles,
isLoadingOlder: state.isLoadingOlderCandles,
hasMoreOlder: state.hasMoreOlderCandles,
instrument: gs?.config.instrument ??
defaultCandlePredictInstrument,
onRefresh: () => context
.read<PredictionBloc>()
.add(const PredictionCandlesReloadRequested()),
),
),
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)
BlocSelector<PredictionBloc, PredictionState, int>(
selector: (s) => s.selectedIntervalMinutes,
builder: (context, selectedMinutes) {
return AdaptiveSpaceBetweenRow(
height: 42,
children: [
for (final item in gs.intervals.where((i) => i.isActive))
ChoiceChip(
label: Text(item.label),
selected: item.intervalMinutes == selectedMinutes,
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),
],
if (bootstrapping)
const PredSkeletonCard(height: 220)
else
RepaintBoundary(child: _TickingBetPanel(state: state)),
const SizedBox(height: 20),
Text(s.recentPredictions, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 10),
if (!bootstrapping)
BlocSelector<PredictionBloc, PredictionState, (String?, String?)>(
selector: (s) => (s.historyWalletFilter, s.historyStatusFilter),
builder: (context, filters) {
final (walletFilter, statusFilter) = filters;
return _HistoryFilterBar(
walletFilter: walletFilter,
statusFilter: statusFilter,
onAll: () => _setHistoryFilters(),
onWallet: (kind) => _setHistoryFilters(
wallet: walletFilter == kind ? null : kind,
status: statusFilter,
),
onStatus: (status) => _setHistoryFilters(
wallet: walletFilter,
status: statusFilter == status ? null : status,
),
);
},
),
const SizedBox(height: 12),
if (bootstrapping ||
(state.isLoadingHistory && state.history.isEmpty)) ...[
const PredSkeletonCard(height: 72),
const SizedBox(height: 8),
const PredSkeletonCard(height: 72),
const SizedBox(height: 8),
const PredSkeletonCard(height: 72),
] else if (state.historyError != null && state.history.isEmpty) ...[
SectionError(
message: state.historyError!,
retrying: state.isLoadingHistory,
onRetry: () => context
.read<PredictionBloc>()
.add(const PredictionHistoryPageRequested(1)),
),
] else
Builder(
builder: (context) {
final filtered = state.history;
final canLoadMore = state.historyPage < state.historyTotalPages;
final hasFilters = state.historyWalletFilter != null ||
state.historyStatusFilter != null;
final showEndLabel = !canLoadMore &&
state.historyTotalPages > 1 &&
filtered.isNotEmpty;
final showLoadMore = canLoadMore;
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 PredSkeletonLine(
width: 120,
height: 18,
),
],
],
),
)
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 PredSkeletonLine(width: 80, height: 18)
: 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,
),
),
],
],
);
},
),
],
),
),
),
],
),
),
);
},
);
}
}
/// Local 1s rebuild so [PredictionState.isBettingWindowOpen] updates without
/// repainting chart / history.
class _TickingBetPanel extends StatefulWidget {
const _TickingBetPanel({required this.state});
final PredictionState state;
@override
State<_TickingBetPanel> createState() => _TickingBetPanelState();
}
class _TickingBetPanelState extends State<_TickingBetPanel> {
Timer? _tick;
@override
void initState() {
super.initState();
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
_tick?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return PredictionBetPanel(state: widget.state);
}
}
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.walletMain,
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),
),
);
}
}
/// Chip + seconds from the same snapshot, same formula as web
/// `useServerAdjustedCountdown`. Owns a 1s ticker so only this header
/// (and the bet panel) rebuild — not the chart or history list.
class _RoundPhaseHeader extends StatefulWidget {
const _RoundPhaseHeader({
required this.round,
required this.openLabel,
required this.waitLabel,
});
final RoundModel? round;
final String openLabel;
final String waitLabel;
@override
State<_RoundPhaseHeader> createState() => _RoundPhaseHeaderState();
}
class _RoundPhaseHeaderState extends State<_RoundPhaseHeader> {
Timer? _tick;
@override
void initState() {
super.initState();
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
_tick?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final current = widget.round;
if (current == null) {
return const Row(
children: [
_StatusChip('waiting'),
Spacer(),
],
);
}
final adjusted = serverAdjustedCountdown(current);
final isOpen = adjusted.bettingOpen;
final seconds =
isOpen ? adjusted.secondsToBettingEnd : adjusted.secondsToBettingStart;
return Row(
children: [
_StatusChip(adjusted.effectiveStatus),
const Spacer(),
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);
}
final lower = raw.toLowerCase();
if (lower.contains('readonly') || lower.contains('read only replica')) {
return s.predictionDbReadonly;
}
return raw;
}