From 9a65ff7ad4fa3106615a5477e5af52e737f0f90c Mon Sep 17 00:00:00 2001 From: bl3kunja Date: Sun, 25 Oct 2026 17:46:55 +0100 Subject: [PATCH] calendar fix and update. --- android/app/src/main/AndroidManifest.xml | 2 + lib/main.dart | 2 + lib/screens/book_screen.dart | 9 +- lib/screens/calendar_screen.dart | 1522 ++++--------- lib/screens/home_screen.dart | 2 +- lib/screens/settings_screen.dart | 3 +- lib/screens/stream_screen.dart | 2533 +++++++++++++++++----- lib/screens/target_view.dart | 37 +- lib/services/notification_service.dart | 55 +- lib/utils/translations.dart | 82 + 10 files changed, 2596 insertions(+), 1651 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c3fadf5..5d70e81 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -6,6 +6,8 @@ + + with WidgetsBindingObserver { Map> _groupedFiles = {}; // Files grouped by folder Map _folderCreationDates = {}; // Folder creation dates Map _folderScores = {}; // Folder scores (sum of scores of all target files inside) + Map _fileScores = {}; // Per-file score cache to avoid sync reads in build Color _bulletColor = Colors.blue; // default fallback Map _folderTypes = {}; // true = tournament, false = training String _folderFilter = 'all'; @@ -136,6 +137,7 @@ Color _getColorFromName(String colorName) { Map folderDates = {}; Map folderScores = {}; Map folderTypes = {}; + Map fileScores = {}; for (var folder in folders) { String folderName = folder.path.split('/').last; @@ -177,7 +179,9 @@ Color _getColorFromName(String colorName) { for (var file in targetFiles) { final jsonString = await file.readAsString(); final data = jsonDecode(jsonString); - totalScore += _getScoreFromJson(data); + final score = _getScoreFromJson(data); + fileScores[file.path] = score; + totalScore += score; } groupedFiles[folderName] = targetFiles; @@ -201,6 +205,7 @@ Color _getColorFromName(String colorName) { _folderTypes = { for (var name in sortedFolderNames) name: folderTypes[name]! }; + _fileScores = fileScores; }); } catch (e) { debugPrint("Error loading target data files: $e"); @@ -782,7 +787,7 @@ Widget _buildTargetsList(String folderName) { children: targetFiles.asMap().entries.map((entry) { final index = entry.key; final file = entry.value; - final score = _getScoreFromJson(jsonDecode(file.readAsStringSync())); + final score = _fileScores[file.path] ?? 0; final fileName = "${_t('Target')} ${index + 1}"; return Container( diff --git a/lib/screens/calendar_screen.dart b/lib/screens/calendar_screen.dart index e25db66..a24688d 100644 --- a/lib/screens/calendar_screen.dart +++ b/lib/screens/calendar_screen.dart @@ -26,9 +26,9 @@ class Contact { } enum EventType { - regular, // Dežurstvo and other regular events - competition, // Liga and Tekmovanje (League and Competition events) - sestanek, // Meetings + regular, + competition, + sestanek, } class CalendarScreen extends StatefulWidget { @@ -46,10 +46,8 @@ class _CalendarScreenState extends State { String _bulletColor = 'Blue'; String _selectedLanguage = 'English'; bool _showContacts = false; - bool _showDebugPreview = false; late Color _backgroundColor; - // Members contact list final List _contacts = [ Contact(firstName: 'Domen', lastName: 'Pleterski', phone: '051227764', email: 'info@bl3k.com'), Contact(firstName: 'Ivan', lastName: 'Tandler', phone: '040471258', email: 'ivan.tandler@gmail.com'), @@ -71,8 +69,7 @@ class _CalendarScreenState extends State { @override void initState() { super.initState(); - initializeDateFormatting('sl_SI', null); // Initialize Slovenian locale - // Initialize with default target background color + initializeDateFormatting('sl_SI', null); _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); _loadBulletColor(); _loadLanguage(); @@ -80,29 +77,17 @@ class _CalendarScreenState extends State { _loadEvents(); } - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } + String _t(String key) => AppTranslations.translate(key, _selectedLanguage); Future _loadLanguage() async { final prefs = await SharedPreferences.getInstance(); - setState(() { - _selectedLanguage = prefs.getString('language') ?? 'English'; - }); + setState(() => _selectedLanguage = prefs.getString('language') ?? 'English'); } Future _loadSelectedTargetColor() async { final prefs = await SharedPreferences.getInstance(); final selectedTarget = prefs.getString('selectedTarget') ?? 'assets/target.png'; - setState(() { - _backgroundColor = TargetColors.getBackgroundColor(selectedTarget); - }); - } - - void _toggleDebugPreview() { - setState(() { - _showDebugPreview = !_showDebugPreview; - }); + setState(() => _backgroundColor = TargetColors.getBackgroundColor(selectedTarget)); } @override @@ -113,70 +98,38 @@ class _CalendarScreenState extends State { Future _loadBulletColor() async { final prefs = await SharedPreferences.getInstance(); - setState(() { - _bulletColor = prefs.getString('bulletColor') ?? 'Blue'; - }); + setState(() => _bulletColor = prefs.getString('bulletColor') ?? 'Blue'); } Color _getAccentColor() { switch (_bulletColor.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 'orange': - 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; + 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 'orange': 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; } } bool _isValidEvent(CalendarEvent event) { - // Filter out events with empty summaries - if (event.summary == null || event.summary!.trim().isEmpty) { - return false; - } - - final summary = event.summary!.trim(); - - // Only exclude very short single-character entries - // This allows short event names like "Meeting", "Training", etc. - if (summary.length < 2) { - return false; - } - - return true; + if (event.summary == null || event.summary!.trim().isEmpty) return false; + return event.summary!.trim().length >= 2; } EventType? _getEventType(CalendarEvent event) { if (event.summary == null) return null; - final summary = event.summary!.toLowerCase(); - if (summary.contains('liga') || summary.contains('tekmovanje') || summary.contains('tekma')) { return EventType.competition; } else if (summary.contains('sestanek')) { @@ -184,8 +137,6 @@ class _CalendarScreenState extends State { } else if (summary.contains('dežurstvo')) { return EventType.regular; } - - // No matching keywords - skip this event return null; } @@ -201,24 +152,14 @@ class _CalendarScreenState extends State { endDate: DateTime.now().add(const Duration(days: 365)), ); - // Get today's date at midnight for comparison final now = DateTime.now(); final today = DateTime(now.year, now.month, now.day); - // Filter: valid events AND matching keywords AND events from today onwards final filteredEvents = events.where((event) { if (!_isValidEvent(event)) return false; - - // Check if event has a matching keyword type if (_getEventType(event) == null) return false; - - // Only include events that are today or in the future if (event.startTime != null) { - final eventDate = DateTime( - event.startTime!.year, - event.startTime!.month, - event.startTime!.day, - ); + final eventDate = DateTime(event.startTime!.year, event.startTime!.month, event.startTime!.day); return eventDate.isAtSameMomentAs(today) || eventDate.isAfter(today); } return false; @@ -231,16 +172,12 @@ class _CalendarScreenState extends State { }); if (mounted) { - setState(() { - _events = filteredEvents; - }); + setState(() => _events = filteredEvents); } NotificationService().scheduleEventNotifications(filteredEvents); } catch (e) { if (mounted) { - setState(() { - _errorMessage = 'Error loading events: $e'; - }); + setState(() => _errorMessage = 'Error loading events: $e'); } } finally { if (mounted) { @@ -250,10 +187,7 @@ class _CalendarScreenState extends State { } Future _makePhoneCall(String phoneNumber) async { - final Uri launchUri = Uri( - scheme: 'tel', - path: phoneNumber, - ); + final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber); try { await launchUrl(launchUri); } catch (e) { @@ -284,7 +218,6 @@ class _CalendarScreenState extends State { void _showContactPopup(BuildContext context, Contact contact) { final accentColor = _getAccentColor(); - showModalBottomSheet( context: context, backgroundColor: Colors.grey[900], @@ -299,7 +232,6 @@ class _CalendarScreenState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - // Header with contact name Padding( padding: const EdgeInsets.only(bottom: 20), child: Row( @@ -314,159 +246,29 @@ class _CalendarScreenState extends State { child: Center( child: Text( contact.firstName[0].toUpperCase(), - style: const TextStyle( - color: Colors.white, - fontSize: 24, - fontWeight: FontWeight.bold, - ), + style: const TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold), ), ), ), const SizedBox(width: 16), Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _capitalize(contact.fullName), - style: const TextStyle( - color: Colors.white, - fontSize: 18, - fontWeight: FontWeight.bold, - ), - ), - ], + child: Text( + _capitalize(contact.fullName), + style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), ), ), ], ), ), - - // Phone number row - Container( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), - decoration: BoxDecoration( - color: Colors.grey[850], - borderRadius: BorderRadius.circular(10), - ), - child: Row( - children: [ - Icon(Icons.phone, color: accentColor, size: 20), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _t('Phone'), - style: const TextStyle( - color: Colors.grey, - fontSize: 11, - ), - ), - Text( - contact.phone, - style: const TextStyle( - color: Colors.white, - fontSize: 14, - fontWeight: FontWeight.w600, - ), - ), - ], - ), - ), - Container( - decoration: BoxDecoration( - color: accentColor, - borderRadius: BorderRadius.circular(8), - ), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - _copyToClipboard(contact.phone, 'Phone number'); - Navigator.pop(context); - }, - borderRadius: BorderRadius.circular(8), - child: const Padding( - padding: EdgeInsets.all(8), - child: Icon( - Icons.content_copy, - color: Colors.white, - size: 18, - ), - ), - ), - ), - ), - ], - ), - ), - + _buildContactDetailRow(accentColor, Icons.phone, _t('Phone'), contact.phone, () { + _copyToClipboard(contact.phone, 'Phone number'); + Navigator.pop(context); + }), const SizedBox(height: 12), - - // Email row - Container( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), - decoration: BoxDecoration( - color: Colors.grey[850], - borderRadius: BorderRadius.circular(10), - ), - child: Row( - children: [ - Icon(Icons.email, color: accentColor, size: 20), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _t('Email'), - style: const TextStyle( - color: Colors.grey, - fontSize: 11, - ), - ), - Text( - contact.email.toLowerCase(), - style: const TextStyle( - color: Colors.white, - fontSize: 14, - fontWeight: FontWeight.w600, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ], - ), - ), - Container( - decoration: BoxDecoration( - color: accentColor, - borderRadius: BorderRadius.circular(8), - ), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - _copyToClipboard(contact.email, 'Email address'); - Navigator.pop(context); - }, - borderRadius: BorderRadius.circular(8), - child: const Padding( - padding: EdgeInsets.all(8), - child: Icon( - Icons.content_copy, - color: Colors.white, - size: 18, - ), - ), - ), - ), - ), - ], - ), - ), + _buildContactDetailRow(accentColor, Icons.email, _t('Email'), contact.email.toLowerCase(), () { + _copyToClipboard(contact.email, 'Email address'); + Navigator.pop(context); + }), ], ), ), @@ -475,15 +277,49 @@ class _CalendarScreenState extends State { ); } + Widget _buildContactDetailRow(Color accentColor, IconData icon, String label, String value, VoidCallback onCopy) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), + decoration: BoxDecoration(color: Colors.grey[850], borderRadius: BorderRadius.circular(10)), + child: Row( + children: [ + Icon(icon, color: accentColor, size: 20), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: const TextStyle(color: Colors.grey, fontSize: 11)), + Text(value, style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600), maxLines: 1, overflow: TextOverflow.ellipsis), + ], + ), + ), + Container( + decoration: BoxDecoration(color: accentColor, borderRadius: BorderRadius.circular(8)), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: onCopy, + borderRadius: BorderRadius.circular(8), + child: const Padding( + padding: EdgeInsets.all(8), + child: Icon(Icons.content_copy, color: Colors.white, size: 18), + ), + ), + ), + ), + ], + ), + ); + } + Widget _buildContactsList() { final accentColor = _getAccentColor(); - return ListView.builder( itemCount: _contacts.length, padding: const EdgeInsets.all(8), itemBuilder: (context, index) { final contact = _contacts[index]; - return GestureDetector( onTap: () => _makePhoneCall(contact.phone), onLongPress: () => _showContactPopup(context, contact), @@ -493,11 +329,7 @@ class _CalendarScreenState extends State { color: Colors.grey[300], borderRadius: BorderRadius.circular(12), boxShadow: [ - BoxShadow( - color: Colors.grey.withValues(alpha: 0.3), - blurRadius: 8, - offset: const Offset(0, 2), - ), + BoxShadow(color: Colors.grey.withValues(alpha: 0.3), blurRadius: 8, offset: const Offset(0, 2)), ], ), child: Stack( @@ -505,115 +337,67 @@ class _CalendarScreenState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // Header bar with bullet color and transparency Container( width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), decoration: BoxDecoration( color: accentColor.withValues(alpha: 0.6), - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), + borderRadius: const BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12)), ), child: Row( children: [ - // White indicator line Container( width: 4, height: 20, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), + decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(2)), ), const SizedBox(width: 12), - // Contact name in white Expanded( child: Text( _capitalize(contact.fullName), - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.bold, - color: Colors.white, - ), + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white), ), ), ], ), ), - // Main content with phone and email info Padding( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row( - children: [ - Icon(Icons.phone, size: 14, color: accentColor), - const SizedBox(width: 6), - Text( - contact.phone, - style: const TextStyle( - fontSize: 12, - color: Colors.black87, - fontWeight: FontWeight.w500, - ), - ), - ], - ), + Row(children: [ + Icon(Icons.phone, size: 14, color: accentColor), + const SizedBox(width: 6), + Text(contact.phone, style: const TextStyle(fontSize: 12, color: Colors.black87, fontWeight: FontWeight.w500)), + ]), const SizedBox(height: 4), - Row( - children: [ - Icon(Icons.email, size: 14, color: accentColor), - const SizedBox(width: 6), - Expanded( - child: Text( - contact.email.toLowerCase(), - style: const TextStyle( - fontSize: 12, - color: Colors.black87, - fontWeight: FontWeight.w500, - ), - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), + Row(children: [ + Icon(Icons.email, size: 14, color: accentColor), + const SizedBox(width: 6), + Expanded( + child: Text(contact.email.toLowerCase(), style: const TextStyle(fontSize: 12, color: Colors.black87, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis), + ), + ]), ], ), ), ], ), - // Phone button on the right (wider now) Positioned( - right: 0, - top: 0, - bottom: 0, + right: 0, top: 0, bottom: 0, child: Container( width: 80, decoration: BoxDecoration( color: accentColor, - borderRadius: const BorderRadius.only( - topRight: Radius.circular(10), - bottomRight: Radius.circular(10), - ), + borderRadius: const BorderRadius.only(topRight: Radius.circular(10), bottomRight: Radius.circular(10)), ), child: Material( color: Colors.transparent, child: InkWell( onTap: () => _makePhoneCall(contact.phone), - borderRadius: const BorderRadius.only( - topRight: Radius.circular(10), - bottomRight: Radius.circular(10), - ), - child: Center( - child: Icon( - Icons.call, - color: Colors.white, - size: 22, - ), - ), + borderRadius: const BorderRadius.only(topRight: Radius.circular(10), bottomRight: Radius.circular(10)), + child: const Center(child: Icon(Icons.call, color: Colors.white, size: 22)), ), ), ), @@ -626,97 +410,329 @@ class _CalendarScreenState extends State { ); } + Color _eventColor(EventType type, Color accentColor) { + switch (type) { + case EventType.competition: return Colors.orange; + case EventType.sestanek: return const Color(0xFFE53935); + case EventType.regular: return accentColor; + } + } + + IconData _eventIcon(EventType type) { + switch (type) { + case EventType.competition: return Icons.emoji_events; + case EventType.sestanek: return Icons.people; + case EventType.regular: return Icons.calendar_today; + } + } + + String _eventBadgeLabel(EventType type) { + switch (type) { + case EventType.competition: return _t('COMPETITION'); + case EventType.sestanek: return _t('MEETING'); + case EventType.regular: return _t('DUTY'); + } + } + + String _timeText(CalendarEvent event) { + final startTime = event.startTime; + if (event.isAllDay || startTime == null || event.endTime == null) return _t('All day'); + return '${DateFormat('HH:mm').format(startTime.toLocal())} – ${DateFormat('HH:mm').format(event.endTime!.toLocal())}'; + } + + Widget _buildEventCard(CalendarEvent event, Color accentColor, {bool highlight = false}) { + final eventType = _getEventType(event); + if (eventType == null) return const SizedBox(); + + final color = _eventColor(eventType, accentColor); + final hasLocation = event.location != null && event.location!.isNotEmpty; + + return RepaintBoundary( + child: Container( + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow(color: Colors.black.withValues(alpha: 0.15), blurRadius: 6, offset: const Offset(0, 2)), + ], + ), + clipBehavior: Clip.antiAlias, + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Type color stripe + Container(width: 5, color: color), + Expanded( + child: Padding( + padding: EdgeInsets.fromLTRB(12, highlight ? 12 : 10, 12, highlight ? 12 : 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _buildTypeChip(_eventIcon(eventType), _eventBadgeLabel(eventType), color), + const Spacer(), + Icon(Icons.access_time, size: 13, color: Colors.grey[700]), + const SizedBox(width: 4), + Text( + _timeText(event), + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.grey[800]), + ), + ], + ), + const SizedBox(height: 8), + Text( + event.summary ?? _t('Untitled Event'), + style: TextStyle( + fontSize: highlight ? 16 : 14, + fontWeight: FontWeight.w700, + color: Colors.grey[900], + ), + ), + if (hasLocation) ...[ + const SizedBox(height: 4), + Row( + children: [ + Icon(Icons.location_on, size: 13, color: Colors.grey[600]), + const SizedBox(width: 4), + Expanded( + child: Text( + event.location!, + style: TextStyle(fontSize: 12, color: Colors.grey[700]), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ], + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildTypeChip(IconData icon, String label, Color color) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 11, color: color), + const SizedBox(width: 4), + Text(label, style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: color, letterSpacing: 0.6)), + ], + ), + ); + } + + Widget _buildSectionHeader(String label, Color dotColor, Color textColor, {String? trailing, Color? trailingColor}) { + return Row( + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle), + ), + const SizedBox(width: 8), + Text(label, style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: textColor, letterSpacing: 1.4)), + if (trailing != null) ...[ + const SizedBox(width: 8), + Expanded( + child: Text( + '· $trailing', + style: TextStyle(fontSize: 12, color: trailingColor ?? textColor), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ], + ); + } + + Widget _buildDateColumn(DateTime date, int daysFromToday, Color accentColor, bool isLight) { + final locale = _selectedLanguage == 'Slovenian' ? 'sl_SI' : 'en_US'; + final relative = daysFromToday == 1 + ? _t('Tomorrow') + : _t('in {n} days').replaceAll('{n}', '$daysFromToday'); + + return SizedBox( + width: 48, + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + DateFormat('EEE', locale).format(date).toUpperCase(), + style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700, color: isLight ? Colors.grey[700] : Colors.grey[400], letterSpacing: 0.8), + ), + Text( + DateFormat('d').format(date), + style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: isLight ? Colors.black87 : Colors.white, height: 1.15), + ), + Text( + relative, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 9, + fontWeight: daysFromToday == 1 ? FontWeight.bold : FontWeight.w500, + color: daysFromToday == 1 ? accentColor : (isLight ? Colors.grey[600] : Colors.grey[500]), + ), + ), + ], + ), + ); + } + + bool _isLightBackground() { + return _backgroundColor.computeLuminance() > 0.4; + } + + Widget _buildCalendarView(Color accentColor) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final locale = _selectedLanguage == 'Slovenian' ? 'sl_SI' : 'en_US'; + final isLight = _isLightBackground(); + final textPrimary = isLight ? Colors.black87 : Colors.white; + final textSecondary = isLight ? Colors.grey[700]! : Colors.grey[400]!; + final textMuted = isLight ? Colors.grey[600]! : Colors.grey[500]!; + + DateTime dayOf(CalendarEvent e) => DateTime(e.startTime!.year, e.startTime!.month, e.startTime!.day); + + final todayEvents = _events.where((e) => e.startTime != null && dayOf(e).isAtSameMomentAs(today)).toList(); + final upcomingEvents = _events.where((e) => e.startTime != null && dayOf(e).isAfter(today)).toList(); + + // Build upcoming list grouped by month, date column shown once per day + final upcomingWidgets = []; + DateTime? lastDay; + for (final e in upcomingEvents) { + final day = dayOf(e); + final isNewMonth = lastDay == null || lastDay.month != day.month || lastDay.year != day.year; + final isNewDay = lastDay == null || !lastDay.isAtSameMomentAs(day); + + if (isNewMonth) { + upcomingWidgets.add(Padding( + padding: EdgeInsets.fromLTRB(16, lastDay == null ? 4 : 18, 16, 8), + child: Text( + DateFormat('LLLL yyyy', locale).format(day).toUpperCase(), + style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, color: textMuted, letterSpacing: 1.5), + ), + )); + } + + upcomingWidgets.add(Padding( + padding: EdgeInsets.fromLTRB(12, isNewDay && !isNewMonth ? 10 : 0, 16, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + isNewDay + ? _buildDateColumn(day, day.difference(today).inDays, accentColor, isLight) + : const SizedBox(width: 48), + const SizedBox(width: 10), + Expanded(child: _buildEventCard(e, accentColor)), + ], + ), + )); + lastDay = day; + } + + return RefreshIndicator( + onRefresh: _loadEvents, + color: accentColor, + child: ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: [ + // TODAY section + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionHeader( + _t('TODAY'), + accentColor, + textPrimary, + trailing: DateFormat('EEEE, d. MMMM', locale).format(now), + trailingColor: textSecondary, + ), + const SizedBox(height: 10), + if (todayEvents.isEmpty) + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 14), + decoration: BoxDecoration( + color: textMuted.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + children: [ + Icon(Icons.event_busy, size: 18, color: textMuted), + const SizedBox(width: 10), + Text(_t('No events today'), style: TextStyle(fontSize: 13, color: textSecondary)), + ], + ), + ) + else + ...todayEvents.map((e) => Padding( + padding: const EdgeInsets.only(bottom: 8), + child: _buildEventCard(e, accentColor, highlight: true), + )), + ], + ), + ), + + if (upcomingEvents.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 10), + child: _buildSectionHeader(_t('UPCOMING'), textMuted, textPrimary), + ), + ...upcomingWidgets, + ], + + if (_events.isEmpty) ...[ + const SizedBox(height: 32), + Center( + child: Column( + children: [ + Icon(Icons.event_available, size: 56, color: textMuted), + const SizedBox(height: 12), + Text(_t('No upcoming events'), style: TextStyle(fontSize: 15, color: textMuted)), + const SizedBox(height: 6), + Text(_t('Pull down to refresh'), style: TextStyle(fontSize: 13, color: textSecondary)), + ], + ), + ), + ], + + const SizedBox(height: 24), + ], + ), + ); + } + @override Widget build(BuildContext context) { final accentColor = _getAccentColor(); - // Debug preview - disabled by default, set _showDebugPreview = true to enable - if (_showDebugPreview) { - return Scaffold( - backgroundColor: Colors.white, - appBar: AppBar( - backgroundColor: Colors.grey[900], - centerTitle: true, - title: const Text( - 'Debug Preview', - style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), - ), - leading: IconButton( - icon: const Icon(Icons.close, color: Colors.white), - onPressed: _toggleDebugPreview, - ), - ), - body: ListView( - padding: const EdgeInsets.all(16), - children: [ - const SizedBox(height: 8), - // Regular event - Text( - 'Regular Event (Dežurstvo)', - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.grey[600], - ), - ), - const SizedBox(height: 8), - _buildSampleEventCard(accentColor, EventType.regular), - const SizedBox(height: 24), - // Competition event - Text( - 'Competition Event (Tekmovanje)', - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.grey[600], - ), - ), - const SizedBox(height: 8), - _buildSampleEventCard(accentColor, EventType.competition), - const SizedBox(height: 24), - // Meeting event - Text( - 'Meeting Event (Sestanek)', - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.grey[600], - ), - ), - const SizedBox(height: 8), - _buildSampleEventCard(accentColor, EventType.sestanek), - const SizedBox(height: 32), - // Other dates section - Text( - 'Other Dates (without emphasis)', - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.grey[600], - ), - ), - const SizedBox(height: 8), - _buildOtherDateEventCard(accentColor, EventType.regular, 'Tomorrow'), - const SizedBox(height: 12), - _buildOtherDateEventCard(accentColor, EventType.competition, 'Next Week'), - const SizedBox(height: 12), - _buildOtherDateEventCard(accentColor, EventType.sestanek, 'In 5 days'), - const SizedBox(height: 24), - ], - ), - ); - } - if (_isLoading && _events.isEmpty) { return Scaffold( - body: Center( - child: CircularProgressIndicator(color: accentColor), - ), + backgroundColor: _backgroundColor, + body: Center(child: CircularProgressIndicator(color: accentColor)), ); } if (_errorMessage != null && _events.isEmpty) { return Scaffold( + backgroundColor: _backgroundColor, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -725,21 +741,14 @@ class _CalendarScreenState extends State { const SizedBox(height: 24), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), - child: Text( - _errorMessage!, - textAlign: TextAlign.center, - style: const TextStyle(fontSize: 16), - ), + child: Text(_errorMessage!, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16, color: Colors.white70)), ), const SizedBox(height: 16), ElevatedButton.icon( onPressed: _loadEvents, icon: const Icon(Icons.refresh), label: Text(_t('Retry')), - style: ElevatedButton.styleFrom( - backgroundColor: accentColor, - foregroundColor: Colors.white, - ), + style: ElevatedButton.styleFrom(backgroundColor: accentColor, foregroundColor: Colors.white), ), ], ), @@ -751,712 +760,55 @@ class _CalendarScreenState extends State { backgroundColor: _backgroundColor, body: Column( children: [ - // Tab buttons + // Tab bar Container( - padding: const EdgeInsets.all(6), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), decoration: BoxDecoration( color: Colors.grey[900], - border: Border( - bottom: BorderSide(color: Colors.grey[800]!, width: 1), - ), ), child: Row( children: [ - Expanded( - child: GestureDetector( - onTap: () { - setState(() { - _showContacts = false; - }); - }, - child: Container( - padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8), - decoration: BoxDecoration( - color: !_showContacts ? Colors.white : Colors.transparent, - borderRadius: BorderRadius.circular(10), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.calendar_month, - color: !_showContacts ? Colors.black : Colors.grey[400], - size: 18, - ), - const SizedBox(width: 6), - Text( - _t('Calendar'), - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: !_showContacts ? Colors.black : Colors.grey[400], - ), - ), - ], - ), - ), - ), - ), + _buildTab(_t('Calendar'), Icons.calendar_month, !_showContacts, () => setState(() => _showContacts = false)), const SizedBox(width: 6), - Expanded( - child: GestureDetector( - onTap: () { - setState(() { - _showContacts = true; - }); - }, - child: Container( - padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8), - decoration: BoxDecoration( - color: _showContacts ? Colors.white : Colors.transparent, - borderRadius: BorderRadius.circular(10), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.people, - color: _showContacts ? Colors.black : Colors.grey[400], - size: 18, - ), - const SizedBox(width: 6), - Text( - _t('Contacts'), - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: _showContacts ? Colors.black : Colors.grey[400], - ), - ), - ], - ), - ), - ), - ), - if (_showDebugPreview) ...[ - const SizedBox(width: 6), - GestureDetector( - onTap: _toggleDebugPreview, - child: Container( - padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12), - decoration: BoxDecoration( - color: Colors.grey[800], - borderRadius: BorderRadius.circular(10), - border: Border.all(color: Colors.amber, width: 1), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.bug_report, - color: Colors.amber, - size: 16, - ), - const SizedBox(width: 4), - const Text( - 'Debug', - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.w600, - color: Colors.amber, - ), - ), - ], - ), - ), - ), - ], + _buildTab(_t('Contacts'), Icons.people, _showContacts, () => setState(() => _showContacts = true)), ], ), ), - // Body content + // Body Expanded( child: _showContacts ? _buildContactsList() - : RefreshIndicator( - onRefresh: _loadEvents, - color: accentColor, - child: _events.isEmpty - ? ListView( - children: [ - const SizedBox(height: 24), - Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.event_available, size: 64, color: Colors.grey[400]), - const SizedBox(height: 16), - Text( - _t('No upcoming events'), - style: const TextStyle(fontSize: 16, color: Colors.grey), - ), - const SizedBox(height: 8), - Text( - _t('Pull down to refresh'), - style: TextStyle(fontSize: 14, color: Colors.grey[400]), - ), - ], - ), - ), - const SizedBox(height: 32), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Text( - _t('Example Event Preview'), - style: TextStyle( - fontSize: 18, - fontWeight: FontWeight.bold, - color: Colors.grey[700], - ), - textAlign: TextAlign.center, - ), - ), - const SizedBox(height: 16), - _buildSampleEventCard(accentColor, EventType.regular), - const SizedBox(height: 8), - _buildSampleEventCard(accentColor, EventType.competition), - const SizedBox(height: 8), - _buildSampleEventCard(accentColor, EventType.sestanek), - ], - ) - : ListView.builder( - itemCount: _events.length, - padding: const EdgeInsets.all(8), - itemBuilder: (context, index) { - final event = _events[index]; - return _buildEventCard(event, accentColor); - }, - ), - ), + : _buildCalendarView(accentColor), ), ], ), ); } - Widget _buildSampleEventCard(Color accentColor, EventType eventType) { - // Color coding for each event type - Color cardAccentColor; - Color backgroundColor = Colors.grey[300]!; - IconData eventIcon; - String title; - String time; - - switch (eventType) { - case EventType.competition: - cardAccentColor = Colors.orange; - eventIcon = Icons.emoji_events; - title = _t('League / Competition'); - time = '09:00 - 18:00'; - break; - case EventType.sestanek: - cardAccentColor = Colors.red; - eventIcon = Icons.groups; - title = _t('Team Meeting'); - time = '18:00 - 19:00'; - break; - case EventType.regular: - cardAccentColor = accentColor; - eventIcon = Icons.event; - title = _t('Duty Shift'); - time = '14:00 - 16:00'; - break; - } - - return RepaintBoundary( - child: Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), - decoration: BoxDecoration( - color: backgroundColor, - borderRadius: BorderRadius.circular(12), - boxShadow: [ - // Strong glow effect for today's events (sample is always today) - BoxShadow( - color: cardAccentColor.withValues(alpha: 0.4), - blurRadius: 20, - offset: const Offset(0, 6), - ), - // Subtle inner shadow - BoxShadow( - color: Colors.grey.withValues(alpha: 0.1), - blurRadius: 4, - offset: const Offset(0, 2), - ), - ], - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Date header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: cardAccentColor, - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - // Small white indicator line - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 8), - Text( - _t('Today'), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - const Spacer(), - // Event type badge - filled badges for all types - Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), - decoration: BoxDecoration( - color: cardAccentColor, - borderRadius: BorderRadius.circular(12), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(eventIcon, size: 12, color: Colors.white), - const SizedBox(width: 4), - Text( - eventType == EventType.competition - ? _t('TEKMOWANIE') - : eventType == EventType.sestanek - ? _t('SESTANEK') - : _t('DEŽURSTVO'), - style: const TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: Colors.white, - letterSpacing: 0.8, - ), - ), - ], - ), - ), - ], - ), + Widget _buildTab(String label, IconData icon, bool active, VoidCallback onTap) { + return Expanded( + child: GestureDetector( + onTap: onTap, + child: Container( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8), + decoration: BoxDecoration( + color: active ? Colors.white : Colors.transparent, + borderRadius: BorderRadius.circular(10), ), - // Main content - Padding( - padding: const EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Title with icon - Row( - children: [ - Icon(eventIcon, size: 20, color: cardAccentColor), - const SizedBox(width: 8), - Expanded( - child: Text( - title, - style: const TextStyle( - fontSize: 15, - fontWeight: FontWeight.w600, - color: Colors.black87, - ), - ), - ), - ], - ), - const SizedBox(height: 8), - // Time range - _buildDetailRowInline( - icon: Icons.access_time, - value: time, - accentColor: cardAccentColor, - ), - ], - ), - ), - ], - ), - ), - ); - } - - Widget _buildOtherDateEventCard(Color accentColor, EventType eventType, String dateLabel) { - // Color coding for each event type - Color cardAccentColor; - Color backgroundColor = Colors.grey[300]!; - IconData eventIcon; - String title; - String time; - - switch (eventType) { - case EventType.competition: - cardAccentColor = Colors.orange; - eventIcon = Icons.emoji_events; - title = _t('League / Competition'); - time = '09:00 - 18:00'; - break; - case EventType.sestanek: - cardAccentColor = Colors.red; - eventIcon = Icons.groups; - title = _t('Team Meeting'); - time = '18:00 - 19:00'; - break; - case EventType.regular: - cardAccentColor = accentColor; - eventIcon = Icons.event; - title = _t('Duty Shift'); - time = '14:00 - 16:00'; - break; - } - - return RepaintBoundary( - child: Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), - decoration: BoxDecoration( - color: backgroundColor, - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Date header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: cardAccentColor.withValues(alpha: 0.7), - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - // Small white indicator line - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 8), - Text( - dateLabel, - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - const Spacer(), - // Event type badge - Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), - decoration: BoxDecoration( - color: cardAccentColor, - borderRadius: BorderRadius.circular(12), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(eventIcon, size: 12, color: Colors.white), - const SizedBox(width: 4), - Text( - eventType == EventType.competition - ? _t('TEKMOVANJE') - : eventType == EventType.sestanek - ? _t('SESTANEK') - : _t('DEŽURSTVO'), - style: const TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: Colors.white, - letterSpacing: 0.8, - ), - ), - ], - ), - ), - ], - ), - ), - // Main content - Padding( - padding: const EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Title with icon - Row( - children: [ - Icon(eventIcon, size: 20, color: cardAccentColor), - const SizedBox(width: 8), - Expanded( - child: Text( - title, - style: const TextStyle( - fontSize: 15, - fontWeight: FontWeight.w600, - color: Colors.black87, - ), - ), - ), - ], - ), - const SizedBox(height: 8), - // Time range - _buildDetailRowInline( - icon: Icons.access_time, - value: time, - accentColor: cardAccentColor, - ), - ], - ), - ), - ], - ), - ), - ); - } - - Widget _buildEventCard(CalendarEvent event, Color accentColor) { - final startTime = event.startTime; - final isAllDay = event.isAllDay; - final eventType = _getEventType(event); - - // Color coding for each event type - Color cardAccentColor; - Color backgroundColor; - IconData eventIcon; - - switch (eventType) { - case EventType.competition: - cardAccentColor = Colors.orange; - backgroundColor = Colors.grey[300]!; - eventIcon = Icons.emoji_events; // Trophy icon for competitions - break; - case EventType.sestanek: - cardAccentColor = Colors.red; - backgroundColor = Colors.grey[300]!; - eventIcon = Icons.groups; // People icon for meetings - break; - case EventType.regular: - cardAccentColor = accentColor; - backgroundColor = Colors.grey[300]!; - eventIcon = Icons.event; - break; - case null: - // This case should never happen due to filtering, but required by compiler - return const SizedBox(); - } - - // Format the date for display - String dateText = ''; - bool isToday = false; - if (startTime != null) { - final now = DateTime.now(); - final today = DateTime(now.year, now.month, now.day); - final eventDay = DateTime(startTime.year, startTime.month, startTime.day); - final difference = eventDay.difference(today).inDays; - - if (difference == 0) { - dateText = _t('Today'); - isToday = true; - } else if (difference == 1) { - dateText = _t('Tomorrow'); - } else { - // Use locale based on selected language - final locale = _selectedLanguage == 'Slovenian' ? 'sl_SI' : 'en_US'; - dateText = DateFormat('EEEE, MMMM d', locale).format(startTime); - // Capitalize first letter of day and month - if (dateText.isNotEmpty) { - dateText = dateText[0].toUpperCase() + dateText.substring(1); - } - } - } - - return RepaintBoundary( - child: Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), - decoration: BoxDecoration( - color: backgroundColor, - borderRadius: BorderRadius.circular(12), - boxShadow: [ - // Strong glow effect only for today's events - if (isToday) ...[ - BoxShadow( - color: cardAccentColor.withValues(alpha: 0.4), - blurRadius: 20, - offset: const Offset(0, 6), - ), - BoxShadow( - color: Colors.grey.withValues(alpha: 0.1), - blurRadius: 4, - offset: const Offset(0, 2), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, color: active ? Colors.black : Colors.grey[400], size: 18), + const SizedBox(width: 6), + Text( + label, + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: active ? Colors.black : Colors.grey[400]), ), ], - ], + ), ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Date header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: isToday ? cardAccentColor : cardAccentColor.withValues(alpha: 0.7), - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - // Small white indicator line - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 8), - Text( - dateText, - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - const Spacer(), - // Event type badge - filled badges for all types - Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), - decoration: BoxDecoration( - color: cardAccentColor, - borderRadius: BorderRadius.circular(12), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(eventIcon, size: 12, color: Colors.white), - const SizedBox(width: 4), - Text( - eventType == EventType.competition - ? _t('TEKMOVANJE') - : eventType == EventType.sestanek - ? _t('SESTANEK') - : _t('DEŽURSTVO'), - style: const TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: Colors.white, - letterSpacing: 0.8, - ), - ), - ], - ), - ), - ], - ), - ), - // Main content - Padding( - padding: const EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Title with icon - Row( - children: [ - Icon(eventIcon, size: 20, color: cardAccentColor), - const SizedBox(width: 8), - Expanded( - child: Text( - event.summary ?? _t('Untitled Event'), - style: TextStyle( - fontSize: 15, - fontWeight: FontWeight.w600, - color: Colors.black87, - ), - ), - ), - ], - ), - const SizedBox(height: 8), - // Time range (if not all day) - if (!isAllDay && startTime != null && event.endTime != null) ...[ - _buildDetailRowInline( - icon: Icons.access_time, - value: '${DateFormat('HH:mm').format(startTime.toLocal())} - ${DateFormat('HH:mm').format(event.endTime!.toLocal())}', - accentColor: cardAccentColor, - ), - const SizedBox(height: 6), - ], - if (isAllDay) ...[ - _buildDetailRowInline( - icon: Icons.access_time, - value: _t('All day'), - accentColor: cardAccentColor, - ), - const SizedBox(height: 6), - ], - // Location - if (event.location != null && event.location!.isNotEmpty) ...[ - _buildDetailRowInline( - icon: Icons.location_on, - value: event.location!, - accentColor: cardAccentColor, - ), - ], - ], - ), - ), - ], - ), ), ); } - - Widget _buildDetailRowInline({ - required IconData icon, - required String value, - required Color accentColor, - }) { - return Row( - children: [ - Icon(icon, size: 16, color: accentColor), - const SizedBox(width: 6), - Expanded( - child: Text( - value, - style: const TextStyle( - fontSize: 13, - color: Colors.black87, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ); - } - } diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index c6ba113..988225c 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -133,7 +133,7 @@ class _HomeScreenState extends State { padding: const EdgeInsets.only(right: 16.0), child: Center( child: Text( - 'V1.1', + 'V1.2', style: TextStyle( color: Colors.grey[400], fontSize: 12, diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index e9995ff..ddbe238 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -50,7 +50,6 @@ class _SettingsScreenState extends State { bool _notifyDezuranje = true; bool _notifySestanek = true; bool _notifyTekma = true; - String _selectedLanguage = 'English'; final List> _languages = [ {'code': 'en', 'name': 'English', 'flag': '🇬🇧'}, @@ -229,11 +228,13 @@ String _getTargetDisplayName(String targetPath) { await prefs.setInt('notificationHours_single', hours); await prefs.setStringList('notificationHours', [hours.toString()]); setState(() => _notificationHours = hours); + NotificationService().rescheduleFromCalendar(); } Future _saveNotifyType(String key, bool value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(key, value); + NotificationService().rescheduleFromCalendar(); } Future _loadCameraIPs() async { diff --git a/lib/screens/stream_screen.dart b/lib/screens/stream_screen.dart index ffdb8ff..986c61e 100644 --- a/lib/screens/stream_screen.dart +++ b/lib/screens/stream_screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart' show compute, Uint8List; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:screenshot/screenshot.dart'; @@ -11,7 +13,35 @@ import 'preview_screen.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import '../utils/translations.dart'; -enum ImageFilterType { none, greyscale, invert} +enum ImageFilterType { none, greyscale, invert } + +// Top-level: runs in background isolate via compute() +Uint8List _processStreamImage(List args) { + final bytes = args[0] as Uint8List; + final filter = args[1] as int; // ImageFilterType.index + final decoded = img.decodeImage(bytes)!; + final w = decoded.width, h = decoded.height; + final size = w < h ? w : h; + img.Image cropped = img.copyCrop(decoded, + x: (w - size) ~/ 2, y: (h - size) ~/ 2, width: size, height: size); + img.Image processed; + if (filter == ImageFilterType.greyscale.index) { + processed = img.grayscale(cropped); + } else if (filter == ImageFilterType.invert.index) { + final result = img.Image.from(cropped); + for (int y = 0; y < result.height; y++) { + for (int x = 0; x < result.width; x++) { + final p = result.getPixel(x, y); + result.setPixelRgb( + x, y, 255 - p.r.toInt(), 255 - p.g.toInt(), 255 - p.b.toInt()); + } + } + processed = result; + } else { + processed = cropped; + } + return Uint8List.fromList(img.encodeJpg(processed)); +} class CameraStreamScreen extends StatefulWidget { final int cameraIndex; @@ -22,48 +52,144 @@ class CameraStreamScreen extends StatefulWidget { State createState() => _CameraStreamScreenState(); } -class _CameraStreamScreenState extends State with SingleTickerProviderStateMixin { +class _CameraStreamScreenState extends State + with TickerProviderStateMixin { String? _streamUrl; bool _isError = false; bool _isCapturing = false; final ScreenshotController _screenshotController = ScreenshotController(); - final TransformationController _transformationController = TransformationController(); + final TransformationController _transformationController = + TransformationController(); ImageFilterType _selectedFilter = ImageFilterType.none; - late YOLODetector _yoloDetector; int _numberOfBullets = 5; // Brightness and contrast controls - double _brightness = 0.0; // -1.0 to 1.0 - double _contrast = 1.0; // 0.0 to 2.0 + double _brightness = 0.0; + double _contrast = 1.0; late AnimationController _zoomAnimController; Animation? _zoomAnimation; Matrix4? _originalMatrix; - Color _bulletColor = Colors.blue; // default/fallback bullet color + 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; + + Future _loadAllPrefs() async { + final prefs = await SharedPreferences.getInstance(); + final filterIndex = prefs.getInt('selectedFilter'); + final url = 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'; + _numberOfBullets = prefs.getInt('bulletCount') ?? 5; + _selectedFilter = (filterIndex != null && + filterIndex >= 0 && + filterIndex < ImageFilterType.values.length) + ? ImageFilterType.values[filterIndex] + : ImageFilterType.none; + _bulletColor = + _getColorFromName(prefs.getString('bulletColor') ?? 'Blue'); + _brightness = prefs.getDouble('brightness') ?? 0.0; + _contrast = prefs.getDouble('contrast') ?? 1.0; + _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(); - _loadLanguage(); - _loadStreamUrl(); - _loadBulletCount(); - _loadSelectedFilter(); - _loadBulletColor(); // 👈 add this to actually load the saved bullet color - _loadBrightnessContrast(); - + _loadAllPrefs(); YOLODetector.create().then((detector) => _yoloDetector = detector); - _setSystemBarStyle(); // 👈 set colors - SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); // 👈 show bars + _setSystemBarStyle(); + SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); _keepScreenAwake(); @@ -71,13 +197,24 @@ class _CameraStreamScreenState extends State with SingleTick vsync: this, duration: const Duration(milliseconds: 200), ); - } - Future _loadBrightnessContrast() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _brightness = prefs.getDouble('brightness') ?? 0.0; - _contrast = prefs.getDouble('contrast') ?? 1.0; + _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); + } }); } @@ -87,78 +224,52 @@ class _CameraStreamScreenState extends State with SingleTick await prefs.setDouble('contrast', _contrast); } - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _selectedLanguage = prefs.getString('language') ?? 'English'; - }); + 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 + } } - Future _loadBulletColor() async { - final prefs = await SharedPreferences.getInstance(); - final selected = prefs.getString('bulletColor') ?? 'Blue'; - setState(() { - _bulletColor = _getColorFromName(selected); - }); -} - -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, - ), - ); -} - - Future _loadSelectedFilter() async { - final prefs = await SharedPreferences.getInstance(); - final index = prefs.getInt('selectedFilter'); - if (index != null && index >= 0 && index < ImageFilterType.values.length) { - setState(() { - _selectedFilter = ImageFilterType.values[index]; - }); - } + SystemChrome.setSystemUIOverlayStyle( + SystemUiOverlayStyle( + statusBarColor: Colors.grey[900], // ✅ match your AppBar + statusBarIconBrightness: Brightness.light, // white icons + systemNavigationBarColor: Colors.grey[900], + systemNavigationBarIconBrightness: Brightness.light, + ), + ); } Future _keepScreenAwake() async { @@ -181,135 +292,100 @@ Color _getColorFromName(String colorName) { }); } - Future _loadBulletCount() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _numberOfBullets = prefs.getInt('bulletCount') ?? 5; - }); - } - Future _captureAndPreviewImage() async { - if (_streamUrl == null || _isCapturing) return; + if (_streamUrl == null || _isCapturing) return; - setState(() => _isCapturing = true); - _originalMatrix = _transformationController.value; + setState(() => _isCapturing = true); + _originalMatrix = _transformationController.value; - try { - final targetMatrix = Matrix4.identity()..scale(1.0); - final isZoomedIn = !_matrixEquals(_originalMatrix!, targetMatrix); + try { + final targetMatrix = Matrix4.identity()..scale(1.0); + final isZoomedIn = !_matrixEquals(_originalMatrix!, targetMatrix); - if (isZoomedIn) { + if (isZoomedIn) { + _zoomAnimController.reset(); + _zoomAnimation = Matrix4Tween( + begin: _originalMatrix, + end: targetMatrix, + ).animate(CurvedAnimation( + parent: _zoomAnimController, + curve: Curves.easeOut, + )); + + void updateZoom() { + _transformationController.value = _zoomAnimation!.value; + } + + _zoomAnimController.addListener(updateZoom); + await _zoomAnimController.forward(); + _zoomAnimController.removeListener(updateZoom); + } + + await Future.delayed(const Duration(milliseconds: 100)); + final imageBytes = await _screenshotController.capture(); + if (imageBytes == null || imageBytes.isEmpty) return; + + final dir = await getApplicationDocumentsDirectory(); + final path = '${dir.path}/ip_capture_temp.jpg'; + + final processedBytes = await compute( + _processStreamImage, [imageBytes, _selectedFilter.index]); + final file = File(path)..writeAsBytesSync(processedBytes); + + // Detect objects in the image using YOLO + final detections = await _yoloDetector.detect(file); + + if (!mounted) return; + + // Navigate to the preview screen + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => PreviewScreen( + imagePath: file.path, + detections: detections, + bulletCount: _numberOfBullets, + ), + ), + ); + } catch (e) { + debugPrint("❌ Capture error: $e"); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Capture failed: $e")), + ); + } + } finally { _zoomAnimController.reset(); _zoomAnimation = Matrix4Tween( - begin: _originalMatrix, - end: targetMatrix, + begin: _transformationController.value, + end: _originalMatrix!, ).animate(CurvedAnimation( parent: _zoomAnimController, - curve: Curves.easeOut, + curve: Curves.easeIn, )); - void updateZoom() { + void restoreZoom() { _transformationController.value = _zoomAnimation!.value; } - _zoomAnimController.addListener(updateZoom); + _zoomAnimController.addListener(restoreZoom); await _zoomAnimController.forward(); - _zoomAnimController.removeListener(updateZoom); + _zoomAnimController.removeListener(restoreZoom); + + setState(() => _isCapturing = false); } - - await Future.delayed(const Duration(milliseconds: 100)); - final imageBytes = await _screenshotController.capture(); - if (imageBytes == null || imageBytes.isEmpty) return; - - final decoded = img.decodeImage(imageBytes); - - if (decoded == null) return; - final width = decoded.width; - final height = decoded.height; - final size = width < height ? width : height; - final offsetX = (width - size) ~/ 2; - final offsetY = (height - size) ~/ 2; - final cropped = img.copyCrop(decoded, x: offsetX, y: offsetY, width: size, height: size); - - // Debugging: log the selected filter - debugPrint("📸 Selected filter: $_selectedFilter"); - - // Create the output directory and path - final dir = await getApplicationDocumentsDirectory(); - final path = '${dir.path}/ip_capture_temp.jpg'; - img.Image processed = cropped; - - // Apply the selected filter - switch (_selectedFilter) { - case ImageFilterType.greyscale: - processed = img.grayscale(cropped); - break; - - case ImageFilterType.invert: - processed = invertImage(cropped); // ✅ use your custom invert function - break; - case ImageFilterType.none: - break; - } - - // Save the processed image to a file - final file = File(path)..writeAsBytesSync(img.encodeJpg(processed)); - - // Detect objects in the image using YOLO - final detections = await _yoloDetector.detect(file); - - if (!mounted) return; - - // Navigate to the preview screen - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => PreviewScreen( - imagePath: file.path, - detections: detections, - bulletCount: _numberOfBullets, - ), - ), - ); - } catch (e) { - debugPrint("❌ Capture error: $e"); - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text("Capture failed: $e")), - ); - } - } finally { - _zoomAnimController.reset(); - _zoomAnimation = Matrix4Tween( - begin: _transformationController.value, - end: _originalMatrix!, - ).animate(CurvedAnimation( - parent: _zoomAnimController, - curve: Curves.easeIn, - )); - - void restoreZoom() { - _transformationController.value = _zoomAnimation!.value; - } - - _zoomAnimController.addListener(restoreZoom); - await _zoomAnimController.forward(); - _zoomAnimController.removeListener(restoreZoom); - - setState(() => _isCapturing = false); } -} - img.Image invertImage(img.Image source) { - final result = img.Image.from(source); - for (int y = 0; y < result.height; y++) { - for (int x = 0; x < result.width; x++) { - final pixel = result.getPixel(x, y); - result.setPixelRgb(x, y, 255 - pixel.r, 255 - pixel.g, 255 - pixel.b); + final result = img.Image.from(source); + for (int y = 0; y < result.height; y++) { + for (int x = 0; x < result.width; x++) { + final pixel = result.getPixel(x, y); + result.setPixelRgb(x, y, 255 - pixel.r, 255 - pixel.g, 255 - pixel.b); + } } - } - return result; + return result; } bool _matrixEquals(Matrix4 a, Matrix4 b) { @@ -319,132 +395,234 @@ Color _getColorFromName(String colorName) { return true; } - void _showBulletDialog() { + void _showImageSettingsDialog() { showDialog( context: context, builder: (BuildContext context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), // Increased padding for better spacing - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: 16.0), - child: Text( - _t('Select the number of bullets'), - textAlign: TextAlign.center, - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, + return StatefulBuilder( + builder: (context, setDialogState) { + return Dialog( + backgroundColor: Colors.grey[900], + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + _t('Image Settings'), + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold), + ), + IconButton( + icon: const Icon(Icons.close, color: Colors.white), + onPressed: () => Navigator.of(context).pop(), + ), + ], ), - ), - ), - Center( - child: Wrap( - alignment: WrapAlignment.center, - spacing: 12, - runSpacing: 12, - children: List.generate(5, (index) { - final bulletNum = index + 1; - final isSelected = _numberOfBullets == bulletNum; - return ElevatedButton( + const SizedBox(height: 16), + Text( + '${_t('Brightness')}: ${(_brightness * 100).toInt()}', + style: + const TextStyle(color: Colors.white70, fontSize: 14), + ), + Slider( + value: _brightness, + min: -1.0, + max: 1.0, + divisions: 40, + activeColor: _bulletColor, + onChanged: (value) { + setState(() => _brightness = value); + setDialogState(() {}); + _saveBrightnessContrast(); + }, + ), + Text( + '${_t('Contrast')}: ${(_contrast * 100).toInt()}%', + style: + const TextStyle(color: Colors.white70, fontSize: 14), + ), + Slider( + value: _contrast, + min: 0.5, + max: 2.0, + divisions: 30, + activeColor: _bulletColor, + onChanged: (value) { + setState(() => _contrast = value); + setDialogState(() {}); + _saveBrightnessContrast(); + }, + ), + const SizedBox(height: 8), + Text( + _t('Filter'), + style: + const TextStyle(color: Colors.white70, fontSize: 14), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: ImageFilterType.values.map((f) { + final isSelected = _selectedFilter == f; + final label = f.toString().split('.').last; + final translatedLabel = + _t(label[0].toUpperCase() + label.substring(1)); + return GestureDetector( + onTap: () async { + setState(() => _selectedFilter = f); + setDialogState(() {}); + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt('selectedFilter', f.index); + }, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: + isSelected ? _bulletColor : Colors.grey[800], + borderRadius: BorderRadius.circular(20), + ), + child: Text( + translatedLabel, + style: const TextStyle( + color: Colors.white, fontSize: 13), + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 16), + Align( + alignment: Alignment.centerRight, + child: TextButton( onPressed: () { - _selectBulletCount(bulletNum); - Navigator.of(context).pop(); + setState(() { + _brightness = 0.0; + _contrast = 1.0; + }); + setDialogState(() {}); + _saveBrightnessContrast(); }, - style: ElevatedButton.styleFrom( - backgroundColor: - isSelected ? _bulletColor : Colors.grey[800], - foregroundColor: Colors.white, - padding: - const EdgeInsets.symmetric(horizontal: 20, vertical: 12), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text( - '$bulletNum', - style: TextStyle( - fontSize: 18, - fontWeight: - isSelected ? FontWeight.bold : FontWeight.normal, - ), - ), - ); - }), - ), + child: Text(_t('Reset'), + style: const TextStyle(color: Colors.white54)), + ), + ), + ], ), - ], - ), - ), + ), + ); + }, ); }, ); } - void _showFilterDialog() { - showDialog( - context: context, - builder: (BuildContext context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _t('Choose a Filter'), - style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), - ), - const SizedBox(height: 16), - Wrap( - spacing: 12, - runSpacing: 12, - alignment: WrapAlignment.center, - children: ImageFilterType.values.map((f) { - final isSelected = _selectedFilter == f; - final label = f.toString().split('.').last; - final translatedLabel = _t(label[0].toUpperCase() + label.substring(1)); - return ElevatedButton( - onPressed: () async { - setState(() { - _selectedFilter = f; - }); - final prefs = await SharedPreferences.getInstance(); - await prefs.setInt('selectedFilter', f.index); // Save filter index - if (context.mounted) { - Navigator.of(context).pop(); - } - }, - style: ElevatedButton.styleFrom( - backgroundColor: isSelected ? _bulletColor : Colors.grey[800], - foregroundColor: Colors.white, - ), - child: Text(translatedLabel), - ); - }).toList(), - ), - ], - ), - ), - ); - }, - ); -} + void _showBulletDialog() { + showDialog( + context: context, + builder: (BuildContext context) { + return StatefulBuilder( + builder: (context, setDialogState) { + Future setCount(int count) async { + final clamped = count.clamp(1, 10); + setState(() => _numberOfBullets = clamped); + setDialogState(() {}); + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt('bulletCount', clamped); + } - void _selectBulletCount(int number) async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _numberOfBullets = number; - }); - await prefs.setInt('bulletCount', number); + return Dialog( + backgroundColor: Colors.grey[900], + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _t('Select the number of bullets'), + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold), + ), + const SizedBox(height: 24), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + onPressed: _numberOfBullets > 1 + ? () => setCount(_numberOfBullets - 1) + : null, + icon: const Icon(Icons.remove, + color: Colors.white, size: 28), + style: IconButton.styleFrom( + backgroundColor: _numberOfBullets > 1 + ? Colors.grey[700] + : Colors.grey[850], + shape: const CircleBorder(), + ), + ), + const SizedBox(width: 24), + Text( + '$_numberOfBullets', + style: TextStyle( + fontSize: 48, + fontWeight: FontWeight.bold, + color: _bulletColor, + ), + ), + const SizedBox(width: 24), + IconButton( + onPressed: _numberOfBullets < 10 + ? () => setCount(_numberOfBullets + 1) + : null, + icon: const Icon(Icons.add, + color: Colors.white, size: 28), + style: IconButton.styleFrom( + backgroundColor: _numberOfBullets < 10 + ? Colors.grey[700] + : Colors.grey[850], + shape: const CircleBorder(), + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + '1 – 10', + style: + const TextStyle(color: Colors.white38, fontSize: 12), + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: () => Navigator.of(context).pop(), + style: ElevatedButton.styleFrom( + backgroundColor: _bulletColor, + foregroundColor: Colors.white, + ), + child: Text(_t('Done')), + ), + ], + ), + ), + ); + }, + ); + }, + ); } void _showHelpDialog() { @@ -453,7 +631,8 @@ Color _getColorFromName(String colorName) { builder: (BuildContext context) { return Dialog( backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), child: Padding( padding: const EdgeInsets.all(24.0), child: Column( @@ -462,18 +641,26 @@ Color _getColorFromName(String colorName) { children: [ Text( _t('Help'), - style: const TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold), + style: const TextStyle( + color: Colors.white, + fontSize: 24, + fontWeight: FontWeight.bold), ), const SizedBox(height: 20), - _buildHelpItem(Icons.camera_alt, _t('Tap camera button to capture and detect bullets')), + _buildHelpItem(Icons.timer, + _t('Timer icon: Configure shoot/wait timer and start session')), const SizedBox(height: 12), - _buildHelpItem(Icons.filter_9_plus, _t('Bottom left number: Set expected bullet count (1-5)')), + _buildHelpItem(Icons.filter_9_plus, + _t('Bottom left number: Set expected bullet count (1-5)')), const SizedBox(height: 12), - _buildHelpItem(Icons.brightness_6, _t('Sun icon: Adjust brightness and contrast for better visibility')), + _buildHelpItem(Icons.brightness_6, + _t('Sun icon: Adjust brightness and contrast for better visibility')), const SizedBox(height: 12), - _buildHelpItem(Icons.filter_alt, _t('Filter icon: Apply color filters (None, Greyscale, Invert)')), + _buildHelpItem(Icons.filter_alt, + _t('Filter icon: Apply color filters (None, Greyscale, Invert)')), const SizedBox(height: 12), - _buildHelpItem(Icons.pinch, _t('Pinch to zoom on the camera stream')), + _buildHelpItem( + Icons.pinch, _t('Pinch to zoom on the camera stream')), const SizedBox(height: 20), Center( child: ElevatedButton( @@ -509,126 +696,273 @@ Color _getColorFromName(String colorName) { ); } - void _showBrightnessContrastDialog() { - showDialog( - context: context, - builder: (BuildContext context) { - return StatefulBuilder( - builder: (context, setDialogState) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _t('Brightness & Contrast'), - style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), - ), - const SizedBox(height: 24), - // Brightness slider - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '${_t('Brightness')}: ${(_brightness * 100).toInt()}', - style: const TextStyle(color: Colors.white, fontSize: 16), - ), - Slider( - value: _brightness, - min: -1.0, - max: 1.0, - divisions: 40, - activeColor: _bulletColor, - onChanged: (value) { - setState(() { - _brightness = value; - }); - setDialogState(() {}); - _saveBrightnessContrast(); - }, - ), - ], - ), - const SizedBox(height: 16), - // Contrast slider - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '${_t('Contrast')}: ${(_contrast * 100).toInt()}%', - style: const TextStyle(color: Colors.white, fontSize: 16), - ), - Slider( - value: _contrast, - min: 0.5, - max: 2.0, - divisions: 30, - activeColor: _bulletColor, - onChanged: (value) { - setState(() { - _contrast = value; - }); - setDialogState(() {}); - _saveBrightnessContrast(); - }, - ), - ], - ), - const SizedBox(height: 16), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - ElevatedButton( - onPressed: () { - setState(() { - _brightness = 0.0; - _contrast = 1.0; - }); - setDialogState(() {}); - _saveBrightnessContrast(); - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], - foregroundColor: Colors.white, - ), - child: Text(_t('Reset')), - ), - ElevatedButton( - onPressed: () { - Navigator.of(context).pop(); - }, - style: ElevatedButton.styleFrom( - backgroundColor: _bulletColor, - foregroundColor: Colors.white, - ), - child: Text(_t('Done')), - ), - ], - ), - ], - ), - ), - ); - }, - ); - }, - ); + @override + void dispose() { + _countdownTimer?.cancel(); + _changeTargetTimer?.cancel(); + _shootProgressController.dispose(); + _reloadProgressController.dispose(); + _waitProgressController.dispose(); + _flashController.dispose(); + _zoomAnimController.dispose(); + _yoloDetector.close(); + _restoreScreenSettings(); + _setSystemBarStyle(); + super.dispose(); } - @override -void dispose() { - _zoomAnimController.dispose(); - _yoloDetector.close(); - _restoreScreenSettings(); +// --- Timer logic --- - _setSystemBarStyle(); // restore grey[900] on back + 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; - super.dispose(); -} + 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 { @@ -638,73 +972,675 @@ void dispose() { } } + // --- 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() { + showDialog( + context: 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, + ), + ); + } + ColorFilter _buildColorFilter() { - // Base filter matrix - List baseMatrix; + // Base filter matrix + List baseMatrix; - switch (_selectedFilter) { - case ImageFilterType.greyscale: - baseMatrix = [ - 0.2126, 0.7152, 0.0722, 0, 0, - 0.2126, 0.7152, 0.0722, 0, 0, - 0.2126, 0.7152, 0.0722, 0, 0, - 0, 0, 0, 1, 0, - ]; - break; - case ImageFilterType.invert: - baseMatrix = [ - -1.0, 0.0, 0.0, 0.0, 255.0, - 0.0, -1.0, 0.0, 0.0, 255.0, - 0.0, 0.0, -1.0, 0.0, 255.0, - 0.0, 0.0, 0.0, 1.0, 0.0, - ]; - break; - default: - baseMatrix = [ - 1.0, 0.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 1.0, 0.0, - ]; + switch (_selectedFilter) { + case ImageFilterType.greyscale: + baseMatrix = [ + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + ]; + break; + case ImageFilterType.invert: + baseMatrix = [ + -1.0, + 0.0, + 0.0, + 0.0, + 255.0, + 0.0, + -1.0, + 0.0, + 0.0, + 255.0, + 0.0, + 0.0, + -1.0, + 0.0, + 255.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ]; + break; + default: + baseMatrix = [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ]; + } + + // Apply brightness and contrast adjustments + final b = _brightness * 255.0; // Convert to 0-255 range + final c = _contrast; + + // Combine filter with brightness/contrast + final adjustedMatrix = [ + c, + 0.0, + 0.0, + 0.0, + b, + 0.0, + c, + 0.0, + 0.0, + b, + 0.0, + 0.0, + c, + 0.0, + b, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + ]; + + // Multiply base matrix with adjustment matrix + return ColorFilter.matrix(_multiplyMatrices(baseMatrix, adjustedMatrix)); } - // Apply brightness and contrast adjustments - final b = _brightness * 255.0; // Convert to 0-255 range - final c = _contrast; + List _multiplyMatrices(List a, List b) { + // For simplicity, just apply brightness/contrast on top of base filter + final result = []; - // Combine filter with brightness/contrast - final adjustedMatrix = [ - c, 0.0, 0.0, 0.0, b, - 0.0, c, 0.0, 0.0, b, - 0.0, 0.0, c, 0.0, b, - 0.0, 0.0, 0.0, 1.0, 0.0, - ]; + for (int i = 0; i < a.length; i++) { + result.add(a[i]); + } - // Multiply base matrix with adjustment matrix - return ColorFilter.matrix(_multiplyMatrices(baseMatrix, adjustedMatrix)); -} + // Apply contrast to RGB components + result[0] = result[0] * b[0]; // R + result[6] = result[6] * b[6]; // G + result[12] = result[12] * b[12]; // B -List _multiplyMatrices(List a, List b) { - // For simplicity, just apply brightness/contrast on top of base filter - final result = []; + // Apply brightness + result[4] = result[4] + b[4]; // R offset + result[9] = result[9] + b[9]; // G offset + result[14] = result[14] + b[14]; // B offset - for (int i = 0; i < a.length; i++) { - result.add(a[i]); + return result; } - // Apply contrast to RGB components - result[0] = result[0] * b[0]; // R - result[6] = result[6] * b[6]; // G - result[12] = result[12] * b[12]; // B - - // Apply brightness - result[4] = result[4] + b[4]; // R offset - result[9] = result[9] + b[9]; // G offset - result[14] = result[14] + b[14]; // B offset - - return result; -} - @override Widget build(BuildContext context) { return Scaffold( @@ -754,7 +1690,8 @@ List _multiplyMatrices(List a, List b) { fit: BoxFit.contain, error: (context, error, stackTrace) { // Mark as error so we can display error placeholder outside filters - WidgetsBinding.instance.addPostFrameCallback((_) { + WidgetsBinding.instance + .addPostFrameCallback((_) { if (mounted) { setState(() { _isError = true; @@ -792,32 +1729,95 @@ List _multiplyMatrices(List a, List b) { ), ), ), + _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, + ), + ), + ], + ), + ), + ), + ), + ), ], ), - floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, - floatingActionButton: _isError - ? null - : FloatingActionButton( - backgroundColor: Colors.white, - onPressed: _captureAndPreviewImage, - child: const Icon(Icons.camera_alt, color: Colors.black), - ), bottomNavigationBar: BottomAppBar( - color: Colors.grey[900], - shape: const CircularNotchedRectangle(), - notchMargin: 8.0, - child: SizedBox( - height: 60, - child: Row( - children: [ - // Left - Bullet count (just number) - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: Padding( - padding: const EdgeInsets.only(left: 16.0), - child: InkWell( - onTap: _showBulletDialog, + 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( @@ -828,30 +1828,55 @@ List _multiplyMatrices(List a, List b) { ), ), ), - ), + _buildTimerButton(), + ], ), - // Center space for FAB - const SizedBox(width: 80), - // Right section - Brightness and Filter - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - IconButton( - icon: const Icon(Icons.brightness_6, color: Colors.white, size: 24), - onPressed: _showBrightnessContrastDialog, + ), + // 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.filter_alt, color: Colors.white, size: 24), - onPressed: _showFilterDialog, - ), - ], - ), + IconButton( + icon: + const Icon(Icons.tune, color: Colors.white, size: 24), + onPressed: _showImageSettingsDialog, + ), + ], ), - ], - ), + ), + ], ), ), + ), ); } @@ -881,7 +1906,8 @@ List _multiplyMatrices(List a, List b) { ), const SizedBox(height: 24), Container( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 16), decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(8), @@ -916,7 +1942,8 @@ List _multiplyMatrices(List a, List b) { const SizedBox(height: 12), Row( children: [ - const Icon(Icons.signal_cellular_off, color: Colors.white, size: 18), + const Icon(Icons.signal_cellular_off, + color: Colors.white, size: 18), const SizedBox(width: 12), Expanded( child: Text( @@ -957,3 +1984,433 @@ List _multiplyMatrices(List a, List b) { ); } } + +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 Dialog( + backgroundColor: Colors.grey[900], + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Icon(Icons.timer, color: c, size: 22), + const SizedBox(width: 8), + Text(_t('Shooting Timer'), + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold)), + ], + ), + IconButton( + icon: + const Icon(Icons.close, color: Colors.white54, size: 20), + onPressed: () => Navigator.of(context).pop(), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + const SizedBox(height: 12), + + // 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); + }, + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/target_view.dart b/lib/screens/target_view.dart index 08c7e0c..3089e87 100644 --- a/lib/screens/target_view.dart +++ b/lib/screens/target_view.dart @@ -29,6 +29,7 @@ class _TargetViewScreenState extends State { List _bullets = []; List _scaledBullets = []; // Bullets scaled to display target size int _totalScore = 0; + Map _folderChartScores = {}; Offset? _targetCenter; Uint8List? _targetImageBytes; img.Image? _targetImageDecoded; @@ -256,6 +257,21 @@ class _TargetViewScreenState extends State { .map((b) => _scoreForBullet(b, _targetCenter!)) .fold(0, (sum, score) => sum + score); + // Pre-compute folder chart scores to avoid sync file reads in build + if (widget.isCombinedView) { + final chartScores = {}; + for (int i = 0; i < widget.jsonFiles.length; i++) { + final data = jsonDecode(await widget.jsonFiles[i].readAsString()); + final bullets = (data['bullets'] as List?) ?? []; + int s = 0; + for (final b in bullets) { + s += _scoreForBullet(Offset(b['x'].toDouble(), b['y'].toDouble()), _targetCenter!); + } + chartScores[i + 1] = s; + } + _folderChartScores = chartScores; + } + setState(() {}); } catch (e) { print("Error loading JSON or image: $e"); @@ -565,26 +581,7 @@ class _TargetViewScreenState extends State { } Widget _buildFolderChartView() { - // Calculate target scores from all files - // Each file represents one target at position (fileIndex + 1) - final Map targetScores = {}; - - for (int fileIdx = 0; fileIdx < widget.jsonFiles.length; fileIdx++) { - final file = widget.jsonFiles[fileIdx]; - final targetPosition = fileIdx + 1; // T1, T2, T3, etc. - - final data = jsonDecode(file.readAsStringSync()); - final bullets = (data['bullets'] as List?) ?? []; - - // Sum scores for this target - int targetScore = 0; - for (int j = 0; j < bullets.length; j++) { - final bullet = Offset(bullets[j]['x'].toDouble(), bullets[j]['y'].toDouble()); - final score = _scoreForBullet(bullet, _targetCenter ?? Offset.zero); - targetScore += score; - } - targetScores[targetPosition] = targetScore; - } + final Map targetScores = _folderChartScores; if (targetScores.isEmpty) { return Center( diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 442ddc1..ea2577a 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -62,9 +62,50 @@ class NotificationService { AndroidFlutterLocalNotificationsPlugin>(); await androidPlugin?.createNotificationChannel(_channel); await requestPermissions(); + await _requestExactAlarmsOnce(); } catch (_) {} } + // Android 12+ needs "Alarms & reminders" access for on-time delivery. + // Ask once; without it we fall back to inexact alarms. + Future _requestExactAlarmsOnce() async { + final android = _plugin.resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>(); + if (android == null) return; + if (await android.canScheduleExactNotifications() ?? true) return; + + final prefs = await SharedPreferences.getInstance(); + if (prefs.getBool('exactAlarmAsked') ?? false) return; + await prefs.setBool('exactAlarmAsked', true); + await android.requestExactAlarmsPermission(); + } + + Future _scheduleMode() async { + final android = _plugin.resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>(); + final canExact = await android?.canScheduleExactNotifications() ?? true; + return canExact + ? AndroidScheduleMode.exactAllowWhileIdle + : AndroidScheduleMode.inexactAllowWhileIdle; + } + + /// Fetches the calendar and reschedules all reminders. Call on app start + /// and whenever notification settings change. + Future rescheduleFromCalendar() async { + final service = GoogleCalendarService(); + try { + final now = DateTime.now(); + final events = await service.getEvents( + startDate: now, + endDate: now.add(const Duration(days: 365)), + ); + await scheduleEventNotifications(events); + } catch (_) { + } finally { + service.dispose(); + } + } + Future requestPermissions() async { final android = _plugin.resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>(); @@ -96,6 +137,7 @@ class NotificationService { final notifyTekma = prefs.getBool('notifyTekma') ?? true; final isSlovenian = (prefs.getString('language') ?? 'English') == 'Slovenian'; final now = DateTime.now(); + final mode = await _scheduleMode(); await _plugin.cancelAll(); @@ -104,9 +146,11 @@ class NotificationService { if (event.startTime == null) continue; final summary = (event.summary ?? '').toLowerCase(); - final isCompetition = summary.contains('liga') || summary.contains('tekmovanje'); - final isSestanek = summary.contains('sestanek'); - final isDezuranje = !isCompetition && !isSestanek; + // Same classification as the calendar screen; skip anything else + final isCompetition = summary.contains('liga') || summary.contains('tekmovanje') || summary.contains('tekma'); + final isSestanek = !isCompetition && summary.contains('sestanek'); + final isDezuranje = !isCompetition && !isSestanek && summary.contains('dežurstvo'); + if (!isCompetition && !isSestanek && !isDezuranje) continue; if (isCompetition && !notifyTekma) continue; if (isSestanek && !notifySestanek) continue; @@ -121,6 +165,7 @@ class NotificationService { ? (hours == 1 ? 'Začne se čez 1 uro' : 'Začne se čez $hours ur') : (hours == 1 ? 'Starts in 1 hour' : 'Starts in $hours hours'), scheduledDate: notifyAt, + mode: mode, ); } } @@ -144,6 +189,7 @@ class NotificationService { title: isSlovenian ? 'Načrtovano testno obvestilo' : 'Scheduled Test', body: isSlovenian ? 'Načrtovana obvestila delujejo!' : 'Scheduled notifications are working!', scheduledDate: in10s, + mode: await _scheduleMode(), ); } catch (_) {} } @@ -153,6 +199,7 @@ class NotificationService { required String title, required String body, required DateTime scheduledDate, + required AndroidScheduleMode mode, }) async { final tzDate = tz.TZDateTime.from(scheduledDate, tz.local); await _plugin.zonedSchedule( @@ -161,7 +208,7 @@ class NotificationService { body, tzDate, _notifDetails, - androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle, + androidScheduleMode: mode, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, ); diff --git a/lib/utils/translations.dart b/lib/utils/translations.dart index 111aed2..13db105 100644 --- a/lib/utils/translations.dart +++ b/lib/utils/translations.dart @@ -249,10 +249,26 @@ class AppTranslations { 'English': 'Today', 'Slovenian': 'Danes', }, + 'TODAY': { + 'English': 'TODAY', + 'Slovenian': 'DANES', + }, + 'UPCOMING': { + 'English': 'UPCOMING', + 'Slovenian': 'PRIHAJAJOČE', + }, + 'No events today': { + 'English': 'No events today', + 'Slovenian': 'Danes ni dogodkov', + }, 'Tomorrow': { 'English': 'Tomorrow', 'Slovenian': 'Jutri', }, + 'in {n} days': { + 'English': 'in {n} days', + 'Slovenian': 'čez {n} dni', + }, 'NOW': { 'English': 'NOW', 'Slovenian': 'ZDAJ', @@ -605,6 +621,10 @@ class AppTranslations { 'English': 'Tap camera button to capture and detect bullets', 'Slovenian': 'Tapnite gumb kamere za zajem in zaznavanje zadetkov', }, + 'Timer icon: Configure shoot/wait timer and start session': { + 'English': 'Timer icon: Configure shoot/wait timer and start session', + 'Slovenian': 'Ikona časovnika: Nastavi časovnik strela/čakanja in začni serijo', + }, 'Bottom left number: Set expected bullet count (1-5)': { 'English': 'Bottom left number: Set expected bullet count (1-5)', 'Slovenian': 'Spodaj levo številka: Nastavite število zadetkov (1-5)', @@ -847,6 +867,68 @@ class AppTranslations { 'Slovenian': 'Točke', }, + // Timer Dialog + 'Shooting Timer': { + 'English': 'Shooting Timer', + 'Slovenian': 'Časovnik streljanja', + }, + 'What do you want to time?': { + 'English': 'What do you want to time?', + 'Slovenian': 'Kaj želiš časovno meriti?', + }, + 'Shoot only': { + 'English': 'Shoot only', + 'Slovenian': 'Samo strel', + }, + 'Wait only': { + 'English': 'Wait only', + 'Slovenian': 'Samo čakanje', + }, + 'Both': { + 'English': 'Both', + 'Slovenian': 'Oboje', + }, + 'Shoot time': { + 'English': 'Shoot time', + 'Slovenian': 'Čas strela', + }, + 'Reload time': { + 'English': 'Reload time', + 'Slovenian': 'Čas polnjenja', + }, + 'Wait time': { + 'English': 'Wait time', + 'Slovenian': 'Čas čakanja', + }, + 'Single shot': { + 'English': 'Single shot', + 'Slovenian': 'En strel', + }, + 'Full target': { + 'English': 'Full target', + 'Slovenian': 'Polna tarča', + }, + 'Change target!': { + 'English': 'Change target!', + 'Slovenian': 'Zamenjaj tarčo!', + }, + 'Change target sign': { + 'English': 'Change target sign', + 'Slovenian': 'Znak zamenjave tarče', + }, + 'Bullet counter': { + 'English': 'Bullet counter', + 'Slovenian': 'Števec strelov', + }, + 'Disable': { + 'English': 'Disable', + 'Slovenian': 'Onemogoči', + }, + 'left': { + 'English': 'left', + 'Slovenian': 'ostalo', + }, + // Notifications 'Notifications': { 'English': 'Notifications',