import 'dart:async'; import 'dart:math' as math; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../core/errors/app_exception.dart'; import '../../../core/realtime/game_socket_service.dart'; import '../../../core/utils/amount_utils.dart'; import '../../../data/models/prediction_models.dart'; import '../../../data/repositories/prediction_repository_impl.dart'; import '../../../data/repositories/wallet_repository_impl.dart'; import '../../../domain/repositories/prediction_repository.dart'; import '../../support/utils/support_ui_gate.dart'; import '../utils/candle_interval_cache.dart'; import '../utils/prediction_history_filter_store.dart'; import '../utils/server_adjusted_countdown.dart'; part 'prediction_event.dart'; part 'prediction_state.dart'; /// `Bloc` processes events **concurrently** by default. `PredictionRefreshTick` /// does an `await`ed HTTP round-trip, so a slow response can resolve *after* a /// later tick already started/finished — an old, in-flight refresh clobbering /// state a newer one already updated. Sequential processing (à la /// `bloc_concurrency`'s `sequential()`, implemented inline to avoid the extra /// dependency) guarantees ticks are fully handled one at a time, in order. EventTransformer _sequential() { return (events, mapper) => events.asyncExpand(mapper); } class PredictionBloc extends Bloc { PredictionBloc(this._repo, this._socket, this._walletRepo) : super(const PredictionState.initial()) { on(_onLoad, transformer: _sequential()); on(_onIntervalChanged); on(_onStakeSelected); on(_onDirectionSelected); on(_onStakeAccountChanged); on(_onPlayModeChanged); on(_onMultiLevelSelected); on(_onMultiDirectionToggled); on(_onPlaceBet); on(_onPlaceMultiBet); on(_onAutoSave); on(_onRefreshTick, transformer: _sequential()); on(_onWsMessage); on(_onSocketStatusChanged); on(_onHistoryPage, transformer: _sequential()); on(_onHistoryFilterChanged); on(_onOlderCandles); on(_onCandlesReload, transformer: _sequential()); on(_onPaused); on(_onResumed); on(_onAppResumed, transformer: _sequential()); on(_onBalancesRefresh); on((event, emit) { emit(state.copyWith(clearError: true, betPlaced: false)); }); _socket.addListener(_handleSocketMessage); _socket.addStatusListener(_handleSocketStatus); } final PredictionRepository _repo; final GameSocketService _socket; final WalletRepositoryImpl _walletRepo; Timer? _pollTimer; bool _screenActive = false; int _multiPollTicks = 0; int _healthyPollSkips = 0; int _lastFullStateSyncMs = 0; static const historyPageSize = 5; static const _pollJitterRatio = 0.12; final historyFilterStore = PredictionHistoryFilterStore(); final candleIntervalCache = CandleIntervalCache(); String _historyKey({ int? intervalMinutes, required String? wallet, required String? status, }) => PredictionHistoryFilterStore.key( intervalMinutes: intervalMinutes ?? state.selectedIntervalMinutes, wallet: wallet, status: status, ); bool _isCurrentHistoryContext({ required int intervalMinutes, String? wallet, String? status, }) => state.selectedIntervalMinutes == intervalMinutes && state.historyWalletFilter == wallet && state.historyStatusFilter == status; void _rememberHistory( List items, { required int page, required int totalPages, int? intervalMinutes, String? wallet, String? status, }) { historyFilterStore.put( _historyKey( intervalMinutes: intervalMinutes, wallet: wallet ?? state.historyWalletFilter, status: status ?? state.historyStatusFilter, ), PredictionHistoryFilterPage( items: items, page: page, totalPages: totalPages, ), ); } int _chartPageSizeForMinutes(int intervalMinutes) { IntervalModel? meta; for (final i in state.gameState?.intervals ?? const []) { if (i.intervalMinutes == intervalMinutes) { meta = i; break; } } final limit = meta?.chartCandleLimit ?? state.gameState?.interval.chartCandleLimit ?? 80; return limit.clamp(20, 200); } void _rememberCandles( int intervalMinutes, List items, bool hasMore, ) { if (items.isEmpty) return; candleIntervalCache.put( intervalMinutes, CandleIntervalPage(items: items, hasMore: hasMore), ); } List _applyLiveHistoryOverlays(List items) { final liveMulti = state.gameState?.userMultiBet; final liveBet = state.gameState?.userBet; var next = items; if (liveMulti != null) { next = _historyWithMultiProgress(next, liveMulti); } if (liveBet != null) { next = _historyWithPrediction(next, liveBet); } return next; } Future _fetchHistoryPage( int page, { int? intervalMinutes, String? wallet, String? status, }) { return _repo.getMyBets( page: page, pageSize: historyPageSize, intervalMinutes: intervalMinutes ?? state.selectedIntervalMinutes, stakeAccountKind: wallet ?? state.historyWalletFilter, status: status ?? state.historyStatusFilter, ); } Future _refreshHistoryFromServer( Emitter emit, { int page = 1, bool append = false, bool showSpinnerIfEmpty = true, }) async { final interval = state.selectedIntervalMinutes; final wallet = state.historyWalletFilter; final status = state.historyStatusFilter; if (append || (showSpinnerIfEmpty && state.history.isEmpty)) { emit(state.copyWith(isLoadingHistory: true, clearHistoryError: true)); } else { emit(state.copyWith(clearHistoryError: true)); } try { final result = await _fetchHistoryPage( page, intervalMinutes: interval, wallet: wallet, status: status, ); if (!_isCurrentHistoryContext( intervalMinutes: interval, wallet: wallet, status: status, )) { return; } final merged = append ? [ ...state.history, ...result.items.where((item) => state.history.every((h) => h.id != item.id)), ] : result.items; final items = append ? merged : _applyLiveHistoryOverlays(merged); final reachedEnd = append && result.items.isEmpty; final nextPage = reachedEnd ? state.historyPage : result.page; final nextTotal = reachedEnd ? state.historyTotalPages : result.totalPages; _rememberHistory( items, page: nextPage, totalPages: nextTotal, intervalMinutes: interval, wallet: wallet, status: status, ); emit(state.copyWith( history: items, historyPage: nextPage, historyTotalPages: nextTotal, isLoadingHistory: false, clearHistoryError: true, )); } catch (e) { if (_isCurrentHistoryContext( intervalMinutes: interval, wallet: wallet, status: status, )) { emit(state.copyWith( isLoadingHistory: false, historyError: e.toString().replaceFirst('Exception: ', ''), )); } } } bool _matchesHistoryFilters(PredictionModel p) { if (state.historyWalletFilter != null && p.stakeAccountKind != state.historyWalletFilter) { return false; } if (state.historyStatusFilter != null && p.status != state.historyStatusFilter) { return false; } return true; } void _handleSocketMessage(Map msg) { if (!_screenActive) return; add(PredictionWsMessageReceived(msg)); } void _handleSocketStatus(GameSocketConnectionState status) { if (!_screenActive) return; add(PredictionSocketStatusChanged(status)); } @override Future close() { _pollTimer?.cancel(); _socket.removeListener(_handleSocketMessage); _socket.removeStatusListener(_handleSocketStatus); return super.close(); } void _stopPolling() { _pollTimer?.cancel(); _pollTimer = null; } void _startPolling() { _stopPolling(); if (!_screenActive) return; final hasActiveMulti = state.gameState?.userMultiBet != null; final autoOn = state.gameState?.autoSettings?.enabled == true; // Auto bets are placed server-side without always relying on WS; poll often enough // to surface pending predictions in Recent predictions quickly. final Duration interval; if (autoOn || hasActiveMulti) { interval = const Duration(seconds: 3); } else if (_socket.isEnabled && state.isRealtimeHealthy) { interval = const Duration(seconds: 8); } else if (_socket.isEnabled) { interval = const Duration(seconds: 4); } else { interval = const Duration(seconds: 2); } void scheduleNext() { if (!_screenActive) return; final baseMs = interval.inMilliseconds; final jitterMs = (baseMs * _pollJitterRatio).round(); final offset = jitterMs <= 0 ? 0 : math.Random().nextInt(jitterMs * 2 + 1) - jitterMs; final nextMs = math.max(1000, baseMs + offset); _pollTimer = Timer(Duration(milliseconds: nextMs), () { if (!_screenActive) return; add(const PredictionRefreshTick()); scheduleNext(); }); } scheduleNext(); } void _onPaused(PredictionPaused event, Emitter emit) { _screenActive = false; SupportUiGate.predictionScreenActive = false; _stopPolling(); _healthyPollSkips = 0; } void _onSocketStatusChanged( PredictionSocketStatusChanged event, Emitter emit, ) { // Support sheet open: ignore transient game-WS drops so the Live badge // does not flash "Reconnecting…" over a healthy Predict session. if (SupportUiGate.holdsGameRealtime && event.status != GameSocketConnectionState.connected && state.isRealtimeHealthy) { return; } final nextRealtime = switch (event.status) { GameSocketConnectionState.connected => PredictionRealtimeStatus.live, GameSocketConnectionState.connecting => PredictionRealtimeStatus.syncing, GameSocketConnectionState.reconnecting => PredictionRealtimeStatus.reconnecting, GameSocketConnectionState.stale => PredictionRealtimeStatus.reconnecting, GameSocketConnectionState.disconnected => PredictionRealtimeStatus.polling, }; final wasHealthy = state.isRealtimeHealthy; emit(state.copyWith( wsConnected: event.status == GameSocketConnectionState.connected, realtimeStatus: nextRealtime, )); _startPolling(); if (event.status != GameSocketConnectionState.connected) { _healthyPollSkips = 0; } if (!wasHealthy && event.status == GameSocketConnectionState.connected) { add(const PredictionRefreshTick(forceGameState: true)); add(const PredictionBalancesRefreshRequested()); add(const PredictionHistoryPageRequested(1)); // Missed candle.append frames leave price cliffs until a full reload; // replace the local series from HTTP after every reconnect. add(const PredictionCandlesReloadRequested()); } } Future _onResumed(PredictionResumed event, Emitter emit) async { _screenActive = true; SupportUiGate.predictionScreenActive = true; add(const PredictionLoadRequested(ifStale: true)); } /// Live badge status — holds "live" while Support is open on this screen. PredictionRealtimeStatus _realtimeStatus({ required PredictionRealtimeStatus whenDisconnected, }) { if (SupportUiGate.holdsGameRealtime && state.realtimeStatus == PredictionRealtimeStatus.live) { return PredictionRealtimeStatus.live; } if (_socket.isConnected) return PredictionRealtimeStatus.live; return whenDisconnected; } static const _freshSyncMs = 5000; void _ensureRealtime([int? intervalMinutes]) { if (!_socket.isEnabled) return; unawaited(_socket.connect()); _socket.subscribe(intervalMinutes ?? state.selectedIntervalMinutes); } Future _soft(Future future) async { try { return await future; } catch (_) { return null; } } /// True root fix for "countdown stuck until I leave and reopen the page": /// mobile OSes suspend Dart `Timer`s and can silently drop the WebSocket /// while backgrounded (screen lock, app switcher, incoming call, long time /// on the page with the screen off) — none of which fires `onDone`, so /// [GameSocketService.isConnected] keeps reporting healthy. Nothing was /// listening for the app returning to the foreground, so the zombie /// connection / disrupted poll schedule silently lingered until the user /// manually left and reopened the prediction screen (which forces a fresh /// `_onLoad`). Wiring [PredictionAppResumed] to `AppLifecycleState.resumed` /// (see `_PredictionScreenState.didChangeAppLifecycleState`) closes that gap /// without requiring any user action. Future _onAppResumed( PredictionAppResumed event, Emitter emit, ) async { if (!_screenActive) return; if (SupportUiGate.holdsGameRealtime) { // Support sheet / IME lifecycle — refresh via poll, do not tear WS down. _startPolling(); add(const PredictionRefreshTick(forceGameState: true)); return; } if (_socket.isEnabled) { // Prefer a soft check: opening Support / IME can fake a resume and a // hard forceReconnect briefly shows "Reconnecting…" despite a healthy WS. await _socket.reconnectAfterBackground(); } // Old recursive Timer chain may have been suspended mid-flight; restart // it fresh instead of trusting whatever was already scheduled. _startPolling(); add(const PredictionRefreshTick(forceGameState: true)); } Future _onBalancesRefresh(PredictionBalancesRefreshRequested event, Emitter emit) async { final labels = await _loadBalances(state.gameState?.config.walletTypeCode); emit(state.copyWith( mainBalanceLabel: labels.mainLabel, bonusBalanceLabel: labels.bonusLabel, testBalanceLabel: labels.testLabel, mainAvailable: labels.main, bonusAvailable: labels.bonus, testAvailable: labels.test, )); } Future< ({ String mainLabel, String bonusLabel, String testLabel, double main, double bonus, double test, })> _loadBalances(String? walletTypeCode) async { try { final balances = await _walletRepo.getBalances(); if (balances.isEmpty) { return ( mainLabel: '—', bonusLabel: '—', testLabel: '—', main: 0.0, bonus: 0.0, test: 0.0, ); } final code = walletTypeCode ?? 'USDT_TRC20'; final match = balances.where((b) => b.walletType.code == code); final b = match.isNotEmpty ? match.first : balances.first; final symbol = _shortSymbol(b.walletType.code); final decimals = b.walletType.decimals; final main = _rawToDouble(b.available, decimals); final bonus = _rawToDouble(b.bonusAvailable, decimals); final test = _rawToDouble(b.testAvailable, decimals); return ( mainLabel: '${rawAmountToHuman(b.available, decimals)} $symbol', bonusLabel: '${rawAmountToHuman(b.bonusAvailable, decimals)} $symbol', testLabel: '${rawAmountToHuman(b.testAvailable, decimals)} $symbol', main: main, bonus: bonus, test: test, ); } catch (_) { return ( mainLabel: '—', bonusLabel: '—', testLabel: '—', main: 0.0, bonus: 0.0, test: 0.0, ); } } double _rawToDouble(String raw, int decimals) { final human = rawAmountToHuman(raw, decimals); return double.tryParse(human) ?? 0; } static const insufficientBalanceCode = 'insufficient_balance'; String? _insufficientBalanceError() { // Balances not loaded yet — let the API validate. if (state.mainBalanceLabel == '—' && state.bonusBalanceLabel == '—' && state.testBalanceLabel == '—') { return null; } if (state.selectedStake <= state.selectedWalletAvailable) return null; return '$insufficientBalanceCode:${state.stakeAccountKind.apiValue}'; } /// Re-emit even when the message text is unchanged (Equatable would skip otherwise). void _emitError(Emitter emit, String message) { if (state.errorMessage == message) { emit(state.copyWith(clearError: true)); } emit(state.copyWith(errorMessage: message)); } String _shortSymbol(String code) { final upper = code.toUpperCase(); if (upper.startsWith('USDT')) return 'USDT'; if (upper.contains('_')) return upper.split('_').first; return upper; } StakeAccountKind _parseStakeKind(String value) { switch (value) { case 'bonus': return StakeAccountKind.bonus; case 'test': return StakeAccountKind.test; default: return StakeAccountKind.main; } } Future _onLoad(PredictionLoadRequested event, Emitter emit) async { final nowMs = DateTime.now().millisecondsSinceEpoch; if (event.ifStale && state.gameState != null && state.candles.isNotEmpty && nowMs - _lastFullStateSyncMs < _freshSyncMs) { _ensureRealtime(state.selectedIntervalMinutes); _startPolling(); return; } final keepExistingUi = state.gameState != null; if (!keepExistingUi) { emit(state.copyWith(status: PredictionStatus.loading, clearError: true)); } else { emit(state.copyWith(clearError: true)); } _ensureRealtime(state.selectedIntervalMinutes); try { final interval = state.selectedIntervalMinutes; final historyWallet = state.historyWalletFilter; final historyStatus = state.historyStatusFilter; final pageSize = _chartPageSizeForMinutes(interval); final stateFuture = _repo.getState(intervalMinutes: interval); final candlesOutcome = _repo .getCandlesPage( intervalMinutes: interval, limit: pageSize, ) .then<({CandlesPageModel? page, Object? error})>( (page) => (page: page, error: null), onError: (Object e, StackTrace _) => (page: null, error: e), ); final historyFuture = _soft(_fetchHistoryPage( 1, intervalMinutes: interval, wallet: historyWallet, status: historyStatus, )); final balancesFuture = _soft(_loadBalances(state.gameState?.config.walletTypeCode)); final gameState = await stateFuture; _ensureRealtime(gameState.selectedIntervalMinutes); // Apply the HTTP snapshot once, through stabilize. Later progressive // emits must only patch candles / history / balances — re-applying this // captured snapshot after WS has opened the next cycle is what caused // 55s → 0s → 52s → 0s after the first-load optimization. final applied = _stabilizeGameStateRound( previous: state.gameState, incoming: gameState, ); if (state.gameState == null) { emit(_readyFromGameState( applied, candles: state.candles, isLoadingCandles: state.candles.isEmpty, )); } else { emit(state.copyWith( status: PredictionStatus.ready, gameState: applied, selectedIntervalMinutes: applied.selectedIntervalMinutes, wsConnected: _socket.isConnected, realtimeStatus: _realtimeStatus( whenDisconnected: _socket.isEnabled ? PredictionRealtimeStatus.syncing : PredictionRealtimeStatus.polling, ), )); } final candles = await candlesOutcome; if (state.selectedIntervalMinutes != gameState.selectedIntervalMinutes) { return; } if (candles.error == null && candles.page != null) { _rememberCandles( gameState.selectedIntervalMinutes, candles.page!.items, candles.page!.hasMore, ); emit(state.copyWith( status: PredictionStatus.ready, candles: candles.page!.items, hasMoreOlderCandles: candles.page!.hasMore, isLoadingOlderCandles: false, clearCandlesError: true, )); } else if (candles.error != null) { emit(state.copyWith( status: PredictionStatus.ready, isLoadingOlderCandles: false, candlesError: candles.error.toString().replaceFirst('Exception: ', ''), )); } final history = await historyFuture; final labels = await balancesFuture; if (_isCurrentHistoryContext( intervalMinutes: interval, wallet: historyWallet, status: historyStatus, ) && history != null) { final historyItems = _applyLiveHistoryOverlays(history.items); _rememberHistory( historyItems, page: history.page, totalPages: history.totalPages, intervalMinutes: interval, wallet: historyWallet, status: historyStatus, ); emit(state.copyWith( history: historyItems, historyPage: history.page, historyTotalPages: history.totalPages, clearHistoryError: true, mainBalanceLabel: labels?.mainLabel, bonusBalanceLabel: labels?.bonusLabel, testBalanceLabel: labels?.testLabel, mainAvailable: labels?.main, bonusAvailable: labels?.bonus, testAvailable: labels?.test, )); } else { if (_isCurrentHistoryContext( intervalMinutes: interval, wallet: historyWallet, status: historyStatus, ) && history == null && state.history.isEmpty) { emit(state.copyWith( isLoadingHistory: false, historyError: AppException.connectionFailedMessage, mainBalanceLabel: labels?.mainLabel, bonusBalanceLabel: labels?.bonusLabel, testBalanceLabel: labels?.testLabel, mainAvailable: labels?.main, bonusAvailable: labels?.bonus, testAvailable: labels?.test, )); } else if (labels != null) { emit(state.copyWith( mainBalanceLabel: labels.mainLabel, bonusBalanceLabel: labels.bonusLabel, testBalanceLabel: labels.testLabel, mainAvailable: labels.main, bonusAvailable: labels.bonus, testAvailable: labels.test, )); } } _lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch; _healthyPollSkips = 0; _startPolling(); } catch (e) { emit(state.copyWith( status: keepExistingUi ? PredictionStatus.ready : PredictionStatus.error, errorMessage: keepExistingUi ? state.errorMessage : e.toString(), wsConnected: _socket.isConnected, realtimeStatus: _realtimeStatus( whenDisconnected: _socket.isEnabled ? PredictionRealtimeStatus.polling : PredictionRealtimeStatus.syncing, ), )); } } PredictionState _readyFromGameState( GameStateModel gameState, { required List candles, bool hasMoreOlder = true, bool isLoadingCandles = false, List? history, int? historyPage, int? historyTotalPages, ({ String mainLabel, String bonusLabel, String testLabel, double main, double bonus, double test, })? labels, }) { final auto = gameState.autoSettings; final multi = gameState.userMultiBet; final stakeKind = multi != null ? _parseStakeKind(multi.stakeAccountKind) : (auto?.enabled == true) ? _parseStakeKind(auto!.stakeAccountKind) : state.stakeAccountKind; final nextStake = state.status == PredictionStatus.initial ? (auto?.enabled == true && auto!.stakeDisplay > 0 ? auto.stakeDisplay : _defaultStake(gameState.config)) : state.selectedStake; return state.copyWith( status: PredictionStatus.ready, gameState: _stabilizeGameStateRound( previous: state.gameState, incoming: gameState, ), candles: candles, hasMoreOlderCandles: hasMoreOlder, isLoadingOlderCandles: isLoadingCandles, history: history, historyPage: historyPage, historyTotalPages: historyTotalPages, selectedIntervalMinutes: gameState.selectedIntervalMinutes, selectedStake: nextStake, multiSequence: _initialMultiSequence(gameState), selectedMultiLevel: gameState.multiLevels.isNotEmpty ? gameState.multiLevels.first : state.selectedMultiLevel, playMode: gameState.userMultiBet != null ? PredictionPlayMode.multi : (auto?.enabled == true ? PredictionPlayMode.auto : state.playMode), stakeAccountKind: stakeKind, mainBalanceLabel: labels?.mainLabel, bonusBalanceLabel: labels?.bonusLabel, testBalanceLabel: labels?.testLabel, mainAvailable: labels?.main, bonusAvailable: labels?.bonus, testAvailable: labels?.test, wsConnected: _socket.isConnected, realtimeStatus: _realtimeStatus( whenDisconnected: _socket.isEnabled ? PredictionRealtimeStatus.syncing : PredictionRealtimeStatus.polling, ), ); } Future _onIntervalChanged(PredictionIntervalChanged event, Emitter emit) async { final prevInterval = state.selectedIntervalMinutes; final minutes = event.minutes; final gs = state.gameState; final cachedHistory = historyFilterStore.peek( _historyKey( intervalMinutes: minutes, wallet: state.historyWalletFilter, status: state.historyStatusFilter, ), ); final cachedCandles = candleIntervalCache.peek(minutes); emit(state.copyWith( selectedIntervalMinutes: minutes, candles: cachedCandles?.items ?? const [], hasMoreOlderCandles: cachedCandles?.hasMore ?? true, isLoadingOlderCandles: cachedCandles == null, clearCandlesError: true, history: cachedHistory?.items ?? const [], historyPage: cachedHistory?.page ?? 1, historyTotalPages: cachedHistory?.totalPages ?? 1, isLoadingHistory: cachedHistory == null, clearHistoryError: cachedHistory != null, gameState: gs?.copyWith( selectedIntervalMinutes: minutes, clearRound: true, clearUserBet: true, ), )); if (_socket.isEnabled && _socket.isConnected) { if (prevInterval != minutes) { _socket.unsubscribe(prevInterval); } _socket.subscribe(minutes); } try { final pageSize = _chartPageSizeForMinutes(minutes); final stateFuture = _repo.getState(intervalMinutes: minutes); final candlesOutcome = _repo .getCandlesPage( intervalMinutes: minutes, limit: pageSize, ) .then<({CandlesPageModel? page, Object? error})>( (page) => (page: page, error: null), onError: (Object e, StackTrace _) => (page: null, error: e), ); final gameState = await stateFuture; if (state.selectedIntervalMinutes != minutes) return; final applied = _stabilizeGameStateRound( previous: state.gameState, incoming: gameState, ); emit(state.copyWith( status: PredictionStatus.ready, gameState: applied, selectedIntervalMinutes: applied.selectedIntervalMinutes, wsConnected: _socket.isConnected, realtimeStatus: _realtimeStatus( whenDisconnected: _socket.isEnabled ? PredictionRealtimeStatus.syncing : PredictionRealtimeStatus.polling, ), )); final candles = await candlesOutcome; if (state.selectedIntervalMinutes != minutes) return; if (candles.error == null && candles.page != null) { _rememberCandles(minutes, candles.page!.items, candles.page!.hasMore); emit(state.copyWith( candles: candles.page!.items, hasMoreOlderCandles: candles.page!.hasMore, isLoadingOlderCandles: false, clearCandlesError: true, )); } else if (candles.error != null) { emit(state.copyWith( isLoadingOlderCandles: false, candlesError: candles.error.toString().replaceFirst('Exception: ', ''), )); } _lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch; _healthyPollSkips = 0; _startPolling(); await _refreshHistoryFromServer( emit, page: 1, showSpinnerIfEmpty: cachedHistory == null, ); } catch (e) { if (state.selectedIntervalMinutes != minutes) return; emit(state.copyWith( errorMessage: e.toString().replaceFirst('Exception: ', ''), )); } } void _onStakeSelected(PredictionStakeSelected event, Emitter emit) { emit(state.copyWith(selectedStake: event.stake)); } void _onDirectionSelected(PredictionDirectionSelected event, Emitter emit) { emit(state.copyWith(selectedDirection: event.direction)); } void _onStakeAccountChanged(PredictionStakeAccountChanged event, Emitter emit) { emit(state.copyWith(stakeAccountKind: event.kind)); } void _onPlayModeChanged(PredictionPlayModeChanged event, Emitter emit) { emit(state.copyWith(playMode: event.mode)); } void _onMultiLevelSelected(PredictionMultiLevelSelected event, Emitter emit) { final level = event.level; emit(state.copyWith( selectedMultiLevel: level, multiSequence: List.filled(level.candleCount, 'long'), )); } void _onMultiDirectionToggled(PredictionMultiDirectionToggled event, Emitter emit) { final seq = List.from(state.multiSequence); if (event.index < 0 || event.index >= seq.length) return; seq[event.index] = seq[event.index] == 'long' ? 'short' : 'long'; emit(state.copyWith(multiSequence: seq)); } Future _onPlaceBet(PredictionPlaceBetRequested event, Emitter emit) async { final gs = state.gameState; if (gs == null) return; final balanceError = _insufficientBalanceError(); if (balanceError != null) { _emitError(emit, balanceError); return; } emit(state.copyWith(isPlacingBet: true, clearError: true)); try { await _repo.placeBet( direction: state.selectedDirection, stakeAmount: state.selectedStake, intervalMinutes: gs.selectedIntervalMinutes, stakeAccountKind: state.stakeAccountKind.apiValue, ); // Toast only for this user-initiated success — never from WS/poll echoes. emit(state.copyWith(isPlacingBet: false, betPlaced: true)); add(const PredictionBalancesRefreshRequested()); add(const PredictionLoadRequested()); } catch (e) { emit(state.copyWith(isPlacingBet: false)); _emitError(emit, e.toString()); } } Future _onPlaceMultiBet(PredictionPlaceMultiBetRequested event, Emitter emit) async { final gs = state.gameState; final level = state.selectedMultiLevel; if (gs == null || level == null) return; final balanceError = _insufficientBalanceError(); if (balanceError != null) { _emitError(emit, balanceError); return; } emit(state.copyWith(isPlacingBet: true, clearError: true)); try { await _repo.placeMultiBet( level: level.level, sequence: state.multiSequence, stakeAmount: state.selectedStake, intervalMinutes: gs.selectedIntervalMinutes, stakeAccountKind: state.stakeAccountKind.apiValue, ); emit(state.copyWith(isPlacingBet: false, betPlaced: true)); add(const PredictionBalancesRefreshRequested()); add(const PredictionLoadRequested()); } catch (e) { emit(state.copyWith(isPlacingBet: false)); _emitError(emit, e.toString()); } } Future _onAutoSave(PredictionAutoSaveRequested event, Emitter emit) async { final enabling = event.body['enabled'] == true; if (enabling) { final balanceError = _insufficientBalanceError(); if (balanceError != null) { _emitError(emit, balanceError); return; } } emit(state.copyWith(isSavingAuto: true, clearError: true)); try { final saved = await _repo.saveAutoSettings(event.body); final gs = state.gameState; if (gs != null) { emit(state.copyWith( isSavingAuto: false, gameState: gs.copyWith(autoSettings: saved), stakeAccountKind: _parseStakeKind(saved.stakeAccountKind), selectedStake: saved.stakeDisplay > 0 ? saved.stakeDisplay : state.selectedStake, playMode: PredictionPlayMode.auto, clearError: saved.autoBetError == null, errorMessage: saved.autoBetError, betPlaced: saved.autoBetPlaced, )); } else { emit(state.copyWith( isSavingAuto: false, clearError: saved.autoBetError == null, errorMessage: saved.autoBetError, betPlaced: saved.autoBetPlaced, )); } if (saved.autoBetPlaced) { add(const PredictionBalancesRefreshRequested()); add(const PredictionLoadRequested()); } else if (saved.enabled) { _startPolling(); add(const PredictionHistoryPageRequested(1)); } } catch (e) { emit(state.copyWith(isSavingAuto: false)); _emitError(emit, e.toString()); } } Future _onRefreshTick(PredictionRefreshTick event, Emitter emit) async { if (!_screenActive || state.status != PredictionStatus.ready) return; try { final interval = state.selectedIntervalMinutes; final wsOk = _socket.isEnabled && _socket.isConnected; final hasActiveMulti = state.gameState?.userMultiBet != null; final autoOn = state.gameState?.autoSettings?.enabled == true; final prevUserBetId = state.gameState?.userBet?.id; final prevLastAuto = state.gameState?.autoSettings?.lastAutoBetAt; final nowMs = DateTime.now().millisecondsSinceEpoch; // Phase boundary (0s / ≤1s): never skip `/state` — healthy-WS skips were // leaving the UI stuck at 0s for ~8–20s then jumping mid next window. final phaseBoundary = countdownNeedsStateResync(state.gameState?.round, clientNowMs: nowMs); final shouldDoSafetyStateSync = !event.forceGameState && wsOk && !hasActiveMulti && !autoOn && (_healthyPollSkips >= 2 || nowMs - _lastFullStateSyncMs >= 20000); // Skip full state polls only when WS is healthy AND there's nothing that // needs frequent HTTP sync (auto placement / multi progress / new window). if (wsOk && !hasActiveMulti && !autoOn && !event.forceGameState && !phaseBoundary && !shouldDoSafetyStateSync) { _healthyPollSkips++; final labels = await _loadBalances(state.gameState?.config.walletTypeCode); final gs = state.gameState; final round = gs?.round; final nextBet = _userBetForRound(gs?.userBet, round); emit(state.copyWith( gameState: gs == null || identical(nextBet, gs.userBet) ? gs : gs.copyWith(userBet: nextBet, clearUserBet: nextBet == null), mainBalanceLabel: labels.mainLabel, bonusBalanceLabel: labels.bonusLabel, testBalanceLabel: labels.testLabel, mainAvailable: labels.main, bonusAvailable: labels.bonus, testAvailable: labels.test, wsConnected: true, realtimeStatus: PredictionRealtimeStatus.live, )); return; } _healthyPollSkips = 0; final gameState = await _repo.getState( intervalMinutes: interval, force: event.forceGameState || phaseBoundary, ); final labels = await _loadBalances(gameState.config.walletTypeCode); final multi = gameState.userMultiBet; var history = state.history; if (multi != null) { history = _historyWithMultiProgress(history, multi); } final userBet = gameState.userBet; if (userBet != null) { history = _historyWithPrediction(history, userBet); } final userBetChanged = userBet?.id != prevUserBetId; final autoPlaced = gameState.autoSettings?.lastAutoBetAt != null && gameState.autoSettings?.lastAutoBetAt != prevLastAuto; emit(state.copyWith( gameState: _stabilizeGameStateRound( previous: state.gameState, incoming: gameState, forceRound: event.forceGameState, ), mainBalanceLabel: labels.mainLabel, bonusBalanceLabel: labels.bonusLabel, testBalanceLabel: labels.testLabel, mainAvailable: labels.main, bonusAvailable: labels.bonus, testAvailable: labels.test, wsConnected: _socket.isConnected || (SupportUiGate.holdsGameRealtime && state.isRealtimeHealthy), realtimeStatus: _realtimeStatus( whenDisconnected: _socket.isEnabled ? PredictionRealtimeStatus.reconnecting : PredictionRealtimeStatus.polling, ), history: history, stakeAccountKind: multi != null ? _parseStakeKind(multi.stakeAccountKind) : state.stakeAccountKind, )); _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); _lastFullStateSyncMs = nowMs; if (hasActiveMulti || multi != null || autoOn || userBetChanged || autoPlaced) { _multiPollTicks++; if (userBetChanged || autoPlaced || _multiPollTicks % 2 == 0) { add(const PredictionHistoryPageRequested(1)); } _startPolling(); } else { _multiPollTicks = 0; } if (_socket.isEnabled && !_socket.isConnected) { await _socket.connect(); if (_socket.isConnected) { _socket.subscribe(interval); _startPolling(); } } } catch (_) {} } void _onWsMessage(PredictionWsMessageReceived event, Emitter emit) { final gs = state.gameState; if (gs == null) return; final msg = event.message; final type = msg['type'] as String?; final msgInterval = (msg['intervalMinutes'] as num?)?.toInt(); // Ignore realtime events for intervals we are not viewing. if (msgInterval != null && msgInterval != state.selectedIntervalMinutes && type != 'connected' && type != 'subscribed') { return; } switch (type) { case 'connected': emit(state.copyWith( wsConnected: true, realtimeStatus: PredictionRealtimeStatus.live, )); break; case 'subscribed': if (msgInterval != null && msgInterval != state.selectedIntervalMinutes) { return; } final snapshot = msg['snapshot']; if (snapshot is Map) { final next = _stabilizeGameStateRound( previous: state.gameState, incoming: GameStateModel.fromJson(snapshot), ); var history = state.history; if (next.userMultiBet != null) { history = _historyWithMultiProgress(history, next.userMultiBet!); } if (next.userBet != null) { history = _historyWithPrediction(history, next.userBet!); } emit(state.copyWith( gameState: next, selectedIntervalMinutes: next.selectedIntervalMinutes, wsConnected: true, realtimeStatus: PredictionRealtimeStatus.live, history: history, stakeAccountKind: next.userMultiBet != null ? _parseStakeKind(next.userMultiBet!.stakeAccountKind) : state.stakeAccountKind, )); _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); if (next.autoSettings?.enabled == true) { _startPolling(); } } break; case 'round.updated': case 'round.settled': final roundVersions = msg['versions']; // Do not advance the ETag on settle before `/state` — that caused 304 // loops while the UI was stuck at secondsToBettingStart: 0. if (type == 'round.updated' && roundVersions is Map) { PredictionRepositoryImpl.mergeCachedStateVersions( state.selectedIntervalMinutes, round: roundVersions['round'] is num ? (roundVersions['round'] as num).toInt() : null, ); } final round = msg['round']; if (round is Map) { final incomingRound = RoundModel.fromJson(round); if (!isIncomingRoundStale(gs.round, incomingRound)) { final parsed = mergeRound(gs.round, incomingRound); final prevStatus = gs.round?.status; final prevRoundId = gs.round?.id; // Timer-only WS ticks must not remount countdown / overwrite UI state. if (roundUiChanged(gs.round, parsed)) { final nextBet = _userBetForRound(gs.userBet, parsed); emit(state.copyWith( gameState: gs.copyWith( round: parsed, userBet: nextBet, clearUserBet: nextBet == null, ), )); // New open window: clear stale lock + sync server state. final openedBetting = parsed.status == 'betting' && prevStatus != 'betting'; final roundChanged = prevRoundId != null && prevRoundId != parsed.id; if (openedBetting || (roundChanged && parsed.status == 'betting')) { add(const PredictionRefreshTick(forceGameState: true)); if (gs.autoSettings?.enabled == true) { add(const PredictionHistoryPageRequested(1)); } } } } } if (type == 'round.settled') { // Candle + next window arrive via candle.append / round.updated. // Force `/state` without the settle ETag so clients leave 0s promptly. PredictionRepositoryImpl.invalidateStateCache( state.selectedIntervalMinutes, ); add(const PredictionBalancesRefreshRequested()); add(const PredictionHistoryPageRequested(1)); add(const PredictionRefreshTick(forceGameState: true)); add(const PredictionCandlesReloadRequested()); } break; case 'multi.updated': final multiVersions = msg['versions']; if (multiVersions is Map) { PredictionRepositoryImpl.mergeCachedStateVersions( state.selectedIntervalMinutes, bet: multiVersions['bet'] is num ? (multiVersions['bet'] as num).toInt() : null, ); } final multi = msg['userMultiBet']; if (multi is Map) { final parsed = MultiCandlePredictionModel.fromJson(multi); final history = _historyWithMultiProgress(state.history, parsed); emit(state.copyWith( gameState: gs.copyWith(userMultiBet: parsed), history: history, playMode: PredictionPlayMode.multi, stakeAccountKind: _parseStakeKind(parsed.stakeAccountKind), )); _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); _startPolling(); } else if (multi == null) { emit(state.copyWith(gameState: gs.copyWith(clearUserMultiBet: true))); add(const PredictionHistoryPageRequested(1)); _startPolling(); } break; case 'candle.append': final candle = msg['candle']; if (candle is Map) { final c = OhlcCandleModel.fromJson(candle); final existing = state.candles; if (existing.isNotEmpty) { final last = existing.last; final intervalMs = state.selectedIntervalMinutes * 60 * 1000; // More than ~1.5 intervals between bars ⇒ we missed WS frames. if (c.openMs - last.openMs > (intervalMs * 3) ~/ 2) { add(const PredictionCandlesReloadRequested()); break; } } emit(state.copyWith(candles: _mergeCandles(existing, [c]))); } break; case 'bet.accepted': final betVersions = msg['versions']; if (betVersions is Map) { PredictionRepositoryImpl.mergeCachedStateVersions( state.selectedIntervalMinutes, bet: betVersions['bet'] is num ? (betVersions['bet'] as num).toInt() : null, auto: betVersions['auto'] is num ? (betVersions['auto'] as num).toInt() : null, ); } final betRaw = msg['bet']; if (betRaw is Map) { final bet = PredictionModel.fromJson(betRaw); final history = _historyWithPrediction(state.history, bet); final GameStateModel nextGs; if (bet.isMulti) { nextGs = gs.copyWith( userMultiBet: MultiCandlePredictionModel( id: bet.id, level: bet.level ?? bet.sequenceDirections.length, sequenceDirections: bet.sequenceDirections, sequenceStep: bet.sequenceStep, stakeDisplay: bet.stakeDisplay, status: bet.status, payoutDisplay: bet.payoutDisplay, intervalMinutes: bet.intervalMinutes, stakeAccountKind: bet.stakeAccountKind, ), clearUserBet: true, ); } else if (gs.round != null && bet.roundId != null && bet.roundId!.isNotEmpty && bet.roundId != gs.round!.id) { // Bet is for another round — ignore for the active lock. nextGs = gs; } else { nextGs = gs.copyWith(userBet: bet); } final auto = gs.autoSettings; final nextAuto = (bet.isAuto && auto != null) ? AutoSettingsModel( enabled: auto.enabled, direction: auto.direction, stakeDisplay: auto.stakeDisplay, mode: auto.mode, periodMinutes: auto.periodMinutes, stakeAccountKind: auto.stakeAccountKind, intervalSeconds: auto.intervalSeconds, lastAutoBetAt: DateTime.now().toIso8601String(), autoBetPlaced: false, autoBetError: null, ) : auto; // Update UI/history only — do not toast here (WS echoes / auto rounds / // other-interval bets caused false "Prediction placed" messages). emit(state.copyWith( gameState: nextAuto != null ? nextGs.copyWith(autoSettings: nextAuto) : nextGs, history: history, stakeAccountKind: bet.isMulti ? _parseStakeKind(bet.stakeAccountKind) : state.stakeAccountKind, )); _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); } add(const PredictionBalancesRefreshRequested()); add(const PredictionHistoryPageRequested(1)); break; case 'auto.updated': final autoVersions = msg['versions']; if (autoVersions is Map) { PredictionRepositoryImpl.mergeCachedStateVersions( state.selectedIntervalMinutes, auto: autoVersions['auto'] is num ? (autoVersions['auto'] as num).toInt() : null, ); } final autoRaw = msg['autoSettings']; if (autoRaw is Map) { final current = gs.autoSettings; final merged = AutoSettingsModel( enabled: autoRaw['enabled'] as bool? ?? current?.enabled ?? false, direction: autoRaw['direction'] as String? ?? current?.direction, stakeDisplay: (autoRaw['stakeDisplay'] as num?)?.toDouble() ?? current?.stakeDisplay ?? 0, mode: autoRaw['mode'] as String? ?? current?.mode ?? 'each_round', periodMinutes: (autoRaw['periodMinutes'] as num?)?.toInt() ?? current?.periodMinutes ?? state.selectedIntervalMinutes, stakeAccountKind: autoRaw['stakeAccountKind'] as String? ?? current?.stakeAccountKind ?? 'main', intervalSeconds: (autoRaw['intervalSeconds'] as num?)?.toInt() ?? current?.intervalSeconds, lastAutoBetAt: autoRaw['lastAutoBetAt'] as String? ?? current?.lastAutoBetAt, autoBetPlaced: autoRaw['autoBetPlaced'] as bool? ?? current?.autoBetPlaced ?? false, autoBetError: autoRaw['autoBetError'] as String? ?? current?.autoBetError, ); emit(state.copyWith(gameState: gs.copyWith(autoSettings: merged))); _startPolling(); } break; default: break; } } Future _onHistoryPage(PredictionHistoryPageRequested event, Emitter emit) async { await _refreshHistoryFromServer( emit, page: event.page, append: event.append, showSpinnerIfEmpty: !event.append, ); } Future _onHistoryFilterChanged( PredictionHistoryFilterChanged event, Emitter emit, ) async { final cached = historyFilterStore.peek( _historyKey( wallet: event.walletFilter, status: event.statusFilter, ), ); emit(state.copyWith( historyWalletFilter: event.walletFilter, historyStatusFilter: event.statusFilter, clearHistoryWalletFilter: event.walletFilter == null, clearHistoryStatusFilter: event.statusFilter == null, history: cached?.items ?? const [], historyPage: cached?.page ?? 1, historyTotalPages: cached?.totalPages ?? 1, isLoadingHistory: cached == null, )); await _refreshHistoryFromServer( emit, page: 1, showSpinnerIfEmpty: cached == null, ); } Future _onOlderCandles(PredictionCandlesOlderRequested event, Emitter emit) async { if (state.candles.isEmpty || state.isLoadingOlderCandles || !state.hasMoreOlderCandles) { return; } emit(state.copyWith(isLoadingOlderCandles: true, clearCandlesError: true)); try { final oldest = state.candles.first; final pageSize = (state.gameState?.interval.chartCandleLimit ?? 80).clamp(20, 200); final page = await _repo.getCandlesPage( intervalMinutes: state.selectedIntervalMinutes, beforeOpenMs: oldest.openMs, limit: pageSize, ); final merged = _mergeCandles(page.items, state.candles); _rememberCandles( state.selectedIntervalMinutes, merged, page.hasMore, ); emit(state.copyWith( candles: merged, hasMoreOlderCandles: page.hasMore, isLoadingOlderCandles: false, clearCandlesError: true, )); } catch (e) { emit(state.copyWith( isLoadingOlderCandles: false, candlesError: e.toString().replaceFirst('Exception: ', ''), )); } } Future _onCandlesReload( PredictionCandlesReloadRequested event, Emitter emit, ) async { emit(state.copyWith( isLoadingOlderCandles: true, clearCandlesError: true, )); try { final pageSize = (state.gameState?.interval.chartCandleLimit ?? 80).clamp(20, 200); final page = await _repo.getCandlesPage( intervalMinutes: state.selectedIntervalMinutes, limit: pageSize, ); _rememberCandles( state.selectedIntervalMinutes, page.items, page.hasMore, ); emit(state.copyWith( candles: page.items, hasMoreOlderCandles: page.hasMore, isLoadingOlderCandles: false, clearCandlesError: true, )); } catch (e) { emit(state.copyWith( isLoadingOlderCandles: false, candlesError: e.toString().replaceFirst('Exception: ', ''), )); } } static PredictionModel? _userBetForRound(PredictionModel? bet, RoundModel? round) { if (bet == null || round == null) return null; return bet.belongsToRound(round) ? bet : null; } static List _mergeCandles( List a, List b, ) { if (a.isEmpty) return List.from(b); if (b.isEmpty) return List.from(a); final map = {}; for (final c in a) { map[c.openMs] = c; } for (final c in b) { map[c.openMs] = c; } final merged = map.values.toList() ..sort((x, y) => x.openMs.compareTo(y.openMs)); return merged; } double _defaultStake(PredictConfigModel config) { if (config.stakeAmounts.isNotEmpty) return config.stakeAmounts.first; return config.minStakeAmount; } /// Keep countdown stable: reject older cycles, merge absolute deadlines, /// and ignore timer-only round ticks. GameStateModel _stabilizeGameStateRound({ required GameStateModel? previous, required GameStateModel incoming, bool forceRound = false, }) { final incomingRound = incoming.round; if (incomingRound == null) return incoming; if (isIncomingRoundStale(previous?.round, incomingRound)) { return incoming.copyWith(round: previous!.round); } final merged = mergeRound(previous?.round, incomingRound); if (!forceRound && previous?.round != null && !roundUiChanged(previous!.round, merged)) { return incoming.copyWith(round: previous.round); } return incoming.copyWith(round: merged); } List _initialMultiSequence(GameStateModel gs) { final level = gs.multiLevels.isNotEmpty ? gs.multiLevels.first : null; if (level == null) return const ['long', 'long']; return List.filled(level.candleCount, 'long'); } /// Patch history rows with live multi-candle step/status so the list updates /// without waiting for a full HTTP history reload. List _historyWithMultiProgress( List history, MultiCandlePredictionModel multi, ) { var found = false; final updated = history.map((p) { if (p.id != multi.id) return p; found = true; return PredictionModel( id: multi.id, direction: multi.sequenceDirections.isNotEmpty ? multi.sequenceDirections.first : p.direction, stakeDisplay: multi.stakeDisplay, status: multi.status, payoutDisplay: multi.payoutDisplay, createdAt: p.createdAt, stakeAccountKind: p.stakeAccountKind, isAuto: p.isAuto, predictionMode: 'multi_candle', level: multi.level, sequenceDirections: multi.sequenceDirections, sequenceStep: multi.sequenceStep, intervalMinutes: multi.intervalMinutes, ); }).toList(); if (found) return updated; final live = PredictionModel( id: multi.id, direction: multi.sequenceDirections.isNotEmpty ? multi.sequenceDirections.first : 'long', stakeDisplay: multi.stakeDisplay, status: multi.status, payoutDisplay: multi.payoutDisplay, createdAt: DateTime.now().toIso8601String(), stakeAccountKind: multi.stakeAccountKind, predictionMode: 'multi_candle', level: multi.level, sequenceDirections: multi.sequenceDirections, sequenceStep: multi.sequenceStep, intervalMinutes: multi.intervalMinutes, ); if (!_matchesHistoryFilters(live)) return history; return [live, ...history]; } /// Ensure a single/auto prediction appears at the top of Recent predictions. List _historyWithPrediction( List history, PredictionModel bet, ) { if (!_matchesHistoryFilters(bet)) return history; final without = history.where((p) => p.id != bet.id).toList(); return [bet, ...without]; } }