import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter/services.dart'; import 'package:flutter_mjpeg/flutter_mjpeg.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import '../utils/translations.dart'; import '../services/app_settings.dart'; import '../widgets/camera_sheet.dart'; import '../widgets/help_sheet.dart'; import '../widgets/image_settings.dart'; import '../services/wifi_binding.dart'; class CameraStreamScreen extends StatefulWidget { final int cameraIndex; // shooting position 1–6 final String? ip; // chosen camera; falls back to the saved IP of the position final String? location; // strelišče the camera belongs to const CameraStreamScreen( {super.key, required this.cameraIndex, this.ip, this.location}); // Image settings are kept per camera, i.e. per position and location String get settingsId => location == null ? '$cameraIndex' : '${cameraIndex}_$location'; String get title => location == null ? '$cameraIndex' : '$cameraIndex · $location'; @override State createState() => _CameraStreamScreenState(); } class _CameraStreamScreenState extends State with TickerProviderStateMixin { String? _streamUrl; bool _isError = false; final TransformationController _transformationController = TransformationController(); ImageAdjustments _image = const ImageAdjustments(); int _numberOfBullets = 5; Color _bulletColor = Colors.blue; String _selectedLanguage = 'English'; // --- Timer state --- bool _timerEnabled = false; int _shootSeconds = 30; int? _reloadSeconds; int? _waitSeconds; bool _fullTarget = false; // false = single shot, true = full target bool _isRunning = false; bool _isPaused = false; bool _isWaitPhase = false; bool _isReloadPhase = false; int _remaining = 0; int _shotsLeft = 0; Timer? _countdownTimer; // --- Manual bullet counter --- bool _manualCounterEnabled = true; int _manualShotsLeft = 0; // --- Change target overlay --- bool _showChangeTarget = false; bool _changeTargetOverlayEnabled = true; Timer? _changeTargetTimer; // --- Phase-change flash --- late AnimationController _flashController; late Animation _flashAnimation; bool _showFlash = false; Color _flashColor = Colors.white; // --- Phase progress bars (continuous, no per-second restart) --- late AnimationController _shootProgressController; late AnimationController _reloadProgressController; late AnimationController _waitProgressController; String _t(String key) { return AppTranslations.translate(key, _selectedLanguage); } // raw values always stored; null means "never configured" int? _reloadSecondsRaw; int? _waitSecondsRaw; bool _shootEnabled = false; bool _reloadEnabled = false; bool _waitEnabled = false; late final Future _wifiReady; Future _loadAllPrefs() async { await _wifiReady; // stream must start after traffic is pinned to Wi-Fi final prefs = await SharedPreferences.getInstance(); final image = await ImageAdjustments.load(widget.settingsId); final url = widget.ip ?? prefs.getString('cameraIP_${widget.cameraIndex}'); final streamUrl = (url != null && url.trim().isNotEmpty) ? (url.startsWith(RegExp(r"https?://")) ? url : "http://$url") : null; final savedShoot = prefs.getInt('timerShootSeconds'); final savedReload = prefs.getInt('timerReloadSeconds'); final savedWait = prefs.getInt('timerWaitSeconds'); final shootOn = prefs.getBool('timerShootEnabled') ?? false; final reloadOn = prefs.getBool('timerReloadEnabled') ?? false; final waitOn = prefs.getBool('timerWaitEnabled') ?? false; setState(() { _selectedLanguage = prefs.getString('language') ?? 'English'; // Older versions allowed up to 10 _numberOfBullets = (prefs.getInt('bulletCount') ?? AppSettings.maxBullets) .clamp(AppSettings.minBullets, AppSettings.maxBullets); _image = image; _bulletColor = _getColorFromName(prefs.getString('bulletColor') ?? 'Blue'); _streamUrl = streamUrl; _isError = streamUrl == null; if (savedShoot != null) _shootSeconds = savedShoot; _reloadSecondsRaw = savedReload; _waitSecondsRaw = savedWait; _shootEnabled = shootOn; _reloadEnabled = reloadOn; _waitEnabled = waitOn; _reloadSeconds = reloadOn ? savedReload : null; _waitSeconds = waitOn ? savedWait : null; _timerEnabled = shootOn || reloadOn || waitOn; _fullTarget = prefs.getBool('timerFullTarget') ?? false; _changeTargetOverlayEnabled = prefs.getBool('showChangeTargetOverlay') ?? true; _manualCounterEnabled = prefs.getBool('manualCounterEnabled') ?? true; _manualShotsLeft = _numberOfBullets; }); } Future _saveTimerPrefs() async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool('timerEnabled', _timerEnabled); await prefs.setInt('timerShootSeconds', _shootSeconds); await prefs.setBool('timerFullTarget', _fullTarget); await prefs.setBool('timerShootEnabled', _shootEnabled); await prefs.setBool('timerReloadEnabled', _reloadEnabled); await prefs.setBool('timerWaitEnabled', _waitEnabled); if (_reloadSecondsRaw != null) { await prefs.setInt('timerReloadSeconds', _reloadSecondsRaw!); } if (_waitSecondsRaw != null) { await prefs.setInt('timerWaitSeconds', _waitSecondsRaw!); } } @override void initState() { super.initState(); _wifiReady = WifiBinding.acquire(); _loadAllPrefs(); _setSystemBarStyle(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); _keepScreenAwake(); _shootProgressController = AnimationController(vsync: this); _reloadProgressController = AnimationController(vsync: this); _waitProgressController = AnimationController(vsync: this); _flashController = AnimationController( vsync: this, duration: const Duration(milliseconds: 600), ); _flashAnimation = Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: _flashController, curve: Curves.easeInOut), ); _flashController.addStatusListener((status) { if (status == AnimationStatus.completed) { _flashController.reverse(); } else if (status == AnimationStatus.dismissed) { if (mounted) setState(() => _showFlash = false); } }); } Color _getColorFromName(String colorName) { switch (colorName.toLowerCase()) { case 'blue': return Colors.blue; case 'green': return Colors.green; case 'yellow': return Colors.yellow; case 'purple': return Colors.purple; case 'cyan': return Colors.cyan; case 'teal': return Colors.teal; case 'indigo': return Colors.indigo; case 'pink': return Colors.pink; case 'lime': return Colors.lime; case 'mint': return Colors.greenAccent; case 'sky': return Colors.orange; case 'violet': return Colors.deepPurpleAccent; case 'amber': return Colors.amber; case 'brown': return Colors.brown; case 'grey': return Colors.grey; default: return Colors.blue; // fallback } } void _setSystemBarStyle() { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarColor: Colors.grey[900], // ✅ match your AppBar statusBarIconBrightness: Brightness.light, // white icons systemNavigationBarColor: Colors.grey[900], systemNavigationBarIconBrightness: Brightness.light, // No grey scrim behind 3-button navigation; we paint the strip ourselves systemNavigationBarContrastEnforced: false, ), ); } Future _keepScreenAwake() async { try { await WakelockPlus.enable(); } catch (e) { debugPrint("⚠️ Could not keep screen awake: $e"); } } Future _loadStreamUrl() async { final prefs = await SharedPreferences.getInstance(); String? url = widget.ip ?? prefs.getString('cameraIP_${widget.cameraIndex}'); setState(() { _streamUrl = (url != null && url.trim().isNotEmpty) ? (url.startsWith(RegExp(r"https?://")) ? url : "http://$url") : null; _isError = _streamUrl == null; }); } void _showImageSettingsDialog() { showImageSettingsSheet( context, initial: _image, settingsId: widget.settingsId, cameraLabel: "${_t('Camera')} ${widget.title}", accent: _bulletColor, t: _t, onChanged: (value) => setState(() => _image = value), ); } void _showBulletDialog() { showCameraSheet( context, builder: (sheet) => StatefulBuilder( builder: (context, setSheetState) { Future setCount(int count) async { final clamped = count.clamp(AppSettings.minBullets, AppSettings.maxBullets); setState(() => _numberOfBullets = clamped); setSheetState(() {}); final prefs = await SharedPreferences.getInstance(); await prefs.setInt('bulletCount', clamped); } return Column( mainAxisSize: MainAxisSize.min, children: [ CameraSheetHeader( title: _t('Select the number of bullets'), subtitle: '${AppSettings.minBullets} – ${AppSettings.maxBullets}', ), SheetStepper( value: _numberOfBullets, min: AppSettings.minBullets, max: AppSettings.maxBullets, accent: _bulletColor, onChanged: setCount, ), const SizedBox(height: 8), ], ); }, ), ); } void _showHelpDialog() { showHelpSheet(context, accent: _bulletColor, t: _t, items: const [ (Icons.pinch, 'Pinch to zoom on the camera stream'), (Icons.filter_5_rounded, 'Number bottom left: shots per target (1–5).'), ( Icons.timer, 'Timer icon: set shoot, reload and wait times. While the timer runs, tap it to stop.' ), ( Icons.play_arrow, 'Play / pause / stop in the middle: control the timer.' ), ( Icons.circle_outlined, 'Circle icon: shot counter. Tap + after each shot; when the target is full you get a "Change target!" warning.' ), ( Icons.tune, 'Settings icon: brightness, contrast, filters and rotation, saved for each camera.' ), ]); } @override void dispose() { _countdownTimer?.cancel(); _changeTargetTimer?.cancel(); _shootProgressController.dispose(); _reloadProgressController.dispose(); _waitProgressController.dispose(); _flashController.dispose(); WifiBinding.release(); _restoreScreenSettings(); _setSystemBarStyle(); super.dispose(); } // --- Timer logic --- void _startTimer() { if (_isRunning) { _stopTimer(); return; } _shootProgressController.reset(); _reloadProgressController.reset(); _waitProgressController.reset(); final hasShoot = _shootEnabled && _shootSeconds > 0; final hasReload = _reloadSeconds != null && _reloadSeconds! > 0; final hasWait = _waitSeconds != null && _waitSeconds! > 0; final shots = _fullTarget ? _numberOfBullets : 1; if (hasShoot) { setState(() { _isRunning = true; _isWaitPhase = false; _isReloadPhase = false; _remaining = _shootSeconds; _shotsLeft = shots; _showFlash = true; _flashColor = _bulletColor; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); } else if (hasReload) { setState(() { _isRunning = true; _isReloadPhase = true; _isWaitPhase = false; _remaining = _reloadSeconds!; _shotsLeft = shots; _showFlash = true; _flashColor = Colors.orange; }); _flashController.forward(from: 0.0); _startReloadProgress(_reloadSeconds!); } else if (hasWait) { setState(() { _isRunning = true; _isWaitPhase = true; _isReloadPhase = false; _remaining = _waitSeconds!; _shotsLeft = shots; _showFlash = true; _flashColor = Colors.red; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); } else { return; // nothing configured } _tickDown(); } void _startShootProgress(int durationSeconds) { _shootProgressController.duration = Duration(seconds: durationSeconds); _shootProgressController.forward(from: 0.0); } void _startReloadProgress(int durationSeconds) { _reloadProgressController.duration = Duration(seconds: durationSeconds); _reloadProgressController.forward(from: 0.0); } void _startWaitProgress(int durationSeconds) { _waitProgressController.duration = Duration(seconds: durationSeconds); _waitProgressController.forward(from: 0.0); } void _stopTimer() { _countdownTimer?.cancel(); _shootProgressController.stop(); _shootProgressController.reset(); _reloadProgressController.stop(); _reloadProgressController.reset(); _waitProgressController.stop(); _waitProgressController.reset(); setState(() { _isRunning = false; _isPaused = false; _isWaitPhase = false; _isReloadPhase = false; _remaining = 0; _shotsLeft = 0; }); } void _pauseTimer() { _countdownTimer?.cancel(); _shootProgressController.stop(); _reloadProgressController.stop(); _waitProgressController.stop(); setState(() => _isPaused = true); } void _resumeTimer() { setState(() => _isPaused = false); if (_isWaitPhase) { final total = _waitSeconds ?? 1; final from = total > 0 ? (total - _remaining) / total : 0.0; _waitProgressController.duration = Duration(seconds: _remaining); _waitProgressController.forward(from: from); } else if (_isReloadPhase) { final total = _reloadSeconds ?? 1; final from = total > 0 ? (total - _remaining) / total : 0.0; _reloadProgressController.duration = Duration(seconds: _remaining); _reloadProgressController.forward(from: from); } else { final from = _shootSeconds > 0 ? (_shootSeconds - _remaining) / _shootSeconds : 0.0; _shootProgressController.duration = Duration(seconds: _remaining); _shootProgressController.forward(from: from); } _tickDown(); } void _tickDown() { _countdownTimer?.cancel(); _countdownTimer = Timer.periodic(const Duration(seconds: 1), (t) { if (!mounted) { t.cancel(); return; } setState(() => _remaining--); if (_remaining <= 0) { t.cancel(); _onPhaseComplete(); } }); } void _onPhaseComplete() { // Cycle order per shot: shoot → reload → wait → (next shot or done) // --- Wait phase ended: cycle complete, start next shoot --- if (_isWaitPhase) { if (_shotsLeft <= 0) { _stopTimer(); return; } // More shots remaining: start next shoot setState(() { _showFlash = true; _flashColor = _bulletColor; _isWaitPhase = false; _isReloadPhase = false; _remaining = _shootSeconds; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); _tickDown(); return; } // --- Reload phase ended: go to wait if configured, else end cycle --- if (_isReloadPhase) { final hasWait = _waitSeconds != null && _waitSeconds! > 0; if (hasWait) { setState(() { _showFlash = true; _flashColor = Colors.red; _isReloadPhase = false; _isWaitPhase = true; _remaining = _waitSeconds!; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); _tickDown(); } else { // No wait: cycle done if (_shotsLeft <= 0) { _stopTimer(); return; } setState(() { _showFlash = true; _flashColor = _bulletColor; _isReloadPhase = false; _remaining = _shootSeconds; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); _tickDown(); } return; } // --- Shoot phase ended --- // Decrement shotsLeft now so the dot disappears immediately final newShotsLeft = _shotsLeft - 1; setState(() => _shotsLeft = newShotsLeft); final hasReload = _reloadSeconds != null && _reloadSeconds! > 0; final hasWait = _waitSeconds != null && _waitSeconds! > 0; // Last shot of a full target: skip reload+wait, show change target if (newShotsLeft <= 0 && _fullTarget) { _stopTimer(); _showChangeTargetOverlay(); return; } // Single shot or more shots remaining: play full reload+wait sequence if (hasReload) { setState(() { _showFlash = true; _flashColor = Colors.orange; _isReloadPhase = true; _remaining = _reloadSeconds!; }); _flashController.forward(from: 0.0); _startReloadProgress(_reloadSeconds!); _tickDown(); } else if (hasWait) { setState(() { _showFlash = true; _flashColor = Colors.red; _isWaitPhase = true; _remaining = _waitSeconds!; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); _tickDown(); } else { // Shoot only if (newShotsLeft <= 0) { _stopTimer(); return; } setState(() { _showFlash = true; _flashColor = _bulletColor; _remaining = _shootSeconds; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); _tickDown(); } } void _showChangeTargetOverlay() { if (!_changeTargetOverlayEnabled) return; setState(() => _showChangeTarget = true); _changeTargetTimer?.cancel(); _changeTargetTimer = Timer(const Duration(seconds: 5), () { if (mounted) setState(() => _showChangeTarget = false); }); } Future _restoreScreenSettings() async { try { await WakelockPlus.disable(); } catch (e) { debugPrint("⚠️ Could not restore screen settings: $e"); } } // --- Timer UI --- Widget _buildTimerButton() { return InkWell( onTap: _timerEnabled && _isRunning ? _stopTimer : _showTimerDialog, onLongPress: _timerEnabled ? _showTimerDialog : null, borderRadius: BorderRadius.circular(8), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), child: Icon( _timerEnabled ? Icons.timer : Icons.timer_outlined, color: Colors.white, size: 26, ), ), ); } Widget _buildCountdownOverlay() { if (!_isRunning) return const SizedBox.shrink(); if (_isWaitPhase) return _buildWaitOverlay(); if (_isReloadPhase) return _buildReloadOverlay(); return _buildShootOverlay(); } // Bullet dots row: filled = remaining, hollow = shot Widget _buildBulletDots(int total, int remaining, {double? size}) { if (total <= 1) return const SizedBox.shrink(); final dotSize = size ?? (total <= 6 ? 18.0 : total <= 8 ? 14.0 : 11.0); final hPad = total <= 6 ? 4.0 : total <= 8 ? 3.0 : 2.0; return Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), decoration: BoxDecoration( color: Colors.black.withValues(alpha: 0.55), borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.white24, width: 1), ), child: Wrap( spacing: hPad * 2, runSpacing: 4, alignment: WrapAlignment.center, children: List.generate(total, (i) { final active = i < remaining; return Container( width: dotSize, height: dotSize, decoration: BoxDecoration( shape: BoxShape.circle, color: active ? Colors.white : Colors.transparent, border: Border.all( color: active ? Colors.white : Colors.white60, width: 2, ), ), ); }), ), ); } // Shared top bar: progress bar + bullet dots centered + time pill on right Widget _buildTopBar({ required Animation progressAnim, required Color barColor, required String timeLabel, required Color timeColor, required IconData timeIcon, }) { final showDots = _fullTarget && _numberOfBullets > 1; return Positioned( top: 0, left: 0, right: 0, child: IgnorePointer( child: Column( children: [ AnimatedBuilder( animation: progressAnim, builder: (_, __) => LinearProgressIndicator( value: (1.0 - progressAnim.value).clamp(0.0, 1.0), minHeight: 5, backgroundColor: Colors.white.withValues(alpha: 0.1), valueColor: AlwaysStoppedAnimation(barColor), ), ), const SizedBox(height: 8), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( children: [ // Left spacer = same width as pill to keep dots truly centered const Expanded(child: SizedBox()), // Bullet dots — centered if (showDots) _buildBulletDots(_numberOfBullets, _shotsLeft), // Right side: pill Expanded( child: Align( alignment: Alignment.centerRight, child: Container( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 4), decoration: BoxDecoration( color: Colors.black.withValues(alpha: 0.55), borderRadius: BorderRadius.circular(20), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(timeIcon, color: timeColor, size: 13), const SizedBox(width: 4), Text( timeLabel, style: TextStyle( color: timeColor, fontSize: 13, fontWeight: FontWeight.bold), ), ], ), ), ), ), ], ), ), ], ), ), ); } // Manual counter dots — shown at top when timer not running Widget _buildManualDotsOverlay() { if (!_showManualCounter || _numberOfBullets <= 1) { return const SizedBox.shrink(); } return Positioned( top: 8, left: 0, right: 0, child: IgnorePointer( child: Center( child: _buildBulletDots(_numberOfBullets, _manualShotsLeft), ), ), ); } // Shoot phase: blue top bar Widget _buildShootOverlay() { return _buildTopBar( progressAnim: _shootProgressController, barColor: Colors.blue, timeLabel: '$_remaining s', timeColor: Colors.blue, timeIcon: Icons.play_circle_outline, ); } // Reload phase: orange top bar + center circle Widget _buildReloadOverlay() { return Positioned.fill( child: Stack( children: [ Positioned.fill( child: IgnorePointer( child: Center( child: SizedBox( width: 160, height: 160, child: Stack( alignment: Alignment.center, children: [ SizedBox.expand( child: CircularProgressIndicator( value: 1.0, strokeWidth: 10, color: Colors.white.withValues(alpha: 0.1), ), ), SizedBox.expand( child: AnimatedBuilder( animation: _reloadProgressController, builder: (_, __) => CircularProgressIndicator( value: (1.0 - _reloadProgressController.value) .clamp(0.0, 1.0), strokeWidth: 10, color: Colors.orange, strokeCap: StrokeCap.round, ), ), ), Container( width: 130, height: 130, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.black.withValues(alpha: 0.6), ), ), Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.refresh, color: Colors.orange, size: 18), const SizedBox(height: 2), Text( '$_remaining', style: const TextStyle( color: Colors.orange, fontSize: 44, fontWeight: FontWeight.bold, height: 1.0, ), ), Text('s', style: TextStyle( color: Colors.orange.withValues(alpha: 0.7), fontSize: 13)), ], ), ], ), ), ), ), ), _buildTopBar( progressAnim: _reloadProgressController, barColor: Colors.orange, timeLabel: '$_remaining s', timeColor: Colors.orange, timeIcon: Icons.refresh, ), ], ), ); } // Wait phase: top bar (dots + time pill) + center circle Widget _buildWaitOverlay() { return Positioned.fill( child: Stack( children: [ // Center wait circle Positioned.fill( child: IgnorePointer( child: Center( child: SizedBox( width: 160, height: 160, child: Stack( alignment: Alignment.center, children: [ SizedBox.expand( child: CircularProgressIndicator( value: 1.0, strokeWidth: 10, color: Colors.white.withValues(alpha: 0.1), ), ), SizedBox.expand( child: AnimatedBuilder( animation: _waitProgressController, builder: (_, __) => CircularProgressIndicator( value: (1.0 - _waitProgressController.value) .clamp(0.0, 1.0), strokeWidth: 10, color: Colors.red, strokeCap: StrokeCap.round, ), ), ), Container( width: 130, height: 130, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.black.withValues(alpha: 0.6), ), ), Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.hourglass_empty, color: Colors.red, size: 18), const SizedBox(height: 2), Text( '$_remaining', style: const TextStyle( color: Colors.red, fontSize: 44, fontWeight: FontWeight.bold, height: 1.0, ), ), Text( 's', style: TextStyle( color: Colors.red.withValues(alpha: 0.7), fontSize: 13, fontWeight: FontWeight.w500, ), ), ], ), ], ), ), ), ), ), // Top bar: dots centered + time pill on right _buildTopBar( progressAnim: _waitProgressController, barColor: Colors.red, timeLabel: '$_remaining s', timeColor: Colors.red, timeIcon: Icons.hourglass_empty, ), ], ), ); } bool get _showManualCounter => _manualCounterEnabled && (!_timerEnabled || (!_fullTarget && _timerEnabled)); void _manualRegisterShot() { if (_manualShotsLeft <= 0) { // Already done — tap resets for next target setState(() => _manualShotsLeft = _numberOfBullets); return; } final newLeft = _manualShotsLeft - 1; setState(() => _manualShotsLeft = newLeft); if (newLeft <= 0) { _showChangeTargetOverlay(); // Don't auto-reset — user taps again to reset } } Widget _buildBottomBarControls() { final showCounter = _showManualCounter; final hasActiveTimer = _timerEnabled && (_shootEnabled || _reloadEnabled || _waitEnabled); final showPlay = hasActiveTimer && !_isRunning; // Timer running: show stop/pause pill only if (hasActiveTimer && _isRunning) { // fall through to pill below } else { if (showCounter && showPlay) { // Combined pill: + on left, play on right return Container( height: 48, decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(24), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ GestureDetector( onTap: _manualRegisterShot, child: Container( width: 64, height: 48, decoration: BoxDecoration( color: _manualShotsLeft <= 0 ? Colors.red : _bulletColor, borderRadius: const BorderRadius.only( topLeft: Radius.circular(24), bottomLeft: Radius.circular(24), ), ), child: Icon( _manualShotsLeft <= 0 ? Icons.refresh : Icons.add, color: Colors.white, size: 26, ), ), ), Container(width: 1, height: 48, color: Colors.white24), GestureDetector( onTap: _startTimer, child: Container( width: 64, height: 48, decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topRight: Radius.circular(24), bottomRight: Radius.circular(24), ), ), child: const Icon(Icons.play_arrow, color: Colors.black, size: 26), ), ), ], ), ); } if (showCounter) { return GestureDetector( onTap: _manualRegisterShot, child: Container( width: 48, height: 48, decoration: BoxDecoration( color: _manualShotsLeft <= 0 ? Colors.red : _bulletColor, shape: BoxShape.circle, ), child: Icon( _manualShotsLeft <= 0 ? Icons.refresh : Icons.add, color: Colors.white, size: 30, ), ), ); } if (showPlay) { return GestureDetector( onTap: _startTimer, child: Container( width: 48, height: 48, decoration: const BoxDecoration( color: Colors.white, shape: BoxShape.circle), child: const Icon(Icons.play_arrow, color: Colors.black, size: 28), ), ); } return const SizedBox.shrink(); } if (!_isRunning) return const SizedBox.shrink(); // Running: pill with stop | pause/resume return Container( height: 44, decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(22), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ GestureDetector( onTap: _stopTimer, child: Container( width: 60, height: 44, decoration: BoxDecoration( color: Colors.red.shade700, borderRadius: const BorderRadius.only( topLeft: Radius.circular(22), bottomLeft: Radius.circular(22), ), ), child: const Icon(Icons.stop, color: Colors.white, size: 22), ), ), Container(width: 1, height: 44, color: Colors.white24), GestureDetector( onTap: _isPaused ? _resumeTimer : _pauseTimer, child: Container( width: 60, height: 44, decoration: BoxDecoration( color: _isPaused ? Colors.orange : Colors.white, borderRadius: const BorderRadius.only( topRight: Radius.circular(22), bottomRight: Radius.circular(22), ), ), child: Icon( _isPaused ? Icons.play_arrow : Icons.pause, color: _isPaused ? Colors.white : Colors.black, size: 22, ), ), ), ], ), ); } void _showTimerDialog() { showCameraSheet( context, builder: (ctx) => _TimerConfigDialog( shootSeconds: _shootSeconds, reloadSeconds: _reloadSecondsRaw, waitSeconds: _waitSecondsRaw, timerEnabled: _timerEnabled, shootEnabled: _shootEnabled, reloadEnabled: _reloadEnabled, waitEnabled: _waitEnabled, bulletColor: _bulletColor, fullTarget: _fullTarget, changeTargetEnabled: _changeTargetOverlayEnabled, numberOfBullets: _numberOfBullets, onChangeTargetToggle: (v) async { setState(() => _changeTargetOverlayEnabled = v); final prefs = await SharedPreferences.getInstance(); await prefs.setBool('showChangeTargetOverlay', v); }, onConfirm: (shoot, reload, reloadOn, wait, waitOn, fullTarget) { setState(() { _shootSeconds = shoot > 0 ? shoot : _shootSeconds; _shootEnabled = shoot > 0; _reloadSecondsRaw = reload; _waitSecondsRaw = wait; _reloadEnabled = reloadOn; _waitEnabled = waitOn; _reloadSeconds = reloadOn ? reload : null; _waitSeconds = waitOn ? wait : null; _fullTarget = fullTarget; _timerEnabled = _shootEnabled || _reloadEnabled || _waitEnabled; if (!_timerEnabled) _stopTimer(); }); _saveTimerPrefs(); }, translateFn: _t, ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("${_t('Camera')} ${widget.title}"), backgroundColor: Colors.grey[900], foregroundColor: Colors.white, leading: IconButton( icon: const Icon(Icons.arrow_back, color: Colors.white), onPressed: () => Navigator.pop(context), ), actions: [ IconButton( icon: const Icon(Icons.info_outline_rounded, color: Colors.white), onPressed: _showHelpDialog, ), const SizedBox(width: 16), ], ), backgroundColor: Colors.black, body: Stack( children: [ LayoutBuilder( builder: (context, constraints) { return Center( child: (_isError || _streamUrl == null) ? _buildErrorContent() : InteractiveViewer( clipBehavior: Clip.hardEdge, constrained: false, boundaryMargin: EdgeInsets.zero, minScale: 1.0, maxScale: 5.0, transformationController: _transformationController, child: SizedBox( width: constraints.maxWidth, height: constraints.maxHeight, child: RepaintBoundary( child: ColorFiltered( colorFilter: _image.colorFilter, child: RotatedBox( quarterTurns: _image.quarterTurns, child: Mjpeg( key: ValueKey(_streamUrl), stream: _streamUrl!, isLive: true, fit: BoxFit.contain, error: (context, error, stackTrace) { // Mark as error so we can display error placeholder outside filters WidgetsBinding.instance .addPostFrameCallback((_) { if (mounted) { setState(() { _isError = true; }); } }); return SizedBox.expand( child: Container(color: Colors.black), ); }, ), ), ), ), ), ), ); }, ), _buildManualDotsOverlay(), _buildCountdownOverlay(), // Phase-change flash overlay if (_showFlash) Positioned.fill( child: FadeTransition( opacity: _flashAnimation, child: Container(color: _flashColor.withValues(alpha: 0.5)), ), ), // Change target overlay if (_showChangeTarget) Positioned.fill( child: IgnorePointer( child: Center( child: Container( padding: const EdgeInsets.symmetric( horizontal: 36, vertical: 28), decoration: BoxDecoration( color: Colors.black.withValues(alpha: 0.88), borderRadius: BorderRadius.circular(24), border: Border.all(color: Colors.green.shade400, width: 2), boxShadow: [ BoxShadow( color: Colors.green.withValues(alpha: 0.3), blurRadius: 24, spreadRadius: 2), ], ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Stack( alignment: Alignment.center, children: [ Icon(Icons.article_outlined, color: Colors.green.shade300, size: 72), Positioned( bottom: 0, right: 0, child: Container( padding: const EdgeInsets.all(4), decoration: const BoxDecoration( color: Colors.black, shape: BoxShape.circle), child: Icon(Icons.check_circle, color: Colors.green.shade400, size: 24), ), ), ], ), const SizedBox(height: 16), Text( _t('Change target!'), textAlign: TextAlign.center, style: TextStyle( color: Colors.green.shade300, fontSize: 26, fontWeight: FontWeight.bold, letterSpacing: 0.5, ), ), ], ), ), ), ), ), ], ), bottomNavigationBar: BottomAppBar( color: Colors.grey[900], child: SizedBox( height: 64, child: Row( children: [ // Left - Bullet count + Timer config Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ const SizedBox(width: 8), InkWell( onTap: _showBulletDialog, borderRadius: BorderRadius.circular(8), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 4), child: Text( '$_numberOfBullets', style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), _buildTimerButton(), ], ), ), // Center - Play/Stop/Pause controls if (!_isError) _buildBottomBarControls(), // Right - Counter toggle + Image settings Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ // Counter toggle — hidden when timer is full target if (!(_timerEnabled && _fullTarget)) InkWell( onTap: () async { setState(() { _manualCounterEnabled = !_manualCounterEnabled; if (_manualCounterEnabled) { _manualShotsLeft = _numberOfBullets; } }); final prefs = await SharedPreferences.getInstance(); await prefs.setBool( 'manualCounterEnabled', _manualCounterEnabled); }, borderRadius: BorderRadius.circular(8), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 4, vertical: 4), child: Icon( _manualCounterEnabled ? Icons.circle : Icons.circle_outlined, color: Colors.white, size: 24, ), ), ), IconButton( icon: const Icon(Icons.tune, color: Colors.white, size: 24), onPressed: _showImageSettingsDialog, ), ], ), ), ], ), ), ), ); } Widget _buildErrorContent() { return Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(24), child: Container( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32), decoration: BoxDecoration( color: Colors.grey[900], borderRadius: BorderRadius.circular(16), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.error, color: _bulletColor, size: 100), const SizedBox(height: 24), Text( _t("Unable to load camera stream"), style: const TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 24), Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(8), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _t("Please ensure:"), style: const TextStyle( color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600, ), ), const SizedBox(height: 12), Row( children: [ const Icon(Icons.wifi, color: Colors.white, size: 18), const SizedBox(width: 12), Expanded( child: Text( _t("WiFi is enabled"), style: const TextStyle( color: Colors.white70, fontSize: 14, ), ), ), ], ), const SizedBox(height: 12), Row( children: [ // Mobile data can stay on: the app pins camera traffic to Wi-Fi const Icon(Icons.videocam_outlined, color: Colors.white, size: 18), const SizedBox(width: 12), Expanded( child: Text( _t("Cameras and PC are switched on"), style: const TextStyle( color: Colors.white70, fontSize: 14, ), ), ), ], ), ], ), ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 48, child: ElevatedButton.icon( onPressed: _loadStreamUrl, icon: const Icon(Icons.refresh, size: 20), label: Text(_t("Reload")), style: ElevatedButton.styleFrom( backgroundColor: _bulletColor, foregroundColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), ), ), ], ), ), ), ), ); } } class _TimerConfigDialog extends StatefulWidget { final int shootSeconds; final int? reloadSeconds; final int? waitSeconds; final bool timerEnabled; final bool shootEnabled; final bool reloadEnabled; final bool waitEnabled; final bool fullTarget; final Color bulletColor; final int numberOfBullets; final bool changeTargetEnabled; final void Function(int shoot, int? reload, bool reloadOn, int? wait, bool waitOn, bool fullTarget) onConfirm; final void Function(bool) onChangeTargetToggle; final String Function(String) translateFn; const _TimerConfigDialog({ required this.shootSeconds, required this.reloadSeconds, required this.waitSeconds, required this.timerEnabled, required this.shootEnabled, required this.reloadEnabled, required this.waitEnabled, required this.fullTarget, required this.changeTargetEnabled, required this.bulletColor, required this.numberOfBullets, required this.onConfirm, required this.onChangeTargetToggle, required this.translateFn, }); @override State<_TimerConfigDialog> createState() => _TimerConfigDialogState(); } class _TimerConfigDialogState extends State<_TimerConfigDialog> { late int _shoot; late int _reload; late int _wait; bool _shootEnabled = false; bool _reloadEnabled = false; bool _waitEnabled = false; late bool _fullTarget; bool _targetSelected = true; late bool _changeTargetEnabled; static const int _minSeconds = 5; static const int _maxSeconds = 300; static const int _step = 5; @override void initState() { super.initState(); _shoot = _clamp(widget.shootSeconds > 0 ? widget.shootSeconds : 30); _reload = _clamp(widget.reloadSeconds != null ? widget.reloadSeconds! : 15); _wait = _clamp(widget.waitSeconds != null ? widget.waitSeconds! : 30); _shootEnabled = widget.timerEnabled && widget.shootEnabled; _reloadEnabled = widget.timerEnabled && widget.reloadEnabled; _waitEnabled = widget.timerEnabled && widget.waitEnabled; _fullTarget = widget.fullTarget; _targetSelected = widget.timerEnabled; _changeTargetEnabled = widget.changeTargetEnabled; } int _clamp(int v) => (((v / _step).round() * _step).clamp(_minSeconds, _maxSeconds)); String _t(String key) => widget.translateFn(key); void _notify() { widget.onConfirm( _shootEnabled ? _shoot : 0, _reload, _reloadEnabled, _wait, _waitEnabled, _targetSelected ? _fullTarget : false, ); } String _label(int s) { if (s < 60) return '${s}s'; final m = s ~/ 60; final rem = s % 60; return rem == 0 ? '${m}m' : '${m}m ${rem}s'; } Widget _buildToggleRow( String label, IconData icon, Color color, bool enabled, void Function(bool) onToggle, int value, VoidCallback onDec, VoidCallback onInc) { return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Icon(icon, color: enabled ? color : Colors.white38, size: 18), const SizedBox(width: 8), Text(label, style: TextStyle( color: enabled ? Colors.white : Colors.white38, fontSize: 15)), ], ), Switch( value: enabled, activeThumbColor: color, onChanged: onToggle, ), ], ), if (enabled) ...[ const SizedBox(height: 4), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const SizedBox(width: 26), _stepBtn(Icons.remove, onDec), SizedBox( width: 72, child: Text( _label(value), textAlign: TextAlign.center, style: TextStyle( color: color, fontSize: 22, fontWeight: FontWeight.bold), ), ), _stepBtn(Icons.add, onInc), const SizedBox(width: 26), ], ), const SizedBox(height: 8), ], ], ); } Widget _buildAlwaysOnRow(String label, IconData icon, Color color, int value, VoidCallback onDec, VoidCallback onInc) { return Column( children: [ Row( children: [ Icon(icon, color: color, size: 18), const SizedBox(width: 8), Text(label, style: const TextStyle(color: Colors.white, fontSize: 15)), ], ), const SizedBox(height: 4), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const SizedBox(width: 26), _stepBtn(Icons.remove, onDec), SizedBox( width: 72, child: Text( _label(value), textAlign: TextAlign.center, style: TextStyle( color: color, fontSize: 22, fontWeight: FontWeight.bold), ), ), _stepBtn(Icons.add, onInc), const SizedBox(width: 26), ], ), const SizedBox(height: 8), ], ); } Widget _stepBtn(IconData icon, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(8), child: Container( width: 40, height: 40, decoration: BoxDecoration( color: Colors.white10, borderRadius: BorderRadius.circular(8)), child: Icon(icon, color: Colors.white, size: 20), ), ); } Widget _buildTargetPill(bool fullTarget) { final c = widget.bulletColor; final selected = _targetSelected && _fullTarget == fullTarget; final label = fullTarget ? _t('Full target') : _t('Single shot'); final icon = fullTarget ? Icons.filter_none : Icons.looks_one_outlined; return Expanded( child: GestureDetector( onTap: () { setState(() { if (_targetSelected && _fullTarget == fullTarget) { _targetSelected = false; } else { _targetSelected = true; _fullTarget = fullTarget; if (fullTarget) _shootEnabled = true; } }); _notify(); }, child: AnimatedContainer( duration: const Duration(milliseconds: 150), padding: const EdgeInsets.symmetric(vertical: 10), decoration: BoxDecoration( color: selected ? c.withValues(alpha: 0.15) : Colors.white10, borderRadius: BorderRadius.circular(10), border: Border.all( color: selected ? c : Colors.transparent, width: 1.5), ), child: Column( children: [ Icon(icon, color: selected ? c : Colors.white38, size: 20), const SizedBox(height: 4), Text(label, style: TextStyle( color: selected ? c : Colors.white38, fontSize: 11, fontWeight: selected ? FontWeight.bold : FontWeight.normal, )), ], ), ), ), ); } @override Widget build(BuildContext context) { final c = widget.bulletColor; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ CameraSheetHeader( title: _t('Shooting Timer'), icon: Icons.timer, iconColor: c, ), // Single / Full target Row( children: [ _buildTargetPill(false), const SizedBox(width: 8), _buildTargetPill(true), ], ), const SizedBox(height: 12), const Divider(color: Colors.white12, height: 4), const SizedBox(height: 8), // Shoot time — always on in full target, toggleable in single shot if (_targetSelected && _fullTarget) _buildAlwaysOnRow( _t('Shoot time'), Icons.play_circle_outline, Colors.blue, _shoot, () { setState(() { if (_shoot > _minSeconds) _shoot -= _step; }); _notify(); }, () { setState(() { if (_shoot < _maxSeconds) _shoot += _step; }); _notify(); }, ) else _buildToggleRow( _t('Shoot time'), Icons.play_circle_outline, Colors.blue, _shootEnabled, (v) { setState(() => _shootEnabled = v); _notify(); }, _shoot, () { setState(() { if (_shoot > _minSeconds) _shoot -= _step; }); _notify(); }, () { setState(() { if (_shoot < _maxSeconds) _shoot += _step; }); _notify(); }, ), const Divider(color: Colors.white12, height: 4), const SizedBox(height: 8), // Reload toggle + stepper _buildToggleRow( _t('Reload time'), Icons.refresh, Colors.orange, _reloadEnabled, (v) { setState(() => _reloadEnabled = v); _notify(); }, _reload, () { setState(() { if (_reload > _minSeconds) _reload -= _step; }); _notify(); }, () { setState(() { if (_reload < _maxSeconds) _reload += _step; }); _notify(); }, ), const Divider(color: Colors.white12, height: 4), const SizedBox(height: 8), // Wait toggle + stepper _buildToggleRow( _t('Wait time'), Icons.hourglass_empty, Colors.red, _waitEnabled, (v) { setState(() => _waitEnabled = v); _notify(); }, _wait, () { setState(() { if (_wait > _minSeconds) _wait -= _step; }); _notify(); }, () { setState(() { if (_wait < _maxSeconds) _wait += _step; }); _notify(); }, ), const Divider(color: Colors.white12, height: 12), const SizedBox(height: 4), // Change target overlay toggle Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Icon(Icons.article_outlined, color: _changeTargetEnabled ? Colors.green : Colors.white38, size: 18), const SizedBox(width: 8), Text(_t('Change target sign'), style: TextStyle( color: _changeTargetEnabled ? Colors.white : Colors.white38, fontSize: 15)), ], ), Switch( value: _changeTargetEnabled, activeThumbColor: Colors.green, onChanged: (v) { setState(() => _changeTargetEnabled = v); widget.onChangeTargetToggle(v); }, ), ], ), ], ); } }