diff --git a/.gitignore b/.gitignore index 79c113f..4cc334f 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,6 @@ app.*.map.json /android/app/debug /android/app/profile /android/app/release + +# Plain club data (contacts) — encrypted into assets/club.enc, never commit +/tool/club_data.json diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 9fed0ee..9139909 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -1,3 +1,6 @@ +import java.util.Properties +import java.io.FileInputStream + plugins { id("com.android.application") id("kotlin-android") @@ -5,8 +8,15 @@ plugins { id("dev.flutter.flutter-gradle-plugin") } +// Upload key for Google Play. android/key.properties is gitignored — never commit it. +val keystoreProperties = Properties() +val keystorePropertiesFile = rootProject.file("key.properties") +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) +} + android { - namespace = "com.example.shooter_app" + namespace = "si.sdkkovinar.app" compileSdk = flutter.compileSdkVersion ndkVersion = "27.0.12077973" // ✅ Keep only this line @@ -22,16 +32,32 @@ android { } defaultConfig { - applicationId = "com.example.shooter_app" - minSdk = 26 - targetSdk = 33 + applicationId = "si.sdkkovinar.app" + minSdk = 26 + targetSdk = 36 versionCode = flutter.versionCode versionName = flutter.versionName } + signingConfigs { + create("release") { + if (keystorePropertiesFile.exists()) { + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["keyPassword"] as String + storeFile = file(keystoreProperties["storeFile"] as String) + storePassword = keystoreProperties["storePassword"] as String + } + } + } + buildTypes { release { - signingConfig = signingConfigs.getByName("debug") + // Falls back to debug key only when key.properties is missing (local testing). + signingConfig = if (keystorePropertiesFile.exists()) { + signingConfigs.getByName("release") + } else { + signingConfigs.getByName("debug") + } isMinifyEnabled = false isShrinkResources = false } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 5d70e81..ea50365 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -11,14 +11,13 @@ + android:networkSecurityConfig="@xml/network_security_config" + android:localeConfig="@xml/locales_config"> + when (call.method) { + "bindToWifi" -> result.success(bindToWifi()) + "unbind" -> { + unbind() + result.success(null) + } + else -> result.notImplemented() + } + } + } + + // The range Wi-Fi has no internet, so Android routes traffic over mobile data + // and the cameras' local IPs become unreachable. Pin this app's traffic to + // Wi-Fi (other apps keep using mobile data). Returns true if bound right away. + private fun bindToWifi(): Boolean { + if (wifiCallback == null) { + val request = NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .build() + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + connectivity.bindProcessToNetwork(network) + } + + override fun onLost(network: Network) { + if (connectivity.boundNetworkForProcess == network) { + connectivity.bindProcessToNetwork(null) + } + } + } + connectivity.registerNetworkCallback(request, callback) + wifiCallback = callback + } + + @Suppress("DEPRECATION") + val wifi = connectivity.allNetworks.firstOrNull { + connectivity.getNetworkCapabilities(it) + ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + } ?: return false + return connectivity.bindProcessToNetwork(wifi) + } + + private fun unbind() { + wifiCallback?.let { connectivity.unregisterNetworkCallback(it) } + wifiCallback = null + connectivity.bindProcessToNetwork(null) + } + + override fun onDestroy() { + unbind() + super.onDestroy() + } +} diff --git a/android/app/src/main/res/xml/locales_config.xml b/android/app/src/main/res/xml/locales_config.xml new file mode 100644 index 0000000..0a6d8b5 --- /dev/null +++ b/android/app/src/main/res/xml/locales_config.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/club.enc b/assets/club.enc new file mode 100644 index 0000000..9c25760 --- /dev/null +++ b/assets/club.enc @@ -0,0 +1 @@ +{"v":1,"salt":"Mrvt+SH25mgmeHSMLSa5MQ==","nonce":"jeM7rMRlbYVFBf/f","cipher":"fjQ0MEjR5SaCvelQ0v3bMMr9s0YbGjTOjFBrFGMVf2f4gsq4fCVlgqFub9nXcsPHIMxwDTr/GXDWRuJQ1afut0XQl9b1jMLrVgL6ELH2mFpIRcyBFCNSgKeyTLOBFbtPvE1zHcBK3HkJtK8vqdjH/3uzf9sWIIBnOi4bzFz6NbBTzLEIU6LkfKOLOTsXx43GpD1EA8j+5F9LFp4FJq4Ap0A5PHxf4IcTOf41FNaNOnbOKLGbOSXCNuGdLy4IFvSeJ3wnnqaTWJXOOnNOA5oWDr2WCEuEm8PfQuHHxdy5b9SmL5cdTe6W6GyEJrruH+ragADiyi6xC+CCkRA3NgIPgm4VyIB9Tg6M9E02NMg05xpwy8DwPar04QFmAfsfJYD/lAFEpi7ZbcJaHgOj0MLpoOHdJInLndPg6mmwtJm3ov2tdUiLDghGx0VzmWFRn659jng853hQm/7AMJ20pg677hTH9hzamf0jmZkln7NTCvesdnhE4T69sJtP+i89k5L/knH2yEBHkID1p8X0GPp9armxZaozdUTbKTRfykKhCC61rAnJCxjCguPK8+GZexBuaJvMNiGj66z6Z3VFE61Dvv1Q17qrhiMK7ZafH4aeiuFUM9thOmxVR5bgmRtfMAb/RgGFn9QG+qupNyQldediUNlM8HT0sIJDgtMA1Xe8fnZ9+psV/TNgO93KsCNm/GyMl9ksRDg/bU6UqQ+LxELSeHzssPKzLWpVdG1dMgtT2bif/rd2W9YIi+FNUhZWV4Y0wjp0TOfUKrrnM4VyMfYnZ6HrYO4TybW55Ub/gBbVZuXocA7g2pnnBBvk9kL6neeR6Fs5fcIhDZrI66dXvL0YYLe9bpYFjWpo1eQCCTGtCpqdcuxi/SIVWcpJMhVB37Iilw/j7YZHLUSlIfDruNwG4nyoVjM/nTjYp5Akd50kS52pN6JuBbHx7aRQ7iyRd9yGTMY1KDOHJ+QS4A10wkTieaEHOMUFNslfxVWdm+mWGAKFpPJRJNmXOvau4Ees0lGlEo9Rdp1aLe0yCz/PZcMiNJWuGWfibsQP/+Z7Tz0Wrw6XiXpdrcOtF2p3MkBXQTlyJwnXTdz7bspuD3Qb0VU4dULn05PpFP67RQGCTRu0/bxrsRyyoRUXveRWUwT9hQzJHr1uUAGYjMXzNgSi+2/sO6J3KR+CvaKAxh2DiGYnHnG4K2u072jLjLiYiRfnKJCIqLGnpNp2Z4IzhMEYFR03BCyQ0vfA6xBDsGE0esu75kLlOkhJv+Ar5s8pbUK/nkciaRS82p8rXwV86NwV53PqEWMo3veVuQaGdGAVnd3pviJ87eaOXV9dChHdoE7x4nJLTKrxZ1cD28vX1Xdpf9JmNfWMiPTwUCH/pO35x4d47PBMKnOexk18+oBqyJStF9pEiBDATTr1KJBZvIF3qo7NHshh1Ams7N9rg5rp2WqZtm2AAmg56GKRx7GogpdT2MwNNtukDUmnSQ2CqOE2JQzrEVMDZB+MMQd0eb7OaD3FXqpX35ZmI8YDmsSUzEyK4Horil44/bfj3Nwf+LgYKSaAkKjw8rJ5DUU7SUsGFScQXsfmRkp4IHpoR7gHsUX7Abq/9KV35ZYu+hcevR3oaOL5vmIqczPbuJaMVuUgLHna/xmqDZG0jD0kc4tRVNR+LQhzXMWuIsla7KMpXQGng9SyZ0srIBCVZNhNKFH05A7MihUoNbnj2/acEJlg4w22nDqV5up3xHFoj6NX2uJoE+xPfUWqNF+yiIU6qU6TbVJcS1DSa1vKRXYCNsQW9t3jU2F1If8sMEwfDg5iMmSouPnWHBT0LyLI6ypnH4MIAyPjb2tWnEPiDxUuZOO/sq4B81AxV0GIKmVH2baGGVlbl+ZnllumN4TB41SpGTxrMyYUJd5uhu+FA8DyW2oe5y7TQ+L9kS0CiwntRKqvU8lycP057ve2Tg2u1ySw9N5OdVFQLnjei/xx6tEqS8Zd0tItV8OrKQPmQ8NqzTwwqlQ34c92anGk1aP+JTdpMOOsAv6QkbMIQg4uxu2GYfLfAhkYjAzRQ7UV7I9I4OkaSmYTHbRkddR0cGICt4w5+SYhGaZ8CMRdqXZYYo1x1nK/bZakkLcDxiW0zR+oHLHIuORZG9Y6msEPsuVRbdOlOVJVoCYQ/mBEEdqBnzD8RF0J4jGPDuJhN/GkICElzq3WRQjrzbjw17oimhfe/QD6yFi25vttiltP2JF0a38t4mpv5O8IQi02H3/E/8zSV9NvXin1RUXXlRnWdTmKROHbwJC4NnvUUBURggkfVNGnYpfxNs6joQLZOr4tpaHAFBIceBMafjXO5rybu2vFPwBErB+mQMbZ37o8MQKtSZBow587IjrTHfwefixurk2RzL/Z+Gk4BwGOhQzn9HSa5g6051PqBjsBwbLdjVdGhhvEUG0I6hPKKTr6nKRnkLoxBbWM0BnPlHmftxqPVcWSOaan7XSTMUF3mVcs0rILt3McRHx3IKEUoLmxot88Un58dDTjg4RIlWRaxdfzNXQEZDPkvpBbjj1/tSc4jhRTgepd8/0PcpN5uFx04GKlPPuOmjxoDFUQxwbD9EdMASsFy1k7Vk2HgWWOuay/w7PVah1mlFXLh9f6O6Q2bDMtuaasTWUl9bqKSu5IbAvgg58LskFZOOlH60UnTa+oWt4nl1aLW9+h5ZywgyYqoBtIlVA246DaTPQ1gMwPODNJxXV2ectRFUYCUvf6/hwPclQ/r7PZRxoSxeL9iSLeh9Ib6Ca+HbX4+pGL0HYbmJuk","mac":"nCVGDv9Ks7x0MIAUGk3Xvg=="} \ No newline at end of file diff --git a/assets/targets/Target13.jpg b/assets/targets/Target13.jpg deleted file mode 100644 index 3a3710a..0000000 Binary files a/assets/targets/Target13.jpg and /dev/null differ diff --git a/devtools_options.yaml b/devtools_options.yaml new file mode 100644 index 0000000..fa0b357 --- /dev/null +++ b/devtools_options.yaml @@ -0,0 +1,3 @@ +description: This file stores settings for Dart & Flutter DevTools. +documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states +extensions: diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 4dd2459..f63d51a 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -5,7 +5,7 @@ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName - Shooter App + SDK Kovinar CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier diff --git a/lib/main.dart b/lib/main.dart index 6d772c6..b8b382b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,10 +1,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; // Import for SystemChrome +import 'package:intl/date_symbol_data_local.dart'; import 'screens/home_screen.dart'; import 'services/notification_service.dart'; +import 'services/app_settings.dart'; +import 'theme/app_theme.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); + await AppSettings.instance.load(); + await initializeDateFormatting(); // Slovenian month/day names for every screen try { await NotificationService().initialize(); } catch (_) {} @@ -23,43 +28,47 @@ void main() async { statusBarColor: Colors.grey[900], systemNavigationBarColor: Colors.grey[900], systemNavigationBarIconBrightness: Brightness.light, + // No grey scrim behind 3-button navigation; we paint the strip ourselves + systemNavigationBarContrastEnforced: false, ), ); runApp(const MyApp()); } - class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( - title: 'SDK Muta', + title: 'SDK Kovinar', debugShowCheckedModeBanner: false, - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.white), - useMaterial3: true, - ), - darkTheme: ThemeData( - colorScheme: ColorScheme.fromSeed( - seedColor: Colors.blue, - brightness: Brightness.dark, - ), - useMaterial3: true, - dialogTheme: DialogThemeData( - backgroundColor: Colors.grey[900], - ), - ), + theme: AppTheme.light(), + darkTheme: AppTheme.dark(), builder: (context, child) { final originalTextScaler = MediaQuery.of(context).textScaler; - final clampedScale = originalTextScaler.clamp(minScaleFactor: 0.8, maxScaleFactor: 1.2); + final clampedScale = + originalTextScaler.clamp(minScaleFactor: 0.8, maxScaleFactor: 1.2); + // Edge-to-edge (Android 15+) ignores the navigation bar color, so paint + // the system bar strip ourselves on every screen, matching our bars. + final systemBar = MediaQuery.viewPaddingOf(context).bottom; return MediaQuery( data: MediaQuery.of(context).copyWith( textScaler: clampedScale, ), - child: child!, + child: Stack( + children: [ + child!, + Positioned( + left: 0, + right: 0, + bottom: 0, + height: systemBar, + child: IgnorePointer(child: ColoredBox(color: AppTheme.bar)), + ), + ], + ), ); }, home: const HomeScreen(), diff --git a/lib/models/camera_setup.dart b/lib/models/camera_setup.dart new file mode 100644 index 0000000..cb7c176 --- /dev/null +++ b/lib/models/camera_setup.dart @@ -0,0 +1,72 @@ +/// Which cameras exist: shooting positions (lanes 1–6) × locations (strelišča). +/// Each position can have a camera at several locations, e.g. "Kovinar" and "Doma". +class CameraSetup { + static const int maxPositions = 6; + static const int firstPort = 9081; + + final List locations; + final int positions; + final Map> ips; // position (1-based) → location → ip:port + final String? activeLocation; // last chosen, used by screens that show one location + final String? clubLocation; // added by the club code, removed when access is removed + + const CameraSetup({ + this.locations = const [], + this.positions = maxPositions, + this.ips = const {}, + this.activeLocation, + this.clubLocation, + }); + + String ipFor(int position, String location) => ips[position]?[location] ?? ''; + + /// Locations with a camera at [position], in the user's location order. + Map camerasAt(int position) => { + for (final l in locations) + if (ipFor(position, l).isNotEmpty) l: ipFor(position, l), + }; + + int camerasIn(String location) => [ + for (int p = 1; p <= positions; p++) + if (ipFor(p, location).isNotEmpty) p, + ].length; + + CameraSetup copyWith({ + List? locations, + int? positions, + Map>? ips, + String? activeLocation, + String? clubLocation, + bool clearClubLocation = false, + }) { + return CameraSetup( + locations: locations ?? this.locations, + positions: positions ?? this.positions, + ips: ips ?? this.ips, + activeLocation: activeLocation ?? this.activeLocation, + clubLocation: clearClubLocation ? null : (clubLocation ?? this.clubLocation), + ); + } + + /// Deep copy of [ips] for editing. + Map> ipsCopy() => {for (final e in ips.entries) e.key: {...e.value}}; + + Map toJson() => { + 'locations': locations, + 'positions': positions, + 'ips': {for (final e in ips.entries) '${e.key}': e.value}, + 'activeLocation': activeLocation, + 'clubLocation': clubLocation, + }; + + factory CameraSetup.fromJson(Map json) => CameraSetup( + locations: [for (final l in json['locations'] as List? ?? []) l as String], + positions: (json['positions'] as int? ?? maxPositions).clamp(1, maxPositions), + ips: { + for (final e in (json['ips'] as Map? ?? {}).entries) + int.parse(e.key): {for (final i in (e.value as Map).entries) i.key as String: i.value as String}, + }, + activeLocation: json['activeLocation'] as String?, + clubLocation: json['clubLocation'] as String?, + ); +} diff --git a/lib/models/contact.dart b/lib/models/contact.dart new file mode 100644 index 0000000..966ecb1 --- /dev/null +++ b/lib/models/contact.dart @@ -0,0 +1,22 @@ +class Contact { + final String firstName; + final String lastName; + final String phone; + final String email; + + const Contact({ + required this.firstName, + required this.lastName, + required this.phone, + required this.email, + }); + + String get fullName => '$firstName $lastName'; + + factory Contact.fromJson(Map json) => Contact( + firstName: json['firstName'] ?? '', + lastName: json['lastName'] ?? '', + phone: json['phone'] ?? '', + email: json['email'] ?? '', + ); +} diff --git a/lib/screens/book_screen.dart b/lib/screens/book_screen.dart index 3051adf..bc8cc9c 100644 --- a/lib/screens/book_screen.dart +++ b/lib/screens/book_screen.dart @@ -1,13 +1,17 @@ -import 'dart:io'; -import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; // For DateFormat -import 'package:path_provider/path_provider.dart'; // For getApplicationDocumentsDirectory -import 'target_view.dart'; // Import the TargetViewScreen -import 'package:shared_preferences/shared_preferences.dart'; -import '../utils/translations.dart'; -import '../utils/target_colors.dart'; +import 'package:intl/intl.dart'; +import '../services/app_settings.dart'; +import '../services/target_repository.dart'; +import '../theme/app_theme.dart'; +import '../widgets/bar_tabs.dart'; +import '../widgets/progress_chart.dart'; +import '../widgets/section.dart'; +import 'session_screen.dart'; +import 'target_view.dart'; +enum _Filter { training, tournament } + +/// Knjiga: one summary card with the shooter's form, then their sessions by month. class BookScreen extends StatefulWidget { const BookScreen({super.key}); @@ -16,1121 +20,709 @@ class BookScreen extends StatefulWidget { } class _BookScreenState extends State 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'; - bool isRenameEnabled = false; - String _sortMode = 'date'; // or 'score' - String _selectedLanguage = 'English'; - String? _expandedFolder; // Track which folder is expanded - late Color _backgroundColor; + static const int _chartSessions = 12; + + List? _sessions; // selected year only; null while loading + List _years = []; + int _year = DateTime.now().year; + _Filter _filter = _Filter.training; + int? _shots; // shots per target shown; null = pick the most common one + bool _sortByScore = false; @override void initState() { super.initState(); - WidgetsBinding.instance.addObserver(this); // Register to listen for lifecycle events - // Initialize with default target background color - _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); - _loadBulletColor(); - _loadLanguage(); - _loadSelectedTargetColor(); - _loadTargetDataFiles(); // Initial load when the screen is first created - } - - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - 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); - }); + WidgetsBinding.instance.addObserver(this); + _load(); } @override void dispose() { - WidgetsBinding.instance.removeObserver(this); // Unregister from lifecycle events when disposed + WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { - super.didChangeAppLifecycleState(state); - if (state == AppLifecycleState.resumed) { - // Reload data when the screen is resumed or comes into view - _loadTargetDataFiles(); + if (state == AppLifecycleState.resumed) _load(); + } + + // Only the selected year's targets are read, which keeps loading quick with years of data + Future _load() async { + final years = await TargetRepository.years(); + final sessions = await TargetRepository.loadSessions(year: _year); + if (mounted) { + setState(() { + _years = years; + _sessions = sessions; + }); } } - 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 '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; // fallback - } -} - - - // Load the target data files from the directory - void _loadTargetDataFiles() async { - try { - final directory = await getApplicationDocumentsDirectory(); - final dataDirectory = Directory('${directory.path}/saved_images'); - - if (!await dataDirectory.exists()) { - await dataDirectory.create(recursive: true); - } - - List folders = dataDirectory.listSync().whereType().toList(); - - Map> groupedFiles = {}; - Map folderDates = {}; - Map folderScores = {}; - Map folderTypes = {}; - Map fileScores = {}; - - for (var folder in folders) { - String folderName = folder.path.split('/').last; - DateTime fallbackDate = folder.statSync().changed; // fallback - - // Read metadata - final metadataFile = File('${folder.path}/metadata.json'); - bool isTournament = false; - DateTime? createdAt; - - if (await metadataFile.exists()) { - try { - final metadata = jsonDecode(await metadataFile.readAsString()); - - isTournament = metadata['isTournament'] == true; - - if (metadata['createdAt'] != null) { - createdAt = DateTime.tryParse(metadata['createdAt']); - } - } catch (e) { - debugPrint("Error reading metadata for $folderName: $e"); - } - } - - // Use createdAt if available, fallback otherwise - folderDates[folderName] = createdAt ?? fallbackDate; - folderTypes[folderName] = isTournament; - - // List target files - List targetFiles = Directory(folder.path) - .listSync() - .whereType() - .where((file) => - file.path.endsWith(".json") && - !file.path.endsWith("metadata.json")) - .toList(); - - int totalScore = 0; - for (var file in targetFiles) { - final jsonString = await file.readAsString(); - final data = jsonDecode(jsonString); - final score = _getScoreFromJson(data); - fileScores[file.path] = score; - totalScore += score; - } - - groupedFiles[folderName] = targetFiles; - folderScores[folderName] = totalScore; - } - - // Sort folders by stored or fallback created date (DESC) - final sortedFolderNames = folderDates.keys.toList() - ..sort((a, b) => folderDates[b]!.compareTo(folderDates[a]!)); - - setState(() { - _groupedFiles = { - for (var name in sortedFolderNames) name: groupedFiles[name]! - }; - _folderCreationDates = { - for (var name in sortedFolderNames) name: folderDates[name]! - }; - _folderScores = { - for (var name in sortedFolderNames) name: folderScores[name]! - }; - _folderTypes = { - for (var name in sortedFolderNames) name: folderTypes[name]! - }; - _fileScores = fileScores; - }); - } catch (e) { - debugPrint("Error loading target data files: $e"); - } -} - - // Function to safely get the score from the JSON data - int _getScoreFromJson(Map data) { - if (data.containsKey('totalScore') && data['totalScore'] is int) { - return data['totalScore']; - } - return 0; // Default to 0 if the score is not present or invalid - } - - // Delete a file - Future _deleteFile(File file) async { - bool? confirmDeletion = await _showConfirmationDialog( - context, - _t('Are you sure you want to delete this file?'), - ); - - if (confirmDeletion == true) { - try { - await file.delete(); - _loadTargetDataFiles(); // Refresh after deleting the file - } catch (e) { - debugPrint("Error deleting file: $e"); - } - } - } - - // Open file preview in the TargetViewScreen - void _openFilePreview(File targetFile) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => TargetViewScreen( - jsonFiles: [targetFile], // Pass the selected file in a list - refreshFolders: _loadTargetDataFiles, // Pass the refreshFolders callback - ), - ), - ); - } - - // Open folder's combined target view in the TargetViewScreen - void _openFolderTargetView(String folderName) async { - final targetFiles = _groupedFiles[folderName] ?? []; - - // Navigate to view screen with all individual files - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => TargetViewScreen( - jsonFiles: targetFiles, // Pass all individual files - refreshFolders: _loadTargetDataFiles, - isCombinedView: true, // 👈 This signals combined/folder view - ), - ), - ); - } - - List _filteredFolderNames() { - final List folders = _groupedFiles.keys.toList(); - - if (_folderFilter != 'all') { - final isTournament = _folderFilter == 'tournament'; - folders.retainWhere((folderName) => _folderTypes[folderName] == isTournament); - } - - // 🔽 Sort using `createdAt` from _folderCreationDates (which is now based on metadata.json) - // 🔽 Apply sorting based on selected sort mode -folders.sort((a, b) { - if (_sortMode == 'score') { - final scoreA = _folderScores[a] ?? 0; - final scoreB = _folderScores[b] ?? 0; - return scoreB.compareTo(scoreA); // High score first - } else { - final dateA = _folderCreationDates[a]; - final dateB = _folderCreationDates[b]; - if (dateA == null || dateB == null) return 0; - return dateB.compareTo(dateA); // Newest first - } -}); - - - return folders; -} - -Future _renameFolder(String oldFolderName) async { - final newNameController = TextEditingController(); - bool isTournament = _folderTypes[oldFolderName] == true; - - final result = await showDialog>( - context: context, - builder: (context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), - child: StatefulBuilder( - builder: (context, setState) { - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - _t('Folder Settings'), - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 20), - TextField( - controller: newNameController, - textAlign: TextAlign.center, - style: const TextStyle(color: Colors.white), - decoration: InputDecoration( - filled: true, - fillColor: Colors.grey[800], - hintText: _t('Enter new folder name'), - hintStyle: const TextStyle(color: Colors.white54), - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(12), - borderSide: BorderSide.none, - ), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(12), - borderSide: BorderSide(color: _bulletColor), - ), - ), - onChanged: (value) { - setState(() { - isRenameEnabled = value.trim().isNotEmpty; - }); - }, - ), - const SizedBox(height: 16), - GestureDetector( - onTap: () { - setState(() { - isTournament = !isTournament; - }); - }, - child: Container( - width: double.infinity, - decoration: BoxDecoration( - color: isTournament ? _bulletColor.withValues(alpha: 0.2) : Colors.grey[850], - borderRadius: BorderRadius.circular(12), - border: Border.all( - color: isTournament ? _bulletColor : Colors.grey[700]!, - width: 1.5, - ), - ), - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - Icons.emoji_events, - size: 16, - color: isTournament ? _bulletColor : Colors.white70, - ), - const SizedBox(width: 8), - Text( - isTournament ? _t('Tournament Mode') : _t('Mark as Tournament'), - style: TextStyle( - color: isTournament ? _bulletColor : Colors.white70, - fontWeight: FontWeight.w500, - fontSize: 16, - ), - ), - ], - ), - ), - ), - ), - const SizedBox(height: 20), - Row( - children: [ - Expanded( - child: ElevatedButton( - onPressed: () => Navigator.of(context).pop(), - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 12), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t('Cancel')), - ), - ), - const SizedBox(width: 12), - Expanded( - child: ElevatedButton( - onPressed: () => Navigator.of(context).pop({ - 'name': newNameController.text.trim(), - 'isTournament': isTournament, - }), - style: ElevatedButton.styleFrom( - backgroundColor: _bulletColor, - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 12), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t('Apply')), - ), - ), - ], - ) - ], - ); - }, - ), - ), - ); - }, - ); - - // ✅ Handle result (rename + tag update) - if (result != null) { - final newName = result['name']; - final isTournament = result['isTournament'] ?? false; - - final directory = await getApplicationDocumentsDirectory(); - final oldFolderPath = Directory('${directory.path}/saved_images/$oldFolderName'); - final targetFolderName = (newName != null && newName.isNotEmpty) ? newName : oldFolderName; - final newFolderPath = Directory('${directory.path}/saved_images/$targetFolderName'); - - if (targetFolderName != oldFolderName) { - if (await newFolderPath.exists()) { - debugPrint('A folder named "$targetFolderName" already exists.'); - return; - } else { - await oldFolderPath.rename(newFolderPath.path); - } - } - - // ✅ Preserve existing createdAt value or set it if missing - final metadataFile = File('${newFolderPath.path}/metadata.json'); - String? createdAt; - - if (await metadataFile.exists()) { - try { - final existing = jsonDecode(await metadataFile.readAsString()); - createdAt = existing['createdAt']; - } catch (_) {} - } - - createdAt ??= DateTime.now().toIso8601String(); // fallback if not found - - final updatedMetadata = { - 'isTournament': isTournament, - 'createdAt': createdAt, - }; - - await metadataFile.writeAsString(jsonEncode(updatedMetadata)); - - _loadTargetDataFiles(); // Refresh UI - } -} - - - - - // Delete a folder - Future _deleteFolder(String folderName) async { - bool? confirmDeletion = await _showConfirmationDialog( - context, - '${_t('Are you sure you want to delete the folder')} "$folderName" ${_t('and all of its contents?')}', - ); - - if (confirmDeletion == true) { - try { - final directory = await getApplicationDocumentsDirectory(); - final folderPath = Directory('${directory.path}/saved_images/$folderName'); - - if (await folderPath.exists()) { - await folderPath.delete(recursive: true); - } - - _loadTargetDataFiles(); // Refresh file/folder list - } catch (e) { - debugPrint("Error deleting folder: $e"); - } - } -} - - Future _showConfirmationDialog(BuildContext context, String message) async { - return 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, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - _t('Confirm Deletion'), + void _pickYear() { + final s = AppSettings.instance; + final options = {..._years, DateTime.now().year}.toList() + ..sort((a, b) => b.compareTo(a)); + showModalBottomSheet( + context: context, + builder: (sheet) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text( + s.t('Year'), style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, - ), - textAlign: TextAlign.center, - ), - const SizedBox(height: 16), - Text( - message, - style: const TextStyle(color: Colors.white70, fontSize: 16), - textAlign: TextAlign.center, - ), - const SizedBox(height: 24), - - // "Yes" Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () => Navigator.of(context).pop(true), - style: ElevatedButton.styleFrom( - backgroundColor: Colors.redAccent, - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t("Yes, delete")), - ), - ), - const SizedBox(height: 12), - - // "No" Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () => Navigator.of(context).pop(false), - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t("Cancel")), - ), - ), - ], - ), - ), - ); - }, - ); -} - - -Widget _buildFolderRow(String folderName) { - final numberOfTargets = _groupedFiles[folderName]!.length; - final totalScore = _folderScores[folderName]; - final folderDate = _folderCreationDates[folderName]; - final formattedDate = folderDate != null - ? DateFormat('dd/MM/yyyy').format(folderDate) - : 'Unknown Date'; - - return Container( - margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(12), - ), - child: Column( - children: [ - // Header section with grey background like toolbars - InkWell( - onTap: () { - setState(() { - _expandedFolder = _expandedFolder == folderName ? null : folderName; - }); - }, - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - child: Container( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), - decoration: BoxDecoration( - color: Colors.grey[900], - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.bold), ), ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( + Flexible( + child: ListView( + shrinkWrap: true, + children: [ + for (final y in options) + SheetOption( + label: '$y', + selected: y == _year, + selectedColor: s.bulletColor, + onTap: () { + Navigator.pop(sheet); + setState(() { + _year = y; + _sessions = null; + _shots = null; + }); + _load(); + }, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), + ), + ); + } + + List get _filtered => [ + for (final s in _sessions ?? []) + if (s.isTournament == (_filter == _Filter.tournament)) s, + ]; + + // Shots-per-target formats in the current tab, most used first + List _formats(List sessions) { + final counts = {}; + for (final session in sessions) { + for (final t in session.targets) { + if (t.shots > 0) counts[t.shots] = (counts[t.shots] ?? 0) + 1; + } + } + return counts.keys.toList() + ..sort((a, b) => counts[b]!.compareTo(counts[a]!)); + } + + Future _openSession(Session session) async { + // Open the full session, not the copy limited to one format + final full = _sessions! + .firstWhere((s) => s.name == session.name, orElse: () => session); + await Navigator.push(context, + MaterialPageRoute(builder: (_) => SessionScreen(session: full))); + _load(); + } + + String get _locale => + AppSettings.instance.language == 'Slovenian' ? 'sl_SI' : 'en_US'; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + if (_sessions == null) { + return Column(children: [ + _buildTabs(), + const Expanded(child: Center(child: CircularProgressIndicator())) + ]); + } + + // Statistics only compare like with like: one tab, one shots-per-target format + final typed = _filtered; + final formats = _formats(typed); + final shots = formats.contains(_shots) + ? _shots + : (formats.isEmpty ? null : formats.first); + final sessions = [ + for (final session in typed) + if (session.onlyShots(shots).targets.isNotEmpty) + session.onlyShots(shots), + ]; + final stats = ShooterStats.of(sessions); + + return Column( + children: [ + _buildTabs(), + _buildFilterBar(formats, shots), + Expanded( + child: RefreshIndicator( + onRefresh: _load, + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 32), children: [ - // White indicator line - Container( - width: 4, - height: 20, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 12), - Row( - children: [ - if (_folderTypes[folderName] == true) ...[ - const Icon(Icons.emoji_events, size: 18, color: Colors.white), - const SizedBox(width: 8), - ], - Text( - folderName, - style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white), - ), - ], - ), + if (stats.targets == 0) + _buildEmpty() + else ...[ + _buildSummary(sessions, stats), + ..._buildHistory(sessions), + ], ], ), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.calendar_today, size: 14, color: Colors.white), + ), + ), + ], + ); + }, + ); + } + + // Filters continue the dark app bar, like Koledar/Stiki; sort toggle at the end + Widget _buildTabs() { + final s = AppSettings.instance; + return BarTabs( + tabs: [ + BarTab(s.t('Trainings'), Icons.track_changes_rounded), + BarTab(s.t('Tournaments'), Icons.emoji_events_rounded), + ], + selected: _filter.index, + onSelect: (i) => setState(() { + _filter = _Filter.values[i]; + _shots = null; + }), + trailing: IconButton( + tooltip: _sortByScore ? s.t('Sort by Score') : s.t('Sort by Date'), + icon: Icon( + _sortByScore ? Icons.leaderboard_rounded : Icons.event_rounded, + color: Colors.white), + onPressed: () => setState(() => _sortByScore = !_sortByScore), + ), + ); + } + + // Second dark row under the tabs: shots-per-target pills left, year right + Widget _buildFilterBar(List formats, int? selected) { + final sorted = [...formats]..sort(); + return Container( + color: AppTheme.bar, + padding: const EdgeInsets.fromLTRB(12, 0, 4, 8), + child: Row( + children: [ + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final n in sorted) ...[ + _BarPill( + label: shotCount(n), + selected: n == selected, + onTap: () => setState(() => _shots = n)), const SizedBox(width: 6), - Text( - formattedDate, - style: const TextStyle(fontSize: 13, color: Colors.white), - ), - const SizedBox(width: 12), - Icon( - _expandedFolder == folderName ? Icons.expand_less : Icons.expand_more, - color: Colors.white, - ), ], - ), + ], + ), + ), + ), + TextButton.icon( + style: TextButton.styleFrom(foregroundColor: Colors.white), + onPressed: _pickYear, + icon: const Icon(Icons.calendar_month_rounded, size: 18), + label: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('$_year', + style: const TextStyle(fontWeight: FontWeight.w700)), + const Icon(Icons.expand_more_rounded, size: 18), ], ), ), - ), - // Expandable targets list (in the middle) - if (_expandedFolder == folderName) ...[ - Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: Colors.grey[100], - ), - child: _buildTargetsList(folderName), - ), ], - // Bottom section: Info badge and action buttons - IntrinsicHeight( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // Info badge section (non-clickable, matches button style) - Expanded( - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), - decoration: BoxDecoration( - color: Colors.grey[200], - borderRadius: BorderRadius.only( - bottomLeft: const Radius.circular(12), - ), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - // Targets count - Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.filter_center_focus, size: 16, color: Colors.black87), - const SizedBox(width: 4), - Text( - "$numberOfTargets", - style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black87), - ), - ], - ), - // Score - Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.emoji_events, size: 16, color: Colors.black87), - const SizedBox(width: 4), - Text( - "$totalScore", - style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black87), - ), - ], - ), - ], - ), - ), - ), - // Preview button section - InkWell( - onTap: () => _openFolderTargetView(folderName), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), - decoration: BoxDecoration( - color: _bulletColor.withValues(alpha: 0.2), - border: Border( - left: BorderSide(color: Colors.grey[400]!, width: 1), - ), - ), - child: Icon(Icons.visibility, color: _bulletColor, size: 20), - ), - ), - // Edit button section - InkWell( - onTap: () => _renameFolder(folderName), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), - decoration: BoxDecoration( - color: _bulletColor.withValues(alpha: 0.2), - border: Border( - left: BorderSide(color: Colors.grey[400]!, width: 1), - ), - ), - child: Icon(Icons.edit, color: _bulletColor, size: 20), - ), - ), - // Delete button section - InkWell( - onTap: () => _deleteFolder(folderName), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), - decoration: BoxDecoration( - color: Colors.red.withValues(alpha: 0.2), - borderRadius: const BorderRadius.only( - bottomRight: Radius.circular(12), - ), - border: Border( - left: BorderSide(color: Colors.grey[400]!, width: 1), - ), - ), - child: const Icon(Icons.delete, color: Colors.red, size: 20), - ), - ), - ], - ), - ), - ], - ), - ); -} - -Widget _buildTargetsList(String folderName) { - final targetFiles = _groupedFiles[folderName] ?? []; - - if (targetFiles.isEmpty) { - return Padding( - padding: const EdgeInsets.all(16.0), - child: Text( - _t("No targets in this folder"), - style: const TextStyle(color: Colors.black54, fontSize: 14), - textAlign: TextAlign.center, ), ); } - return Column( - children: targetFiles.asMap().entries.map((entry) { - final index = entry.key; - final file = entry.value; - final score = _fileScores[file.path] ?? 0; - final fileName = "${_t('Target')} ${index + 1}"; - - return Container( - margin: const EdgeInsets.only(bottom: 8), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: Colors.grey[300]!, width: 1), + // Up to 12 trainings: one point each. More: one point per month, so a busy year + // shows the trend instead of day-to-day noise. + List _chartPoints(List chronological) { + if (chronological.length <= _chartSessions) { + return [ + for (final x in chronological) + ChartPoint(DateFormat('d. M.').format(x.date), x.averagePerShot!), + ]; + } + final byMonth = >{}; + for (final x in chronological) { + byMonth.putIfAbsent(x.date.month, () => []).add(x); + } + return [ + for (final entry in byMonth.entries) + ChartPoint( + DateFormat('LLL', _locale) + .format(DateTime(_year, entry.key)) + .replaceAll('.', ''), + entry.value.fold(0, (sum, x) => sum + x.totalScore) / + entry.value.fold(0, (sum, x) => sum + x.shots), ), + ]; + } + + Widget _buildSummary(List sessions, ShooterStats stats) { + final s = AppSettings.instance; + final surf = Surfaces.current; + final chartSessions = sessions + .where((x) => x.shots > 0) + .toList() + .reversed + .toList(); // oldest first + + // Last session's average per shot compared with the overall average + final last = + chartSessions.isNotEmpty ? chartSessions.last.averagePerShot : null; + final delta = (last != null && + stats.averagePerShot != null && + chartSessions.length > 1) + ? last - stats.averagePerShot! + : null; + + return ClipRRect( + borderRadius: BorderRadius.circular(20), + child: ColoredBox( + color: surf.card, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Dark header: headline number left, trend right + Container( + color: AppTheme.bar, + padding: const EdgeInsets.fromLTRB(20, 14, 16, 14), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(s.t('Average per shot'), + style: const TextStyle( + fontSize: 13, color: Colors.white60)), + Text( + stats.averagePerShot?.toStringAsFixed(2) ?? '–', + style: const TextStyle( + fontSize: 40, + fontWeight: FontWeight.w800, + color: Colors.white, + height: 1.15), + ), + ], + ), + ), + if (delta != null) + _TrendBadge(delta: delta, label: s.t('last training')), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(20, 8, 20, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (chartSessions.length > 1) ...[ + const SizedBox(height: 4), + ProgressChart( + points: _chartPoints(chartSessions), + color: s.bulletColor, + textColor: surf.textSecondary, + gridColor: surf.divider, + ), + ], + const SizedBox(height: 12), + Divider(height: 1, color: surf.divider), + const SizedBox(height: 14), + Row( + children: [ + Expanded( + child: _MiniStat( + label: s.t('Best target'), + value: '${stats.best!.score}', + ), + ), + Expanded( + child: _MiniStat( + label: s.t('Average target'), + value: stats.averageTarget!.toStringAsFixed(1), + ), + ), + Expanded( + child: _MiniStat( + label: s.t('Targets'), + value: '${stats.targets}', + ), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + } + + List _buildHistory(List sessions) { + final s = AppSettings.instance; + final surf = Surfaces.current; + final widgets = []; + + if (_sortByScore) { + final ranked = [...sessions] + ..sort((a, b) => b.totalScore.compareTo(a.totalScore)); + widgets.add(_monthHeader(s.t('Best results'))); + widgets.addAll(ranked.map(_sessionCard)); + return widgets; + } + + String? month; + for (final session in sessions) { + final m = + DateFormat('LLLL yyyy', _locale).format(session.date).toUpperCase(); + if (m != month) { + widgets.add(_monthHeader(m)); + month = m; + } + widgets.add(_sessionCard(session)); + } + if (widgets.isEmpty) { + widgets.add(Padding( + padding: const EdgeInsets.all(24), + child: Text(s.t('No saved target data found'), + style: TextStyle(color: surf.textSecondary)), + )); + } + return widgets; + } + + Widget _monthHeader(String text) { + return Padding( + padding: const EdgeInsets.fromLTRB(4, 24, 4, 10), + child: Text( + text, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + letterSpacing: 1.4, + color: Surfaces.current.textSecondary, + ), + ), + ); + } + + // Same build as the calendar cards: date block on the left, content in the + // middle (opens the training), action strip on the right (opens all targets). + Widget _sessionCard(Session session) { + final s = AppSettings.instance; + final surf = Surfaces.current; + final avg = session.averagePerShot; + final full = _sessions! + .firstWhere((x) => x.name == session.name, orElse: () => session); + + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Container( + decoration: BoxDecoration( + color: surf.card, + 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: [ - // Target info section - Clickable + _DateBlock( + date: session.date, color: s.bulletColor, locale: _locale), Expanded( - child: InkWell( - onTap: () => _openFilePreview(file), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), - child: Row( - children: [ - Expanded( - child: Text( - fileName, - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.black87, + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () => _openSession(session), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 12, 12, 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + if (session.isTournament) ...[ + Icon(Icons.emoji_events_rounded, + size: 16, color: s.bulletColor), + const SizedBox(width: 4), + ], + Flexible( + child: Text( + session.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: surf.textPrimary), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + [ + targetCount(session.targets.length), + if (avg != null) + '${avg.toStringAsFixed(2)} / ${s.t('shot')}', + ].join(' · '), + style: TextStyle( + fontSize: 12, color: surf.textSecondary), + ), + ], ), ), - ), - const SizedBox(width: 8), - const Icon( - Icons.emoji_events, - color: Colors.black87, - size: 14, - ), - const SizedBox(width: 4), - Text( - "$score", - style: const TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: Colors.black87, - ), - ), - ], - ), - ), - ), - ), - // Delete button - InkWell( - onTap: () => _deleteFile(file), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: Colors.red.withValues(alpha: 0.1), - border: Border( - left: BorderSide(color: Colors.grey[300]!, width: 1), - ), - borderRadius: const BorderRadius.only( - topRight: Radius.circular(10), - bottomRight: Radius.circular(10), - ), - ), - child: const Icon( - Icons.delete, - color: Colors.red, - size: 18, - ), - ), - ), - ], - ), - ), - ); - }).toList(), - ); -} - - - - @override -Widget build(BuildContext context) { - return Scaffold( - backgroundColor: _backgroundColor, - body: Column( - children: [ - // 🔽 Filter dropdown at the top (styled like tab bar) - Container( - padding: const EdgeInsets.all(6), - decoration: BoxDecoration( - color: Colors.grey[900], - border: Border( - bottom: BorderSide(color: Colors.grey[800]!, width: 1), - ), - ), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - child: GestureDetector( - onTap: () => _showFolderFilterPopup(context), - child: Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(10), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - _folderFilter == 'all' - ? Icons.folder - : _folderFilter == 'tournament' - ? Icons.emoji_events - : Icons.track_changes, - size: 16, - color: Colors.black, - ), - const SizedBox(width: 6), Text( - _folderFilter == 'all' - ? _t('Showing: All folders') - : _folderFilter == 'tournament' - ? _t('Showing: Tournament folders') - : _t('Showing: Training folders'), - style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Colors.black), + '${session.totalScore}', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w800, + color: surf.textPrimary), ), ], ), - Icon(Icons.filter_list, color: Colors.black87, size: 18), - ], - ), - ), - ), - ), - ), - // 📁 Folder list or empty state - Expanded( - child: _groupedFiles.isEmpty - ? Center(child: Text(_t("No saved target data found"), style: const TextStyle(fontSize: 18))) - : Scrollbar( - thumbVisibility: true, // always show scrollbar - thickness: 6, // optional: adjust width - radius: const Radius.circular(8), - child: ListView.builder( - padding: const EdgeInsets.only(top: 8), - itemCount: _filteredFolderNames().length, - itemBuilder: (context, index) { - String folderName = _filteredFolderNames()[index]; - return _buildFolderRow(folderName); - }, - ), - ), - ), - ], - ), - ); -} - -void _showFolderFilterPopup(BuildContext context) { - showDialog( - context: context, - builder: (BuildContext context) { - return StatefulBuilder( - builder: (context, setState) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _t('Filter Folders'), - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, ), ), - const SizedBox(height: 24), - - // Folder type filters - _buildStyledFilterButton('all', Icons.folder, _t('All folders'), context), - const SizedBox(height: 12), - _buildStyledFilterButton('tournament', Icons.emoji_events, _t('Tournament'), context), - const SizedBox(height: 12), - _buildStyledFilterButton('training', Icons.track_changes, _t('Training'), context), - - const SizedBox(height: 24), - - Text( - _t('Sort By'), - style: const TextStyle(color: Colors.white70, fontSize: 16, fontWeight: FontWeight.w500), - ), - const SizedBox(height: 12), - - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Expanded( - child: GestureDetector( - onTap: () { - setState(() => _sortMode = 'date'); - this.setState(() {}); // 👈 refresh parent widget - }, - child: Container( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8), - margin: const EdgeInsets.only(right: 6), - decoration: BoxDecoration( - color: _sortMode == 'date' ? _bulletColor : Colors.grey[800], - borderRadius: BorderRadius.circular(12), - ), - child: Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - Icons.calendar_today, - size: 14, - color: _sortMode == 'date' ? Colors.white : Colors.white70, - ), - const SizedBox(width: 4), - Text( - _t('Sort by Date'), - textAlign: TextAlign.center, - style: TextStyle( - color: _sortMode == 'date' ? Colors.white : Colors.white70, - fontWeight: FontWeight.w500, - fontSize: 14, - ), - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - ], - ), - ), - ), - ), - ), - Expanded( - child: GestureDetector( - onTap: () { - setState(() => _sortMode = 'score'); - this.setState(() {}); // 👈 refresh parent widget - }, - child: Container( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8), - margin: const EdgeInsets.only(left: 6), - decoration: BoxDecoration( - color: _sortMode == 'score' ? _bulletColor : Colors.grey[800], - borderRadius: BorderRadius.circular(12), - ), - child: Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - Icons.emoji_events, - size: 14, - color: _sortMode == 'score' ? Colors.white : Colors.white70, - ), - const SizedBox(width: 4), - Text( - _t('Sort by Score'), - textAlign: TextAlign.center, - style: TextStyle( - color: _sortMode == 'score' ? Colors.white : Colors.white70, - fontWeight: FontWeight.w500, - fontSize: 14, - ), - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - ], - ), - ), - ), - ), - ), - ], - ), - ], + ), ), - ), - ); - }, - ); - }, - ); -} - - -Widget _buildStyledFilterButton(String value, IconData icon, String label, BuildContext context) { - final isSelected = _folderFilter == value; - - return SizedBox( - width: double.infinity, - child: GestureDetector( - onTap: () { - setState(() { - _folderFilter = value; - }); - Navigator.of(context).pop(); - }, - child: Container( - padding: const EdgeInsets.symmetric(vertical: 14), - decoration: BoxDecoration( - color: isSelected ? _bulletColor : Colors.grey[800], - borderRadius: BorderRadius.circular(12), - ), - child: Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - icon, - size: 18, - color: isSelected ? Colors.white : Colors.white70, - ), - const SizedBox(width: 8), - Text( - label, - style: TextStyle( - color: isSelected ? Colors.white : Colors.white70, - fontSize: 16, - fontWeight: FontWeight.w500, + Material( + color: AppTheme.bar, + child: InkWell( + onTap: () => _openAllTargets(full), + child: const SizedBox( + width: 56, + child: Icon(Icons.visibility_rounded, + color: Colors.white, size: 22), + ), ), ), ], ), ), ), - ), - ); + ); + } + + Future _openAllTargets(Session session) async { + if (session.targets.isEmpty) return; + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => TargetViewScreen( + jsonFiles: session.files, + refreshFolders: _load, + isCombinedView: true), + ), + ); + _load(); + } + + Widget _buildEmpty() { + final s = AppSettings.instance; + final surf = Surfaces.current; + return Container( + padding: const EdgeInsets.symmetric(vertical: 48, horizontal: 24), + decoration: BoxDecoration( + color: surf.card, borderRadius: BorderRadius.circular(20)), + child: Column( + children: [ + Icon(Icons.track_changes_rounded, + size: 48, color: surf.textSecondary), + const SizedBox(height: 12), + Text( + s.t('No saved target data found'), + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: surf.textPrimary), + ), + const SizedBox(height: 4), + Text( + s.t('Saved targets and your statistics will appear here'), + textAlign: TextAlign.center, + style: TextStyle(color: surf.textSecondary), + ), + ], + ), + ); + } } +/// ▲/▼ difference with an icon, so the direction never depends on color alone. +class _TrendBadge extends StatelessWidget { + final double delta; + final String label; + const _TrendBadge({required this.delta, required this.label}); + + @override + Widget build(BuildContext context) { + final up = delta >= 0; + final color = up ? Colors.green[700]! : Colors.red[700]!; + return Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(12)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + up + ? Icons.arrow_upward_rounded + : Icons.arrow_downward_rounded, + size: 14, + color: Colors.white), + const SizedBox(width: 2), + Text( + delta.abs().toStringAsFixed(2), + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + ], + ), + ), + const SizedBox(height: 2), + Text(label, + style: const TextStyle(fontSize: 11, color: Colors.white60)), + ], + ); + } +} + +class _MiniStat extends StatelessWidget { + final String label; + final String value; + + const _MiniStat({required this.label, required this.value}); + + @override + Widget build(BuildContext context) { + final surf = Surfaces.current; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(value, + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: surf.textPrimary)), + Text(label, style: TextStyle(fontSize: 12, color: surf.textSecondary)), + ], + ); + } +} + +/// Full-height date column on the card's left edge, like the calendar cards. +class _DateBlock extends StatelessWidget { + final DateTime date; + final Color color; + final String locale; + + const _DateBlock( + {required this.date, required this.color, required this.locale}); + + @override + Widget build(BuildContext context) { + final small = TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + color: Colors.white.withValues(alpha: 0.9)); + return Container( + width: 56, + color: color, + padding: const EdgeInsets.symmetric(vertical: 8), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(DateFormat('EEE', locale).format(date).toUpperCase(), + style: small), + Text( + DateFormat('d').format(date), + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Colors.white, + height: 1.15), + ), + Text( + DateFormat('MMM', locale) + .format(date) + .toUpperCase() + .replaceAll('.', ''), + style: small), + ], + ), + ); + } +} + +/// Small pill on the dark bar: white when selected, outlined otherwise. +class _BarPill extends StatelessWidget { + final String label; + final bool selected; + final VoidCallback onTap; + + const _BarPill( + {required this.label, required this.selected, required this.onTap}); + + @override + Widget build(BuildContext context) { + return Material( + color: selected ? Colors.white : Colors.transparent, + shape: StadiumBorder( + side: BorderSide(color: selected ? Colors.white : Colors.white30)), + child: InkWell( + customBorder: const StadiumBorder(), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: selected ? Colors.black : Colors.white70, + ), + ), + ), + ), + ); + } } diff --git a/lib/screens/calendar_screen.dart b/lib/screens/calendar_screen.dart index a24688d..2fcac65 100644 --- a/lib/screens/calendar_screen.dart +++ b/lib/screens/calendar_screen.dart @@ -4,27 +4,15 @@ import 'package:intl/intl.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../models/contact.dart'; +import '../services/app_settings.dart'; +import '../theme/app_theme.dart'; +import '../widgets/bar_tabs.dart'; import '../services/google_calendar_service.dart'; import '../services/notification_service.dart'; import '../utils/translations.dart'; import '../utils/target_colors.dart'; -class Contact { - final String firstName; - final String lastName; - final String phone; - final String email; - - Contact({ - required this.firstName, - required this.lastName, - required this.phone, - required this.email, - }); - - String get fullName => '$firstName $lastName'; -} - enum EventType { regular, competition, @@ -48,29 +36,13 @@ class _CalendarScreenState extends State { bool _showContacts = false; late Color _backgroundColor; - 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'), - Contact(firstName: 'Jože', lastName: 'Verhnjak', phone: '041443463', email: 'joze.verhnjak@gmail.com'), - Contact(firstName: 'Branko', lastName: 'Pokeržnik', phone: '041291001', email: 'pokerznik.helena@gmail.com'), - Contact(firstName: 'Franc', lastName: 'Žigart', phone: '041439597', email: 'franc.zigart@gmail.com'), - Contact(firstName: 'Janez', lastName: 'Božič', phone: '041551704', email: 'janbozic@gmail.com'), - Contact(firstName: 'Mitja', lastName: 'Čeh', phone: '070550383', email: 'mekabara@gmail.com'), - Contact(firstName: 'Rado', lastName: 'Keter', phone: '041324529', email: 'rado.keter@gmail.com'), - Contact(firstName: 'Karli', lastName: 'Proje', phone: '040424951', email: 'karl.project@gmail.com'), - Contact(firstName: 'Jan', lastName: 'Pleterski', phone: '041842063', email: 'jan.pleterski1997@gmail.com'), - Contact(firstName: 'Silvo', lastName: 'Poročnik', phone: '040860618', email: 'skobar.silvo@gmail.com'), - Contact(firstName: 'Dušan', lastName: 'Onuk', phone: '070448303', email: 'dusan.onuk@gmail.com'), - Contact(firstName: 'Matjaž', lastName: 'Pleterski', phone: '041603859', email: 'matjaz.pleterski@gmail.com'), - Contact(firstName: 'Marko', lastName: 'Blimen', phone: '031610857', email: 'blimenmarko@gmail.com'), - Contact(firstName: 'Doris', lastName: 'Fesel', phone: '070373987', email: 'doris.fesel@gmail.com'), - ]; + List get _contacts => AppSettings.instance.clubContacts; @override void initState() { super.initState(); initializeDateFormatting('sl_SI', null); - _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); + _backgroundColor = AppSettings.instance.backgroundColor; _loadBulletColor(); _loadLanguage(); _loadSelectedTargetColor(); @@ -81,13 +53,16 @@ class _CalendarScreenState extends State { 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)); + final selectedTarget = + prefs.getString('selectedTarget') ?? 'assets/target.png'; + setState(() => + _backgroundColor = TargetColors.getBackgroundColor(selectedTarget)); } @override @@ -103,22 +78,38 @@ class _CalendarScreenState extends State { 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; } } @@ -130,7 +121,9 @@ class _CalendarScreenState extends State { 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')) { + if (summary.contains('liga') || + summary.contains('tekmovanje') || + summary.contains('tekma')) { return EventType.competition; } else if (summary.contains('sestanek')) { return EventType.sestanek; @@ -159,7 +152,8 @@ class _CalendarScreenState extends State { if (!_isValidEvent(event)) return false; if (_getEventType(event) == null) return false; 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; @@ -225,51 +219,62 @@ class _CalendarScreenState extends State { borderRadius: BorderRadius.vertical(top: Radius.circular(20)), ), builder: (context) { - return RepaintBoundary( - child: Container( - padding: const EdgeInsets.all(20), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: 20), - child: Row( - children: [ - Container( - width: 50, - height: 50, - decoration: BoxDecoration( - color: accentColor, - borderRadius: BorderRadius.circular(10), - ), - child: Center( - child: Text( - contact.firstName[0].toUpperCase(), - style: const TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold), + // SafeArea keeps the buttons above Android's gesture bar (edge-to-edge) + return SafeArea( + child: RepaintBoundary( + child: Container( + padding: const EdgeInsets.all(20), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(bottom: 20), + child: Row( + children: [ + Container( + width: 50, + height: 50, + decoration: BoxDecoration( + color: accentColor, + borderRadius: BorderRadius.circular(10), + ), + child: Center( + child: Text( + contact.firstName[0].toUpperCase(), + style: const TextStyle( + color: Colors.white, + fontSize: 24, + fontWeight: FontWeight.bold), + ), ), ), - ), - const SizedBox(width: 16), - Expanded( - child: Text( - _capitalize(contact.fullName), - style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), + const SizedBox(width: 16), + Expanded( + child: Text( + _capitalize(contact.fullName), + style: const TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.bold), + ), ), - ), - ], + ], + ), ), - ), - _buildContactDetailRow(accentColor, Icons.phone, _t('Phone'), contact.phone, () { - _copyToClipboard(contact.phone, 'Phone number'); - Navigator.pop(context); - }), - const SizedBox(height: 12), - _buildContactDetailRow(accentColor, Icons.email, _t('Email'), contact.email.toLowerCase(), () { - _copyToClipboard(contact.email, 'Email address'); - Navigator.pop(context); - }), - ], + _buildContactDetailRow( + accentColor, Icons.phone, _t('Phone'), contact.phone, () { + _copyToClipboard(contact.phone, 'Phone number'); + Navigator.pop(context); + }), + const SizedBox(height: 12), + _buildContactDetailRow(accentColor, Icons.email, _t('Email'), + contact.email.toLowerCase(), () { + _copyToClipboard(contact.email, 'Email address'); + Navigator.pop(context); + }), + ], + ), ), ), ); @@ -277,10 +282,12 @@ class _CalendarScreenState extends State { ); } - Widget _buildContactDetailRow(Color accentColor, IconData icon, String label, String value, VoidCallback onCopy) { + 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)), + decoration: BoxDecoration( + color: Colors.grey[850], borderRadius: BorderRadius.circular(10)), child: Row( children: [ Icon(icon, color: accentColor, size: 20), @@ -289,13 +296,21 @@ class _CalendarScreenState extends State { 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), + 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)), + decoration: BoxDecoration( + color: accentColor, borderRadius: BorderRadius.circular(8)), child: Material( color: Colors.transparent, child: InkWell( @@ -303,7 +318,8 @@ class _CalendarScreenState extends State { borderRadius: BorderRadius.circular(8), child: const Padding( padding: EdgeInsets.all(8), - child: Icon(Icons.content_copy, color: Colors.white, size: 18), + child: + Icon(Icons.content_copy, color: Colors.white, size: 18), ), ), ), @@ -321,15 +337,18 @@ class _CalendarScreenState extends State { itemBuilder: (context, index) { final contact = _contacts[index]; return GestureDetector( - onTap: () => _makePhoneCall(contact.phone), - onLongPress: () => _showContactPopup(context, contact), + // Card opens the info sheet (copy number/e-mail); the call strip on the right calls + onTap: () => _showContactPopup(context, contact), child: Container( margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), decoration: BoxDecoration( - color: Colors.grey[300], + color: Surfaces.current.card, borderRadius: BorderRadius.circular(12), boxShadow: [ - BoxShadow(color: Colors.grey.withValues(alpha: 0.3), blurRadius: 8, offset: const Offset(0, 2)), + BoxShadow( + color: Colors.black.withValues(alpha: 0.15), + blurRadius: 6, + offset: const Offset(0, 2)), ], ), child: Stack( @@ -339,44 +358,62 @@ class _CalendarScreenState extends State { children: [ Container( width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + 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: [ 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), 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), ), ), ], ), ), Padding( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), + 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)), + Text(contact.phone, + style: TextStyle( + fontSize: 12, + color: Surfaces.current.textPrimary, + 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), + child: Text(contact.email.toLowerCase(), + style: TextStyle( + fontSize: 12, + color: Surfaces.current.textPrimary, + fontWeight: FontWeight.w500), + overflow: TextOverflow.ellipsis), ), ]), ], @@ -385,19 +422,27 @@ class _CalendarScreenState extends State { ], ), 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: const 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)), ), ), ), @@ -412,48 +457,64 @@ 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; + 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; + 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'); + 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'); + 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}) { + // When [date] is given, the type stripe widens into a date block (upcoming list). + Widget _buildEventCard(CalendarEvent event, Color accentColor, + {bool highlight = false, DateTime? date, int daysFromToday = 0}) { final eventType = _getEventType(event); if (eventType == null) return const SizedBox(); final color = _eventColor(eventType, accentColor); final hasLocation = event.location != null && event.location!.isNotEmpty; + final surf = Surfaces.current; return RepaintBoundary( child: Container( decoration: BoxDecoration( - color: Colors.grey[300], + color: surf.card, borderRadius: BorderRadius.circular(12), boxShadow: [ - BoxShadow(color: Colors.black.withValues(alpha: 0.15), blurRadius: 6, offset: const Offset(0, 2)), + BoxShadow( + color: Colors.black.withValues(alpha: 0.15), + blurRadius: 6, + offset: const Offset(0, 2)), ], ), clipBehavior: Clip.antiAlias, @@ -461,23 +522,31 @@ class _CalendarScreenState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - // Type color stripe - Container(width: 5, color: color), + // Type color stripe, or date block for upcoming events + date != null + ? _buildDateBlock(date, daysFromToday, color) + : Container(width: 5, color: color), Expanded( child: Padding( - padding: EdgeInsets.fromLTRB(12, highlight ? 12 : 10, 12, highlight ? 12 : 10), + 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), + _buildTypeChip(_eventIcon(eventType), + _eventBadgeLabel(eventType), color), const Spacer(), - Icon(Icons.access_time, size: 13, color: Colors.grey[700]), + Icon(Icons.access_time, + size: 13, color: surf.textSecondary), const SizedBox(width: 4), Text( _timeText(event), - style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.grey[800]), + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: surf.textSecondary), ), ], ), @@ -487,19 +556,21 @@ class _CalendarScreenState extends State { style: TextStyle( fontSize: highlight ? 16 : 14, fontWeight: FontWeight.w700, - color: Colors.grey[900], + color: surf.textPrimary, ), ), if (hasLocation) ...[ const SizedBox(height: 4), Row( children: [ - Icon(Icons.location_on, size: 13, color: Colors.grey[600]), + Icon(Icons.location_on, + size: 13, color: surf.textSecondary), const SizedBox(width: 4), Expanded( child: Text( event.location!, - style: TextStyle(fontSize: 12, color: Colors.grey[700]), + style: TextStyle( + fontSize: 12, color: surf.textSecondary), maxLines: 1, overflow: TextOverflow.ellipsis, ), @@ -530,13 +601,19 @@ class _CalendarScreenState extends State { 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)), + 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}) { + Widget _buildSectionHeader(String label, Color dotColor, Color textColor, + {String? trailing, Color? trailingColor}) { return Row( children: [ Container( @@ -545,7 +622,12 @@ class _CalendarScreenState extends State { 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)), + Text(label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: textColor, + letterSpacing: 1.4)), if (trailing != null) ...[ const SizedBox(width: 8), Expanded( @@ -560,32 +642,43 @@ class _CalendarScreenState extends State { ); } - Widget _buildDateColumn(DateTime date, int daysFromToday, Color accentColor, bool isLight) { + Widget _buildDateBlock(DateTime date, int daysFromToday, Color color) { 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, + return Container( + width: 56, + color: color, + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 2), child: Column( - crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.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), + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + color: Colors.white.withValues(alpha: 0.9), + letterSpacing: 0.8), ), Text( DateFormat('d').format(date), - style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: isLight ? Colors.black87 : Colors.white, height: 1.15), + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: 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]), + fontWeight: + daysFromToday == 1 ? FontWeight.bold : FontWeight.w500, + color: Colors.white.withValues(alpha: 0.9), ), ), ], @@ -606,17 +699,24 @@ class _CalendarScreenState extends State { 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); + 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(); + 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 + // Build upcoming list grouped by month, each card carries its own date block 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 isNewMonth = lastDay == null || + lastDay.month != day.month || + lastDay.year != day.year; final isNewDay = lastDay == null || !lastDay.isAtSameMomentAs(day); if (isNewMonth) { @@ -624,23 +724,20 @@ class _CalendarScreenState extends State { 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), + 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)), - ], - ), + padding: + EdgeInsets.fromLTRB(16, isNewDay && !isNewMonth ? 10 : 0, 16, 8), + child: _buildEventCard(e, accentColor, + date: day, daysFromToday: day.difference(today).inDays), )); lastDay = day; } @@ -668,7 +765,8 @@ class _CalendarScreenState extends State { if (todayEvents.isEmpty) Container( width: double.infinity, - padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 14), + padding: const EdgeInsets.symmetric( + vertical: 14, horizontal: 14), decoration: BoxDecoration( color: textMuted.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(12), @@ -677,15 +775,17 @@ class _CalendarScreenState extends State { children: [ Icon(Icons.event_busy, size: 18, color: textMuted), const SizedBox(width: 10), - Text(_t('No events today'), style: TextStyle(fontSize: 13, color: textSecondary)), + 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), - )), + padding: const EdgeInsets.only(bottom: 8), + child: _buildEventCard(e, accentColor, highlight: true), + )), ], ), ), @@ -693,7 +793,8 @@ class _CalendarScreenState extends State { if (upcomingEvents.isNotEmpty) ...[ Padding( padding: const EdgeInsets.fromLTRB(16, 24, 16, 10), - child: _buildSectionHeader(_t('UPCOMING'), textMuted, textPrimary), + child: + _buildSectionHeader(_t('UPCOMING'), textMuted, textPrimary), ), ...upcomingWidgets, ], @@ -705,9 +806,11 @@ class _CalendarScreenState extends State { children: [ Icon(Icons.event_available, size: 56, color: textMuted), const SizedBox(height: 12), - Text(_t('No upcoming events'), style: TextStyle(fontSize: 15, color: textMuted)), + 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)), + Text(_t('Pull down to refresh'), + style: TextStyle(fontSize: 13, color: textSecondary)), ], ), ), @@ -741,14 +844,19 @@ 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, color: Colors.white70)), + child: Text(_errorMessage!, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 16, color: Surfaces.current.textSecondary)), ), 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), ), ], ), @@ -760,19 +868,13 @@ class _CalendarScreenState extends State { backgroundColor: _backgroundColor, body: Column( children: [ - // Tab bar - Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - decoration: BoxDecoration( - color: Colors.grey[900], - ), - child: Row( - children: [ - _buildTab(_t('Calendar'), Icons.calendar_month, !_showContacts, () => setState(() => _showContacts = false)), - const SizedBox(width: 6), - _buildTab(_t('Contacts'), Icons.people, _showContacts, () => setState(() => _showContacts = true)), - ], - ), + BarTabs( + tabs: [ + BarTab(_t('Calendar'), Icons.calendar_month), + BarTab(_t('Contacts'), Icons.people), + ], + selected: _showContacts ? 1 : 0, + onSelect: (i) => setState(() => _showContacts = i == 1), ), // Body Expanded( @@ -784,31 +886,4 @@ class _CalendarScreenState extends State { ), ); } - - 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), - ), - 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]), - ), - ], - ), - ), - ), - ); - } } diff --git a/lib/screens/camera_screen.dart b/lib/screens/camera_screen.dart index 8ae900a..519b6eb 100644 --- a/lib/screens/camera_screen.dart +++ b/lib/screens/camera_screen.dart @@ -7,6 +7,7 @@ import 'yolo_detector.dart'; import 'preview_screen.dart'; import '../utils/translations.dart'; import '../utils/target_colors.dart'; +import '../widgets/camera_sheet.dart'; class CameraScreen extends StatefulWidget { const CameraScreen({super.key}); @@ -26,9 +27,10 @@ class _CameraScreenState extends State { String _selectedLanguage = 'English'; late Color _backgroundColor; - // Brightness and contrast controls - double _brightness = 0.0; // -1.0 to 1.0 - double _contrast = 1.0; // 0.0 to 2.0 + // Real camera controls (they change the photo itself) + double _exposure = 0, _minExposure = 0, _maxExposure = 0; + double _zoom = 1, _minZoom = 1, _maxZoom = 1; + bool _torch = false; @override void initState() { @@ -40,24 +42,9 @@ class _CameraScreenState extends State { _loadBulletColor(); // 👈 _loadLanguage(); _loadSelectedTargetColor(); - _loadBrightnessContrast(); YOLODetector.create().then((detector) => _yoloDetector = detector); } - Future _loadBrightnessContrast() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _brightness = prefs.getDouble('brightness') ?? 0.0; - _contrast = prefs.getDouble('contrast') ?? 1.0; - }); - } - - Future _saveBrightnessContrast() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setDouble('brightness', _brightness); - await prefs.setDouble('contrast', _contrast); - } - String _t(String key) { return AppTranslations.translate(key, _selectedLanguage); } @@ -71,63 +58,63 @@ class _CameraScreenState extends State { Future _loadSelectedTargetColor() async { final prefs = await SharedPreferences.getInstance(); - final selectedTarget = prefs.getString('selectedTarget') ?? 'assets/target.png'; + final selectedTarget = + prefs.getString('selectedTarget') ?? 'assets/target.png'; setState(() { _backgroundColor = TargetColors.getBackgroundColor(selectedTarget); }); } 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 '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; // fallback + 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 '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; // fallback + } + } Future _loadBulletCount() async { final prefs = await SharedPreferences.getInstance(); setState(() { - _numberOfBullets = prefs.getInt('bulletCount') ?? 5; // Load stored bullet count, default to 5 + _numberOfBullets = prefs.getInt('bulletCount') ?? + 5; // Load stored bullet count, default to 5 }); } @@ -146,7 +133,13 @@ Color _getColorFromName(String colorName) { enableAudio: false, ); - _initializeControllerFuture = _controller!.initialize(); + _initializeControllerFuture = _controller!.initialize().then((_) async { + // Ranges differ per phone; read them once the camera is ready + _minExposure = await _controller!.getMinExposureOffset(); + _maxExposure = await _controller!.getMaxExposureOffset(); + _minZoom = await _controller!.getMinZoomLevel(); + _maxZoom = (await _controller!.getMaxZoomLevel()).clamp(_minZoom, 8.0); + }); if (mounted) setState(() {}); } @@ -193,7 +186,7 @@ Color _getColorFromName(String colorName) { builder: (context) => PreviewScreen( imagePath: croppedFile.path, detections: detections, - bulletCount: _numberOfBullets, // Pass the bullet count + bulletCount: _numberOfBullets, // Pass the bullet count ), ), ); @@ -202,83 +195,40 @@ Color _getColorFromName(String colorName) { } } - // Method to show the dialog for selecting the number of bullets void _showBulletDialog() { - 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, - ), - ), - ), - 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( - onPressed: () { - _selectBulletCount(bulletNum); - Navigator.of(context).pop(); - }, - 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, - ), - ), - ); - }), - ), - ), - ], + showCameraSheet( + context, + builder: (sheet) => StatefulBuilder( + builder: (context, setSheetState) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + CameraSheetHeader( + title: _t('Select the number of bullets'), subtitle: '1 – 10'), + SheetStepper( + value: _numberOfBullets, + min: 1, + max: 10, + accent: _bulletColor, + onChanged: (n) { + _selectBulletCount(n); + setSheetState(() {}); + }, ), - ), - ); - }, + const SizedBox(height: 8), + ], + ), + ), ); } - void _showHelpDialog() { showDialog( context: context, 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( @@ -287,16 +237,23 @@ 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.camera_alt, + _t('Tap camera button to capture and detect bullets')), 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.tune, + _t('Settings icon: exposure, zoom and flashlight')), const SizedBox(height: 12), - _buildHelpItem(Icons.crop_square, _t('Align target inside the square frame')), + _buildHelpItem(Icons.crop_square, + _t('Align target inside the square frame')), const SizedBox(height: 20), Center( child: ElevatedButton( @@ -332,116 +289,88 @@ 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')), - ), - ], - ), - ], + void _showCameraControls() { + showCameraSheet( + context, + builder: (sheet) => StatefulBuilder( + builder: (context, setSheetState) { + Future apply( + VoidCallback change, Future Function() camera) async { + setState(change); + setSheetState(() {}); + try { + await camera(); + } catch (_) {} // control not supported on this phone + } + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CameraSheetHeader( + title: _t('Image Settings'), + trailing: TextButton.icon( + style: TextButton.styleFrom(foregroundColor: Colors.white70), + icon: const Icon(Icons.restart_alt_rounded, size: 18), + label: Text(_t('Reset')), + onPressed: () => apply(() { + _exposure = 0; + _zoom = _minZoom; + }, () async { + await _controller!.setExposureOffset(0); + await _controller!.setZoomLevel(_minZoom); + }), ), ), - ); - }, - ); - }, + if (_maxExposure > _minExposure) + SheetSlider( + icon: Icons.exposure_rounded, + label: _t('Exposure'), + valueText: + '${_exposure >= 0 ? '+' : ''}${_exposure.toStringAsFixed(1)}', + value: _exposure, + min: _minExposure, + max: _maxExposure, + accent: _bulletColor, + onChanged: (v) => apply(() => _exposure = v, + () => _controller!.setExposureOffset(v)), + ), + if (_maxZoom > _minZoom) + SheetSlider( + icon: Icons.zoom_in_rounded, + label: _t('Zoom'), + valueText: '${_zoom.toStringAsFixed(1)}×', + value: _zoom, + min: _minZoom, + max: _maxZoom, + accent: _bulletColor, + onChanged: (v) => apply( + () => _zoom = v, () => _controller!.setZoomLevel(v)), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: SheetToggle( + icon: _torch + ? Icons.flashlight_on_rounded + : Icons.flashlight_off_rounded, + label: _t('Flashlight'), + active: _torch, + accent: _bulletColor, + onTap: () => apply( + () => _torch = !_torch, + () => _controller! + .setFlashMode(_torch ? FlashMode.torch : FlashMode.off), + ), + ), + ), + ], + ); + }, + ), ); } - // Update the bullet count and save it void _selectBulletCount(int number) { setState(() { _numberOfBullets = number; // Update the selected number @@ -519,8 +448,9 @@ Color _getColorFromName(String colorName) { mainAxisAlignment: MainAxisAlignment.end, children: [ IconButton( - icon: const Icon(Icons.brightness_6, color: Colors.white, size: 24), - onPressed: _showBrightnessContrastDialog, + icon: + const Icon(Icons.tune, color: Colors.white, size: 24), + onPressed: _showCameraControls, ), ], ), @@ -540,35 +470,35 @@ Color _getColorFromName(String colorName) { builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { final screenSize = MediaQuery.of(context).size; - return Stack( - children: [ - Positioned.fill( - child: Container( - color: Colors.black, // covers any empty space - child: FittedBox( - fit: BoxFit.cover, - child: SizedBox( - width: _controller!.value.previewSize!.height, - height: _controller!.value.previewSize!.width, - child: CameraPreview(_controller!), + return Stack( + children: [ + Positioned.fill( + child: Container( + color: Colors.black, // covers any empty space + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: _controller!.value.previewSize!.height, + height: _controller!.value.previewSize!.width, + child: CameraPreview(_controller!), + ), ), ), ), - ), - Center( - child: Container( - width: screenSize.width * 0.9, - height: screenSize.width * 0.9, - decoration: BoxDecoration( - border: Border.all( - color: _bulletColor.withValues(alpha: 0.9), - width: 3, + Center( + child: Container( + width: screenSize.width * 0.9, + height: screenSize.width * 0.9, + decoration: BoxDecoration( + border: Border.all( + color: _bulletColor.withValues(alpha: 0.9), + width: 3, + ), ), ), ), - ), - ], - ); + ], + ); } else { return const Center(child: CircularProgressIndicator()); } diff --git a/lib/screens/camera_settings_screen.dart b/lib/screens/camera_settings_screen.dart new file mode 100644 index 0000000..7a88b20 --- /dev/null +++ b/lib/screens/camera_settings_screen.dart @@ -0,0 +1,161 @@ +import 'package:flutter/material.dart'; +import '../models/camera_setup.dart'; +import '../services/app_settings.dart'; +import '../theme/app_theme.dart'; +import '../widgets/section.dart'; +import '../widgets/text_prompt.dart'; + +/// Locations (strelišča), number of positions, and the camera IP of every +/// position at every location. +class CameraSettingsScreen extends StatelessWidget { + const CameraSettingsScreen({super.key}); + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final s = AppSettings.instance; + final t = s.t; + final setup = s.cameras; + final surf = Surfaces.current; + const firstPort = CameraSetup.firstPort; + + return Scaffold( + backgroundColor: s.backgroundColor, + appBar: AppBar( + title: Text(t('Cameras'), style: const TextStyle(color: Colors.white)), + backgroundColor: AppTheme.bar, + iconTheme: const IconThemeData(color: Colors.white), + scrolledUnderElevation: 0, + ), + body: ListView( + // Keep the last row clear of the system gesture bar (edge-to-edge) + padding: EdgeInsets.fromLTRB(16, 4, 16, 24 + MediaQuery.paddingOf(context).bottom), + children: [ + SectionHeader(t('Locations')), + GroupCard(children: [ + for (final location in setup.locations) + SettingsTile( + leading: Icon( + location == setup.clubLocation ? Icons.verified_rounded : Icons.place_rounded, + color: location == setup.clubLocation ? Colors.green : s.bulletColor, + ), + title: location, + subtitle: location == setup.clubLocation ? t('Added with the club code') : null, + value: t('{n} cameras').replaceAll('{n}', '${setup.camerasIn(location)}'), + onTap: () => _editLocation(context, location), + ), + SettingsTile( + leading: Icon(Icons.add_rounded, color: surf.textSecondary), + title: t('Add location'), + onTap: () => _addLocation(context), + ), + ]), + + SectionHeader(t('Positions')), + GroupCard(children: [ + SettingsTile( + title: t('Number of positions'), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.remove_rounded), + color: surf.textPrimary, + onPressed: setup.positions > 1 ? () => s.setPositionCount(setup.positions - 1) : null, + ), + SizedBox( + width: 28, + child: Text( + '${setup.positions}', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: surf.textPrimary), + ), + ), + IconButton( + icon: const Icon(Icons.add_rounded), + color: surf.textPrimary, + onPressed: setup.positions < CameraSetup.maxPositions + ? () => s.setPositionCount(setup.positions + 1) + : null, + ), + ], + ), + ), + ]), + + for (final location in setup.locations) ...[ + SectionHeader(location), + GroupCard(children: [ + SettingsTile( + leading: Icon(Icons.bolt_rounded, color: s.bulletColor), + title: t('Set all cameras from one IP'), + subtitle: t('Ports {from}–{to}') + .replaceAll('{from}', '$firstPort') + .replaceAll('{to}', '${firstPort + setup.positions - 1}'), + onTap: () => _editHost(context, location), + ), + for (int p = 1; p <= setup.positions; p++) + SettingsTile( + title: '${t('Camera')} $p', + value: setup.ipFor(p, location).isEmpty ? '—' : setup.ipFor(p, location), + onTap: () => _editCamera(context, p, location), + ), + ]), + ], + ], + ), + ); + }, + ); + } + + Future _addLocation(BuildContext context) async { + final s = AppSettings.instance; + final name = await showTextPrompt(context, title: s.t('Add location'), hint: s.t('e.g. Home')); + if (name == null || name.isEmpty) return; + if (!await s.addLocation(name) && context.mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(s.t('This location already exists')))); + } + } + + Future _editLocation(BuildContext context, String location) async { + final s = AppSettings.instance; + final name = await showTextPrompt( + context, + title: s.t('Location'), + initial: location, + resetLabel: s.t('Delete'), + onReset: () => s.removeLocation(location), + ); + if (name != null && name.isNotEmpty && name != location) await s.renameLocation(location, name); + } + + Future _editHost(BuildContext context, String location) async { + final s = AppSettings.instance; + final first = s.cameras.ipFor(1, location); + final host = await showTextPrompt( + context, + title: '${s.t('Set all cameras from one IP')} · $location', + initial: first.split(':').first, + hint: '192.168.0.10', + keyboardType: TextInputType.url, + ); + if (host != null && host.isNotEmpty) s.setLocationHost(location, host); + } + + Future _editCamera(BuildContext context, int position, String location) async { + final s = AppSettings.instance; + final ip = await showTextPrompt( + context, + title: '${s.t('Camera')} $position · $location', + initial: s.cameras.ipFor(position, location), + hint: '192.168.0.10:${CameraSetup.firstPort + position - 1}', + keyboardType: TextInputType.url, + resetLabel: s.t('Remove'), + onReset: () => s.setCameraIp(position, location, ''), + ); + if (ip != null && ip.isNotEmpty) s.setCameraIp(position, location, ip); + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index 988225c..f6036fa 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -4,153 +4,126 @@ import 'calendar_screen.dart'; import 'settings_screen.dart'; import 'target_screen.dart'; import '../widgets/bottom_nav.dart'; -//import 'login_screen.dart'; import 'camera_screen.dart'; import 'spectator_screen.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '../utils/translations.dart'; -import '../utils/target_colors.dart'; +import '../services/app_settings.dart'; +import '../theme/app_theme.dart'; + +enum AppTab { book, shooting, camera, calendar, settings } class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override - _HomeScreenState createState() => _HomeScreenState(); + State createState() => _HomeScreenState(); } class _HomeScreenState extends State { - int _selectedIndex = 1; // Default to Shooting Screen - String _selectedLanguage = 'English'; - String _selectedTarget = 'assets/target.png'; - late Color _backgroundColor; + AppTab _selected = AppTab.shooting; - static final List _pages = [ - BookScreen(), - TargetScreen(), - Placeholder(), // Placeholder for Scan - optional - CalendarScreen(), - SettingsScreen(), - ]; + static const Map _titles = { + AppTab.book: 'Book', + AppTab.shooting: 'Shooting', + AppTab.camera: 'Camera', + AppTab.calendar: 'Calendar', + AppTab.settings: 'Settings', + }; - final List _pageTitles = [ - 'Book', - 'Shooting', - 'Scan', - 'Calendar', - 'Settings' - ]; + static const Map _icons = { + AppTab.book: Icons.book, + AppTab.shooting: Icons.my_location, + AppTab.camera: Icons.camera_alt, + AppTab.calendar: Icons.calendar_today, + AppTab.settings: Icons.settings, + }; - @override - void initState() { - super.initState(); - // Initialize with default target background color - _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); - _loadLanguage(); - _loadSelectedTarget(); + // Calendar is only shown to club members (see Settings > Club code) + List get _visibleTabs => [ + for (final tab in AppTab.values) + if (tab != AppTab.calendar || AppSettings.instance.clubUnlocked) tab, + ]; + + Widget _page(AppTab tab) { + switch (tab) { + case AppTab.book: + return const BookScreen(); + case AppTab.shooting: + case AppTab.camera: // camera opens as its own route, never shown here + return const TargetScreen(); + case AppTab.calendar: + return const CalendarScreen(); + case AppTab.settings: + return const SettingsScreen(); + } } - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _selectedLanguage = prefs.getString('language') ?? 'English'; - }); - } - - Future _loadSelectedTarget() async { - final prefs = await SharedPreferences.getInstance(); - final selectedTarget = - prefs.getString('selectedTarget') ?? 'assets/target.png'; - setState(() { - _selectedTarget = selectedTarget; - _backgroundColor = TargetColors.getBackgroundColor(selectedTarget); - }); - } - - void _onItemTapped(int index) { - if (index == 2) { + void _onTabTapped(AppTab tab) { + if (tab == AppTab.camera) { _openCameraScan(); return; } - setState(() { - _selectedIndex = index; - }); - // Reload language when switching screens to pick up any changes from Settings - _loadLanguage(); + setState(() => _selected = tab); } - //void _logout() { - // Navigator.of(context).pushAndRemoveUntil( - // MaterialPageRoute(builder: (context) => const LoginScreen()), - // (Route route) => false, - // ); - //} - - // When opening the camera screen, ensure the shooting screen is always selected after returning + // When returning from the camera screen, always land on the Shooting tab void _openCameraScan() async { - // Navigate to CameraScreen await Navigator.of(context).push( MaterialPageRoute(builder: (context) => const CameraScreen()), ); - - // After returning, ensure that Shooting screen (index 1) is selected - setState(() { - _selectedIndex = 1; - }); + setState(() => _selected = AppTab.shooting); } @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text( - _t(_pageTitles[_selectedIndex]), - style: const TextStyle(color: Colors.white), - ), - backgroundColor: Colors.grey[900], - iconTheme: const IconThemeData(color: Colors.white), - automaticallyImplyLeading: false, - scrolledUnderElevation: 0, // For Material 3 (Flutter 3.7+) - actions: [ - if (_selectedIndex == 1) - IconButton( - icon: const Icon(Icons.visibility_rounded, color: Colors.white), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => SpectatorScreen( - selectedLanguage: _selectedLanguage, - ), - ), - ); - }, + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final settings = AppSettings.instance; + final tabs = _visibleTabs; + if (!tabs.contains(_selected)) _selected = AppTab.settings; // calendar was just locked + + return Scaffold( + appBar: AppBar( + title: Text( + settings.t(_titles[_selected]!), + style: const TextStyle(color: Colors.white), ), - Padding( - padding: const EdgeInsets.only(right: 16.0), - child: Center( - child: Text( - 'V1.2', - style: TextStyle( - color: Colors.grey[400], - fontSize: 12, - fontWeight: FontWeight.w500, + backgroundColor: AppTheme.bar, + iconTheme: const IconThemeData(color: Colors.white), + automaticallyImplyLeading: false, + scrolledUnderElevation: 0, // For Material 3 (Flutter 3.7+) + actions: [ + if (_selected == AppTab.shooting) + IconButton( + icon: const Icon(Icons.visibility_rounded, color: Colors.white), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => SpectatorScreen( + selectedLanguage: settings.language, + ), + ), + ); + }, ), - ), - ), + ], ), - ], - ), - backgroundColor: _backgroundColor, - body: _pages[_selectedIndex], - bottomNavigationBar: BottomNavBar( - selectedIndex: _selectedIndex, - onItemTapped: _onItemTapped, - selectedLanguage: _selectedLanguage, - ), + backgroundColor: settings.backgroundColor, + body: _page(_selected), + bottomNavigationBar: BottomNavBar( + selectedIndex: tabs.indexOf(_selected), + onItemTapped: (i) => _onTabTapped(tabs[i]), + items: [ + for (final tab in tabs) + BottomNavigationBarItem( + icon: Icon(_icons[tab]), + label: settings.t(_titles[tab]!), + ), + ], + ), + ); + }, ); } } diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dart deleted file mode 100644 index b3ae232..0000000 --- a/lib/screens/login_screen.dart +++ /dev/null @@ -1,232 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:google_sign_in/google_sign_in.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '../widgets/input_field.dart'; -import 'home_screen.dart'; -import 'register_screen.dart'; - -class LoginScreen extends StatefulWidget { - const LoginScreen({super.key}); - - @override - State createState() => _LoginScreenState(); -} - -class _LoginScreenState extends State { - final usernameController = TextEditingController(); - final passwordController = TextEditingController(); - bool rememberMe = false; - - final GoogleSignIn _googleSignIn = GoogleSignIn( - clientId: 'YOUR_WEB_CLIENT_ID_HERE', - scopes: ['email'], - ); - - @override - void initState() { - super.initState(); - _checkAutoLogin(); - } - - Future _checkAutoLogin() async { - final prefs = await SharedPreferences.getInstance(); - final isRemembered = prefs.getBool('rememberMe') ?? false; - final googleUser = prefs.getString('googleUser'); - - if (isRemembered) { - final savedUsername = prefs.getString('loginUsername') ?? prefs.getString('username'); - final savedPassword = prefs.getString('password'); - if (savedUsername != null && savedPassword != null) { - usernameController.text = savedUsername; - passwordController.text = savedPassword; - setState(() => rememberMe = true); - } - } else if (googleUser != null) { - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => const HomeScreen()), - ); - } - } - - Future _saveLoginDetails(String username, String password) async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('loginUsername', username); // Ensures login uses latest username - await prefs.setString('password', password); - - if (rememberMe) { - await prefs.setBool('rememberMe', true); - } else { - await prefs.remove('rememberMe'); - } -} - - - void login() async { - String username = usernameController.text.trim(); - String password = passwordController.text.trim(); - - final prefs = await SharedPreferences.getInstance(); - String? savedUsername = prefs.getString('loginUsername') ?? prefs.getString('username'); // Get the latest username - String? savedPassword = prefs.getString('password'); // Get the saved password - - if (savedUsername == username && savedPassword == password) { - await _saveLoginDetails(username, password); - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => const HomeScreen()), - ); - } else { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Invalid username or password')), - ); - } -} - - - Future googleLogin() async { - try { - final GoogleSignInAccount? googleUser = await _googleSignIn.signIn(); - if (googleUser != null) { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('googleUser', googleUser.displayName ?? 'Google User'); - await prefs.setString('googleEmail', googleUser.email); - - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => const HomeScreen()), - ); - } - } catch (error) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Google Sign-In Failed: $error')), - ); - } - } - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.white, - body: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Image.asset( - 'assets/logo.png', - width: 1000, - height: 150, - ), - const SizedBox(height: 40), - InputField( - hintText: 'Username', - icon: Icons.person, - controller: usernameController, - ), - const SizedBox(height: 16), - InputField( - hintText: 'Password', - icon: Icons.lock, - obscureText: true, - controller: passwordController, - ), - const SizedBox(height: 16), - - /// Remember Me Checkbox - Centered - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Checkbox( - value: rememberMe, - onChanged: (value) { - setState(() { - rememberMe = value ?? false; - }); - }, - activeColor: Colors.grey[800], - ), - const Text( - 'Remember Me', - style: TextStyle( - color: Colors.black87, - fontSize: 16, - ), - ), - ], - ), - const SizedBox(height: 24), - - /// Login Button - ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], - foregroundColor: Colors.white, - minimumSize: const Size.fromHeight(50), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - ), - onPressed: login, - child: const Text('Login', style: TextStyle(fontSize: 18)), - ), - const SizedBox(height: 16), - - /// Horizontal Line with "or" - Row( - children: const [ - Expanded( - child: Divider(color: Colors.grey, thickness: 1), - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text("or", style: TextStyle(color: Colors.grey, fontSize: 16)), - ), - Expanded( - child: Divider(color: Colors.grey, thickness: 1), - ), - ], - ), - const SizedBox(height: 16), - - /// Google Sign-In Button (Styled same as Login) - ElevatedButton.icon( - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], // Match Login Button - foregroundColor: Colors.white, - minimumSize: const Size.fromHeight(50), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - ), - onPressed: googleLogin, - icon: const Icon(Icons.g_mobiledata, size: 30), // Google Icon - label: const Text('Sign in with Google', style: TextStyle(fontSize: 18)), - ), - const SizedBox(height: 20), - - /// Register Text (Styled in Blue) - GestureDetector( - onTap: () { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => const RegisterScreen()), - ); - }, - child: const Text( - "Don't have an account? Register", - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Colors.grey, // Better visibility - ), - ), - ), - ], - ), - ), - ), - ); - } -} diff --git a/lib/screens/preview_screen.dart b/lib/screens/preview_screen.dart index fbde9ac..d60dea1 100644 --- a/lib/screens/preview_screen.dart +++ b/lib/screens/preview_screen.dart @@ -1,6 +1,8 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; +import '../utils/target_colors.dart'; +import '../theme/app_theme.dart'; import 'package:flutter/services.dart' show rootBundle; import 'package:image/image.dart' as img; import 'package:path_provider/path_provider.dart'; @@ -273,121 +275,9 @@ class _PreviewScreenState extends State { "📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY"); } - Color _getBackgroundColorForTarget(String targetPath) { - // Map each target to its background color (extracted from first pixel of each image) - switch (targetPath) { - case 'assets/target.png': - return const Color(0xFFFFFFFF); // White - - case 'assets/targets/Target1.jpg': - return const Color(0xFFE8ECD5); // Light beige - - case 'assets/targets/Target2.jpg': - return const Color(0xFFC1DF87); // Light green - - case 'assets/targets/Target3.jpg': - return const Color(0xFFFEFEFE); // Off-white - - case 'assets/targets/Target4.jpg': - return const Color(0xFFD42931); // Red - - case 'assets/targets/Target5.jpg': - return const Color(0xFF02050A); // Very dark blue/black - - case 'assets/targets/Target6.jpg': - return const Color(0xFFF3E7D1); // Light beige - - case 'assets/targets/Target7.jpg': - return const Color(0xFFFFD454); // Bright yellow - - case 'assets/targets/Target8.jpg': - return const Color(0xFF1E5E81); // Dark teal blue - - case 'assets/targets/Target9.jpg': - return const Color(0xFFFEFEFC); // Off-white - - case 'assets/targets/Target10.jpg': - return const Color(0xFF98926E); // Olive green - - case 'assets/targets/Target11.jpg': - return const Color(0xFF13132B); // Dark blue - - case 'assets/targets/Target12.jpg': - return const Color(0xFFF5F4EF); // Off-white - - case 'assets/targets/Target13.jpg': - return const Color(0xFF174AA5); // Blue - - case 'assets/targets/Target14.jpg': - return const Color(0xFFFEE05E); // Light yellow - - case 'assets/targets/Target15.jpg': - return const Color(0xFFFFFFFF); // White - - case 'assets/targets/Target16.jpg': - return const Color(0xFF000000); // Black - - case 'assets/targets/Target17.jpg': - return const Color(0xFF21304D); // Dark blue - - case 'assets/targets/Target18.jpg': - return const Color(0xFF050608); // Very dark gray - - case 'assets/targets/Target19.jpg': - return const Color(0xFFF68527); // Warm orange - - case 'assets/targets/Target20.jpg': - return const Color(0xFFA9D9EF); // Light blue - - case 'assets/targets/Target21.jpg': - return const Color(0xFFDA6868); // Muted red - - case 'assets/targets/Target22.jpg': - return const Color(0xFFFBFAF6); // Off-white - - case 'assets/targets/Target23.jpg': - return const Color(0xFF000000); // Black - - case 'assets/targets/Target24.jpg': - return const Color(0xFFb7b7b7); // Gray - - case 'assets/targets/Target25.jpg': - return const Color(0xFF040308); // Very dark gray - - case 'assets/targets/Target26.jpg': - return const Color(0xFF161C2C); // Dark blue-gray - - case 'assets/targets/Target27.jpg': - return const Color(0xFF28A5DF); // Blue - - case 'assets/targets/Target28.jpg': - return const Color(0xFFFFFFFF); // White - - case 'assets/targets/Target29.jpg': - return const Color(0xFF180E27); // Dark purple - - case 'assets/targets/Target30.jpg': - return const Color(0xFFFDFDFB); // Off-white - - case 'assets/targets/Target31.jpg': - return const Color(0xFFC52736); // Red - - case 'assets/targets/Target32.jpg': - return const Color(0xFFFCF3EE); // Light cream - - case 'assets/targets/Target33.jpg': - return const Color(0xFFFCFCF3); // Very light off-white - - case 'assets/targets/Target34.jpg': - return const Color(0xFFFFFFFD); // Almost white - - case 'assets/targets/Target35.jpg': - return const Color(0xFFFFC5C4); // Light salmon - - default: - return Colors.grey[900]!; // Fallback to dark gray - } - } + // One source of truth for target colors (utils/target_colors.dart) + Color _getBackgroundColorForTarget(String targetPath) => + TargetColors.getBackgroundColor(targetPath); Future _loadBulletColor() async { final prefs = await SharedPreferences.getInstance(); @@ -940,6 +830,7 @@ class _PreviewScreenState extends State { final targetData = { 'date': dateString, 'totalScore': _totalScore, + 'bulletCount': widget.bulletCount, // shots fired; missed ones are absent from 'bullets' 'bullets': bulletsInDefaultCoordinates, }; @@ -1349,7 +1240,7 @@ class _PreviewScreenState extends State { children: [ // Training/Tournament Banner Container( - color: Colors.grey[300], + color: Surfaces.current.card, padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 10), child: Row( @@ -1359,9 +1250,9 @@ class _PreviewScreenState extends State { child: Text( _currentFolderName.isNotEmpty ? _currentFolderName - : 'No training selected', - style: const TextStyle( - color: Colors.black, + : _t('No training selected'), + style: TextStyle( + color: Surfaces.current.textPrimary, fontSize: 13, fontWeight: FontWeight.w600, ), @@ -1371,8 +1262,8 @@ class _PreviewScreenState extends State { if (_currentDate.isNotEmpty) Text( _currentDate, - style: const TextStyle( - color: Colors.black, + style: TextStyle( + color: Surfaces.current.textPrimary, fontSize: 11, ), ), @@ -1636,7 +1527,7 @@ class _PreviewScreenState extends State { Container( height: 30, decoration: BoxDecoration( - color: Colors.grey[300], + color: Surfaces.current.card, borderRadius: const BorderRadius .only( @@ -1649,11 +1540,11 @@ class _PreviewScreenState extends State { alignment: Alignment.center, child: Text( '${index + 1}', - style: const TextStyle( + style: TextStyle( fontWeight: FontWeight.bold, fontSize: 14, - color: Colors.black87, + color: Surfaces.current.textPrimary, ), ), ), @@ -1728,7 +1619,7 @@ class _PreviewScreenState extends State { Container( height: 30, decoration: BoxDecoration( - color: Colors.grey[300], + color: Surfaces.current.card, borderRadius: const BorderRadius .only( @@ -1741,11 +1632,11 @@ class _PreviewScreenState extends State { alignment: Alignment.center, child: Text( '$bulletNum', - style: const TextStyle( + style: TextStyle( fontWeight: FontWeight.bold, fontSize: 14, - color: Colors.black87, + color: Surfaces.current.textPrimary, ), ), ), @@ -1791,129 +1682,93 @@ class _PreviewScreenState extends State { ), ], ), - const SizedBox(height: 12), + // Room for the save button, which sticks up out of the bottom bar + const SizedBox(height: 40), ], ), _buildEditController(), ], ), - bottomNavigationBar: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Top bar - Total Score - Container( - color: Colors.grey[300], - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.track_changes, size: 20, color: Colors.black), - const SizedBox(width: 8), - Text( - _t("Total score:"), - style: const TextStyle( - fontSize: 13, - fontWeight: FontWeight.bold, - color: Colors.black, + // Same layout as the camera screen: number on the left, round white + // main action docked in the notch, secondary icons on the right. + floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, + floatingActionButton: FloatingActionButton( + backgroundColor: Colors.white, + onPressed: _saveToLastFolder, + tooltip: _t("Save"), + child: const Icon(Icons.save, color: Colors.black), + ), + bottomNavigationBar: BottomAppBar( + color: Colors.grey[900], + shape: const CircularNotchedRectangle(), + notchMargin: 8.0, + child: SizedBox( + height: 60, + child: Row( + children: [ + // Left - total score + Expanded( + child: Padding( + padding: const EdgeInsets.only(left: 16), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _t('Total').toUpperCase(), + style: const TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + letterSpacing: 1.2, + color: Colors.white54, + ), + ), + Text( + '$_totalScore', + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Colors.white, + height: 1.1, + ), + ), + ], ), ), - const SizedBox(width: 12), - Text( - "$_totalScore", - style: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.black, - ), - ), - ], - ), - ), - // Bottom bar - Action Buttons - BottomAppBar( - color: Colors.grey[900], - padding: EdgeInsets.zero, - child: SizedBox( - height: 60, - child: Row( - children: [ - // Plus button (left, no background) - Expanded( - child: Center( - child: IconButton( - icon: Stack( - alignment: Alignment.center, - children: [ - const Icon(Icons.folder, color: Colors.white, size: 24), - Positioned( - bottom: 0, - right: 0, - child: Container( - decoration: const BoxDecoration( - color: Colors.white, - shape: BoxShape.circle, - ), - padding: const EdgeInsets.all(2), - child: const Icon(Icons.add, color: Colors.grey, size: 10), - ), - ), - ], - ), - onPressed: _saveTargetDataWithDialog, - ), - ), - ), - // Save button (center with white background) - Expanded( - child: Center( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: SizedBox( - width: 60, - height: 40, - child: Container( - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - ), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: _saveToLastFolder, - borderRadius: BorderRadius.circular(8), - child: const Icon(Icons.save, - color: Colors.black, size: 20), - ), - ), - ), - ), - ), - ), - ), - // Edit button (right) - Expanded( - child: Center( - child: IconButton( - icon: Icon( - _isEditMode ? Icons.check : Icons.edit, - color: _isEditMode ? Colors.red : Colors.white, - size: 24, - ), - onPressed: () { - setState(() { - _isEditMode = !_isEditMode; - _selectedBulletIndexInEdit = null; - }); - }, - tooltip: _isEditMode ? _t("Done Editing") : _t("Edit Mode"), - ), - ), - ), - ], ), - ), + // Center space for FAB + const SizedBox(width: 80), + // Right - save to another folder, edit mode + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + IconButton( + icon: const Icon(Icons.create_new_folder_outlined, color: Colors.white, size: 24), + onPressed: _saveTargetDataWithDialog, + tooltip: _t("Save to folder"), + ), + IconButton( + icon: Icon( + _isEditMode ? Icons.check : Icons.edit, + color: _isEditMode ? Colors.red : Colors.white, + size: 24, + ), + onPressed: () { + setState(() { + _isEditMode = !_isEditMode; + _selectedBulletIndexInEdit = null; + }); + }, + tooltip: _isEditMode ? _t("Done Editing") : _t("Edit Mode"), + ), + const SizedBox(width: 4), + ], + ), + ), + ], ), - ], + ), ), ); } diff --git a/lib/screens/register_screen.dart b/lib/screens/register_screen.dart deleted file mode 100644 index 844f7a6..0000000 --- a/lib/screens/register_screen.dart +++ /dev/null @@ -1,180 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '../widgets/input_field.dart'; -import 'login_screen.dart'; - -class RegisterScreen extends StatefulWidget { - const RegisterScreen({super.key}); - - @override - State createState() => _RegisterScreenState(); -} - -class _RegisterScreenState extends State { - final usernameController = TextEditingController(); - final emailController = TextEditingController(); - final passwordController = TextEditingController(); - final confirmPasswordController = TextEditingController(); - - Future register() async { - String username = usernameController.text.trim(); - String email = emailController.text.trim(); - String password = passwordController.text.trim(); - String confirmPassword = confirmPasswordController.text.trim(); - - if (username.isEmpty || email.isEmpty || password.isEmpty || confirmPassword.isEmpty) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('All fields are required')), - ); - return; - } - - if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(email)) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Invalid email format')), - ); - return; - } - - if (password != confirmPassword) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Passwords do not match')), - ); - return; - } - - final prefs = await SharedPreferences.getInstance(); - - // Check if the username or email is already taken - String? existingUser = prefs.getString(username); - String? existingEmail = prefs.getString(email); - if (existingUser != null || existingEmail != null) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Username or Email already exists. Choose another.')), - ); - return; - } - - // Save user credentials in SharedPreferences - await prefs.setString(username, password); - await prefs.setString(email, username); // Store email linked to the username - - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Registration Successful! Please Login')), - ); - - // Redirect to Login Screen - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => const LoginScreen()), - ); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.white, - body: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - /// Logo - Image.asset( - 'assets/logo.png', - width: 1000, - height: 150, - ), - const SizedBox(height: 40), - - /// Username Field - InputField( - hintText: 'Username', - icon: Icons.person, - controller: usernameController, - ), - const SizedBox(height: 16), - - /// Email Field - InputField( - hintText: 'Email', - icon: Icons.email, - controller: emailController, - ), - const SizedBox(height: 16), - - /// Password Field - InputField( - hintText: 'Password', - icon: Icons.lock, - obscureText: true, - controller: passwordController, - ), - const SizedBox(height: 16), - - /// Confirm Password Field - InputField( - hintText: 'Confirm Password', - icon: Icons.lock, - obscureText: true, - controller: confirmPasswordController, - ), - const SizedBox(height: 24), - - /// Register Button - ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], // Match Login Button - foregroundColor: Colors.white, - minimumSize: const Size.fromHeight(50), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - ), - onPressed: register, - child: const Text('Register', style: TextStyle(fontSize: 18)), - ), - const SizedBox(height: 16), - - /// Horizontal Line with "or" (optional, in case Google Sign-Up is added) - Row( - children: const [ - Expanded( - child: Divider(color: Colors.grey, thickness: 1), - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text("or", style: TextStyle(color: Colors.grey, fontSize: 16)), - ), - Expanded( - child: Divider(color: Colors.grey, thickness: 1), - ), - ], - ), - const SizedBox(height: 16), - - /// Login Navigation (Styled in Blue) - GestureDetector( - onTap: () { - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => const LoginScreen()), - ); - }, - child: const Text( - "Already have an account? Login", - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Colors.grey, // Styled for better visibility - ), - ), - ), - ], - ), - ), - ), - ); - } -} diff --git a/lib/screens/session_screen.dart b/lib/screens/session_screen.dart new file mode 100644 index 0000000..ef79daa --- /dev/null +++ b/lib/screens/session_screen.dart @@ -0,0 +1,252 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import '../services/app_settings.dart'; +import '../services/target_repository.dart'; +import '../theme/app_theme.dart'; +import '../widgets/section.dart'; +import 'target_view.dart'; + +/// One training or tournament: its stats, its targets, and edit/delete actions. +class SessionScreen extends StatefulWidget { + final Session session; + + const SessionScreen({super.key, required this.session}); + + @override + State createState() => _SessionScreenState(); +} + +class _SessionScreenState extends State { + late Session _session = widget.session; + + Future _reload() async { + final sessions = await TargetRepository.loadSessions(); + final updated = sessions.where((s) => s.name == _session.name); + if (!mounted) return; + if (updated.isEmpty) { + Navigator.pop(context); // session no longer exists + } else { + setState(() => _session = updated.first); + } + } + + void _openTargets(List targets) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => TargetViewScreen( + jsonFiles: [for (final t in targets) t.file], + refreshFolders: _reload, + ), + ), + ); + } + + Future _edit() async { + final result = await showEditSessionDialog(context, _session); + if (result == null) return; + final ok = await TargetRepository.updateSession(_session, name: result.name, isTournament: result.isTournament); + if (!mounted) return; + if (!ok) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(AppSettings.instance.t('A folder with this name already exists'))), + ); + return; + } + _session = Session(name: result.name, isTournament: result.isTournament, date: _session.date, targets: _session.targets); + _reload(); + } + + Future _delete() async { + final s = AppSettings.instance; + final message = '${s.t('Are you sure you want to delete the folder')} "${_session.name}" ${s.t('and all of its contents?')}'; + if (await confirmDelete(context, message) != true) return; + await TargetRepository.deleteSession(_session); + if (mounted) Navigator.pop(context); + } + + Future _deleteTarget(TargetRecord target) async { + if (await confirmDelete(context, AppSettings.instance.t('Are you sure you want to delete this file?')) != true) return; + await TargetRepository.deleteTarget(target); + _reload(); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final s = AppSettings.instance; + final t = s.t; + final surf = Surfaces.current; + final session = _session; + final stats = ShooterStats.of([session]); + + return Scaffold( + backgroundColor: s.backgroundColor, + appBar: AppBar( + title: Text(session.name, style: const TextStyle(color: Colors.white)), + backgroundColor: AppTheme.bar, + iconTheme: const IconThemeData(color: Colors.white), + scrolledUnderElevation: 0, + actions: [ + IconButton(icon: const Icon(Icons.edit), tooltip: t('Edit'), onPressed: _edit), + IconButton(icon: const Icon(Icons.delete, color: Colors.red), tooltip: t('Delete'), onPressed: _delete), + ], + ), + body: ListView( + // Keep the last row clear of the system gesture bar (edge-to-edge) + padding: EdgeInsets.fromLTRB(16, 4, 16, 24 + MediaQuery.paddingOf(context).bottom), + children: [ + SectionHeader( + '${session.isTournament ? t('Tournament') : t('Training')} · ${DateFormat('d. M. yyyy').format(session.date)}', + ), + StatGrid(tiles: [ + StatTile(label: t('Total'), value: '${session.totalScore}', caption: targetCount(session.targets.length)), + StatTile( + label: t('Average per shot'), + value: stats.averagePerShot?.toStringAsFixed(2) ?? '–', + caption: shotCount(stats.shots), + ), + ]), + SectionHeader(t('Targets')), + if (session.targets.isEmpty) + Padding( + padding: const EdgeInsets.all(16), + child: Text(t('No targets in this folder'), style: TextStyle(color: surf.textSecondary)), + ) + else + GroupCard(children: [ + for (int i = 0; i < session.targets.length; i++) + SettingsTile( + title: '${t('Target')} ${i + 1}', + subtitle: '${DateFormat('HH:mm').format(session.targets[i].shotAt)} · ${shotCount(session.targets[i].shots)}', + onTap: () => _openTargets([session.targets[i]]), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${session.targets[i].score}', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: surf.textPrimary), + ), + IconButton( + icon: const Icon(Icons.delete, color: Colors.red, size: 20), + onPressed: () => _deleteTarget(session.targets[i]), + ), + ], + ), + ), + ]), + ], + ), + ); + }, + ); + } +} + +/// "1 target" / "5 targets", with Slovenian dual and plural forms. +String targetCount(int n) { + final s = AppSettings.instance; + if (s.language != 'Slovenian') return n == 1 ? '1 target' : '$n targets'; + final mod = n % 100; + final word = mod == 1 ? 'tarča' : mod == 2 ? 'tarči' : (mod == 3 || mod == 4) ? 'tarče' : 'tarč'; + return '$n $word'; +} + +/// "1 shot" / "5 shots", with Slovenian dual and plural forms. +String shotCount(int n) { + final s = AppSettings.instance; + if (s.language != 'Slovenian') return n == 1 ? '1 shot' : '$n shots'; + final mod = n % 100; + final word = mod == 1 ? 'strel' : mod == 2 ? 'strela' : (mod == 3 || mod == 4) ? 'streli' : 'strelov'; + return '$n $word'; +} + +Future confirmDelete(BuildContext context, String message) { + final s = AppSettings.instance; + return showDialog( + context: context, + builder: (dialog) => AlertDialog( + title: Text(s.t('Confirm Deletion')), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialog, false), + child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)), + ), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: Colors.red[700]), + onPressed: () => Navigator.pop(dialog, true), + child: Text(s.t('Yes, delete')), + ), + ], + ), + ); +} + +class SessionEdit { + final String name; + final bool isTournament; + + const SessionEdit(this.name, this.isTournament); +} + +/// Rename a session and choose training/tournament. +Future showEditSessionDialog(BuildContext context, Session session) { + final s = AppSettings.instance; + final controller = TextEditingController(text: session.name); + var isTournament = session.isTournament; + + return showDialog( + context: context, + builder: (dialog) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + title: Text(s.t('Folder Settings')), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: controller, + style: const TextStyle(color: Colors.white), + cursorColor: s.bulletColor, + decoration: InputDecoration( + filled: true, + fillColor: Colors.white10, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: s.bulletColor), + ), + ), + ), + const SizedBox(height: 8), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(s.t('Tournament'), style: const TextStyle(color: Colors.white)), + secondary: Icon(Icons.emoji_events, color: isTournament ? s.bulletColor : Colors.white54), + value: isTournament, + activeTrackColor: s.bulletColor, + onChanged: (v) => setDialogState(() => isTournament = v), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialog), + child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)), + ), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: s.bulletColor), + onPressed: () { + final name = controller.text.trim(); + if (name.isEmpty || name.contains('/')) return; + Navigator.pop(dialog, SessionEdit(name, isTournament)); + }, + child: Text(s.t('Save')), + ), + ], + ), + ), + ); +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index ddbe238..9a2e1d6 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,1309 +1,442 @@ import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '../utils/translations.dart'; -import '../utils/target_colors.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import '../services/app_settings.dart'; import '../services/notification_service.dart'; +import '../theme/app_theme.dart'; +import '../utils/target_colors.dart'; +import '../widgets/section.dart'; +import '../widgets/text_prompt.dart'; +import 'camera_settings_screen.dart'; -class SettingsScreen extends StatefulWidget { +class SettingsScreen extends StatelessWidget { const SettingsScreen({super.key}); - @override - State createState() => _SettingsScreenState(); -} - -class _SettingsScreenState extends State { - Color _backgroundColor = Colors.grey[900]!; - List _cameraIPs = List.generate(6, (index) => 'Not Set'); - - final List _defaultIPs = [ - '192.168.0.134:9081', - '192.168.0.134:9082', - '192.168.0.134:9083', - '192.168.0.134:9084', - '192.168.0.134:9085', - '192.168.0.134:9086', - ]; - - - String _selectedBulletColor = 'Blue'; - final List _bulletColors = [ - 'Blue', - 'Green', - 'Yellow', - 'Purple', - 'Cyan', - 'Teal', - 'Indigo', - 'Pink', - 'Lime', - 'Mint', - 'Orange', - 'Violet', - 'Amber', - 'Brown', - 'Grey', -]; - - int _notificationHours = 1; - final List _notificationHourOptions = [1, 2, 3, 6, 12, 24, 48]; - - bool _notifyDezuranje = true; - bool _notifySestanek = true; - bool _notifyTekma = true; - String _selectedLanguage = 'English'; - final List> _languages = [ - {'code': 'en', 'name': 'English', 'flag': '🇬🇧'}, - {'code': 'sl', 'name': 'Slovenian', 'flag': '🇸🇮'}, - ]; - - String _selectedTarget = 'assets/target.png'; - final List _availableTargets = [ - 'assets/target.png', - 'assets/targets/Target1.jpg', - 'assets/targets/Target2.jpg', - 'assets/targets/Target3.jpg', - 'assets/targets/Target4.jpg', - 'assets/targets/Target5.jpg', - 'assets/targets/Target6.jpg', - 'assets/targets/Target7.jpg', - 'assets/targets/Target8.jpg', - 'assets/targets/Target9.jpg', - 'assets/targets/Target10.jpg', - 'assets/targets/Target11.jpg', - 'assets/targets/Target12.jpg', - 'assets/targets/Target13.jpg', - 'assets/targets/Target14.jpg', - 'assets/targets/Target15.jpg', - 'assets/targets/Target16.jpg', - 'assets/targets/Target17.jpg', - 'assets/targets/Target18.jpg', - 'assets/targets/Target19.jpg', - 'assets/targets/Target20.jpg', - 'assets/targets/Target21.jpg', - 'assets/targets/Target22.jpg', - 'assets/targets/Target23.jpg', - 'assets/targets/Target24.jpg', - 'assets/targets/Target25.jpg', - 'assets/targets/Target26.jpg', - 'assets/targets/Target27.jpg', - 'assets/targets/Target28.jpg', - 'assets/targets/Target29.jpg', - 'assets/targets/Target30.jpg', - 'assets/targets/Target31.jpg', - 'assets/targets/Target32.jpg', - 'assets/targets/Target33.jpg', - 'assets/targets/Target34.jpg', - 'assets/targets/Target35.jpg', - ]; - - @override - void initState() { - super.initState(); - _loadCameraIPs(); - _loadBulletColor(); - _loadLanguage(); - _loadSelectedTarget(); - _loadNotificationSettings(); - } - - - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - 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 '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; // fallback - } -} - - Future _loadBulletColor() async { - final prefs = await SharedPreferences.getInstance(); - String savedColor = prefs.getString('bulletColor') ?? 'Blue'; - - // Fallback in case old color is no longer valid - if (!_bulletColors.contains(savedColor)) { - savedColor = 'Blue'; - await prefs.setString('bulletColor', savedColor); - } - - setState(() { - _selectedBulletColor = savedColor; - }); -} - -Future _saveBulletColor(String color) async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('bulletColor', color); - setState(() => _selectedBulletColor = color); -} - -Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - String savedLanguage = prefs.getString('language') ?? 'English'; - - setState(() { - _selectedLanguage = savedLanguage; - }); -} - -Future _saveLanguage(String language) async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('language', language); - setState(() => _selectedLanguage = language); -} - -Future _loadSelectedTarget() async { - final prefs = await SharedPreferences.getInstance(); - String savedTarget = prefs.getString('selectedTarget') ?? 'assets/target.png'; - - setState(() { - _selectedTarget = savedTarget; - _backgroundColor = TargetColors.getBackgroundColor(savedTarget); - }); -} - -Future _saveSelectedTarget(String target) async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('selectedTarget', target); - setState(() { - _selectedTarget = target; - _backgroundColor = TargetColors.getBackgroundColor(target); - }); -} - -String _getTargetDisplayName(String targetPath) { - if (targetPath == 'assets/target.png') { - return _t('Default Target'); - } - final targetName = targetPath - .replaceAll('assets/targets/', '') - .replaceAll('.jpg', ''); - return _t(targetName); -} - - Future _loadNotificationSettings() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _notificationHours = prefs.getInt('notificationHours_single') ?? 1; - _notifyDezuranje = prefs.getBool('notifyDezuranje') ?? true; - _notifySestanek = prefs.getBool('notifySestanek') ?? true; - _notifyTekma = prefs.getBool('notifyTekma') ?? true; - }); - } - - Future _saveNotificationHours(int hours) async { - final prefs = await SharedPreferences.getInstance(); - 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 { - final prefs = await SharedPreferences.getInstance(); - - List tempIPs = []; - - for (int i = 0; i < 6; i++) { - String key = 'cameraIP_${i + 1}'; - String? savedIP = prefs.getString(key); - - // If not saved, use default and write it to prefs - if (savedIP == null) { - await prefs.setString(key, _defaultIPs[i]); - tempIPs.add(_defaultIPs[i]); - } else { - tempIPs.add(savedIP); - } - } - - setState(() { - _cameraIPs = tempIPs; - }); -} - - Future _saveCameraIP(int index, String ip) async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('cameraIP_${index + 1}', ip); - _loadCameraIPs(); - } - - Future _clearCameraIP(int index) async { - final prefs = await SharedPreferences.getInstance(); - await prefs.remove('cameraIP_${index + 1}'); - _loadCameraIPs(); - } - - - void _editCameraIP(int index) { - TextEditingController controller = TextEditingController( - text: _cameraIPs[index], - ); - - showDialog( - context: context, - builder: (context) { - return RepaintBoundary( - child: Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), - child: StatefulBuilder( - builder: (context, setState) { - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - "${_t('Camera')} ${index + 1}", - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, - ), - textAlign: TextAlign.center, - ), - const SizedBox(height: 16), - - SizedBox( - width: double.infinity, - child: TextField( - controller: controller, - style: const TextStyle(color: Colors.white), - textAlign: TextAlign.center, - decoration: InputDecoration( - filled: true, - fillColor: Colors.grey[800], - hintText: _t("Enter Camera IP"), - hintStyle: const TextStyle(color: Colors.white54), - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(12), - borderSide: BorderSide.none, - ), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(12), - borderSide: BorderSide(color: _getColorFromName(_selectedBulletColor)), - ), - ), - ), - ), - const SizedBox(height: 24), - - // Save Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () async { - String newIP = controller.text.trim(); - if (newIP.isNotEmpty) { - await _saveCameraIP(index, newIP); - if (context.mounted) { - Navigator.pop(context); - } - } - }, - style: ElevatedButton.styleFrom( - backgroundColor: _getColorFromName(_selectedBulletColor), - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t("Save")), - ), - ), - const SizedBox(height: 12), - - // Reset Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () async { - await _clearCameraIP(index); - if (context.mounted) { - Navigator.pop(context); - } - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[700], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t("Reset to Default")), - ), - ), - const SizedBox(height: 12), - - // Cancel Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () => Navigator.pop(context), - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t("Cancel")), - ), - ), - ], - ); - }, - ), - ), - ), - ); - }, - ); -} - + static final Future _packageInfo = PackageInfo.fromPlatform(); @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: _backgroundColor, - body: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), - child: Column( - children: [ - const SizedBox(height: 8), - _buildLanguageSelector(), - const SizedBox(height: 16), - _buildAppearanceSelector(), - const SizedBox(height: 16), + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final s = AppSettings.instance; + final t = s.t; + final language = AppSettings.languages.firstWhere( + (l) => l['name'] == s.language, + orElse: () => AppSettings.languages.first, + ); - _buildNotificationSettings(), - const SizedBox(height: 16), - _buildCameraList(), + return ListView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), + children: [ + SectionHeader(t('Language')), + GroupCard(children: [ + SettingsTile( + leading: Text(language['flag']!, style: const TextStyle(fontSize: 22)), + title: t(language['name']!), + subtitle: s.followSystemLanguage ? t('Automatic (phone language)') : null, + onTap: () => _pickLanguage(context), + ), + ]), + + SectionHeader(t('Appearance')), + GroupCard(children: [ + SettingsTile( + title: t('Bullet color'), + valueLeading: _ColorDot(s.bulletColor, size: 18), + value: t(s.bulletColorName), + onTap: () => _pickBulletColor(context), + ), + SettingsTile( + title: t('Target'), + valueLeading: _TargetThumb(s.selectedTarget, size: 30), + value: s.targetName(s.selectedTarget), + onTap: () => _pickTarget(context), + ), + ]), + + SectionHeader(t('Club')), + GroupCard(children: [ + if (s.clubUnlocked) + SettingsTile( + leading: const Icon(Icons.verified_rounded, color: Colors.green), + title: t('Member access'), + subtitle: t('Calendar and contacts unlocked'), + value: t('Remove'), + onTap: () => _confirmLock(context), + ) + else + SettingsTile( + leading: Icon(Icons.lock_outline_rounded, color: Surfaces.current.textSecondary), + title: t('Club code'), + subtitle: t('Unlocks calendar and contacts'), + onTap: () => _enterClubCode(context), + ), + ]), + Padding( + padding: const EdgeInsets.fromLTRB(4, 8, 4, 0), + child: Text( + t('Member access is currently available only for SDK Kovinar Muta. Support for other clubs may be added in the future.'), + style: TextStyle(fontSize: 12, color: Surfaces.current.textSecondary), + ), + ), + + if (s.clubUnlocked) ...[ + SectionHeader(t('Notifications')), + GroupCard(children: [ + SettingsSwitchTile( + title: t('Dežuranje'), + value: s.notifyDezuranje, + activeColor: s.bulletColor, + onChanged: (v) => s.setNotifyDezuranje(v).then((_) => _reschedule()), + ), + SettingsSwitchTile( + title: t('Sestanek'), + value: s.notifySestanek, + activeColor: s.bulletColor, + onChanged: (v) => s.setNotifySestanek(v).then((_) => _reschedule()), + ), + SettingsSwitchTile( + title: t('Tekma'), + value: s.notifyTekma, + activeColor: s.bulletColor, + onChanged: (v) => s.setNotifyTekma(v).then((_) => _reschedule()), + ), + SettingsTile( + title: t('Remind me'), + value: _hoursBefore(s.reminderHours), + onTap: () => _pickReminder(context), + ), + ]), + ], + + SectionHeader(t('Cameras')), + GroupCard(children: [ + SettingsTile( + title: t('Camera Settings'), + value: _camerasSummary(s), + onTap: () => Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const CameraSettingsScreen()), + ), + ), + ]), + + const SizedBox(height: 28), + FutureBuilder( + future: _packageInfo, + builder: (context, snap) { + final info = snap.data; + if (info == null) return const SizedBox.shrink(); + return Text( + '${info.appName} ${info.version}', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: Surfaces.current.textSecondary), + ); + }, + ), + ], + ); + }, + ); + } + + static void _reschedule() => NotificationService().rescheduleFromCalendar(); + + Future _enterClubCode(BuildContext context) async { + final s = AppSettings.instance; + final code = await showTextPrompt( + context, + title: s.t('Club code'), + message: s.t('Unlocks calendar and contacts'), + confirmLabel: s.t('Unlock'), + ); + if (code == null || code.isEmpty || !context.mounted) return; + + // Unlocking takes about a second (slow key derivation on purpose) + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + final ok = await s.unlockClub(code); + if (!context.mounted) return; + Navigator.of(context).pop(); + + if (ok) _reschedule(); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(s.t(ok ? 'Club access unlocked' : 'Wrong club code')), + backgroundColor: ok ? Colors.green[700] : Colors.red[700], + )); + } + + Future _confirmLock(BuildContext context) async { + final s = AppSettings.instance; + final confirmed = await showDialog( + context: context, + builder: (dialog) => AlertDialog( + title: Text(s.t('Member access')), + content: Text(s.t('Remove club access from this phone?')), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialog, false), + child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)), + ), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: Colors.red[700]), + onPressed: () => Navigator.pop(dialog, true), + child: Text(s.t('Remove')), + ), + ], + ), + ); + if (confirmed == true) { + await s.lockClub(); + _reschedule(); // cancels reminders + } + } + + static String _hoursBefore(int hours) => + AppSettings.instance.t('{n} h before').replaceAll('{n}', '$hours'); + + // Location names (e.g. "Kovinar · Doma"), or a hint when nothing is set up yet. + static String _camerasSummary(AppSettings s) { + final locations = s.cameras.locations; + return locations.isEmpty ? s.t('Not set up') : locations.join(' · '); + } + + void _pickLanguage(BuildContext context) { + final s = AppSettings.instance; + showModalBottomSheet( + context: context, + builder: (sheet) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _SheetTitle(s.t('Select Language')), + SheetOption( + leading: const Text('📱', style: TextStyle(fontSize: 22)), + label: '${s.t('Automatic (phone language)')} · ${s.t(AppSettings.systemLanguage)}', + selected: s.followSystemLanguage, + selectedColor: s.bulletColor, + onTap: () { + s.useSystemLanguage(); + Navigator.pop(sheet); + }, + ), + for (final lang in AppSettings.languages) + SheetOption( + leading: Text(lang['flag']!, style: const TextStyle(fontSize: 22)), + label: s.t(lang['name']!), + selected: !s.followSystemLanguage && lang['name'] == s.language, + selectedColor: s.bulletColor, + onTap: () { + s.setLanguage(lang['name']!); + Navigator.pop(sheet); + }, + ), + const SizedBox(height: 8), ], ), ), ); } - Widget _buildLanguageSelector() { - final selectedLang = _languages.firstWhere( - (lang) => lang['name'] == _selectedLanguage, - orElse: () => _languages[0], - ); - - return Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 0), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: Colors.grey[900], - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), + void _pickReminder(BuildContext context) { + final s = AppSettings.instance; + showModalBottomSheet( + context: context, + builder: (sheet) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _SheetTitle(s.t('Remind me')), + for (final h in AppSettings.reminderHourOptions) + SheetOption( + label: _hoursBefore(h), + selected: h == s.reminderHours, + selectedColor: s.bulletColor, + onTap: () { + s.setReminderHours(h).then((_) => _reschedule()); + Navigator.pop(sheet); + }, ), - ), - child: Row( - children: [ - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 12), - Text( - _t("Language"), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ], - ), - ), - // Content - GestureDetector( - onTap: _showLanguagePopup, - child: Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(12), - bottomRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - Text( - selectedLang['flag'] ?? '🌐', - style: const TextStyle(fontSize: 20), - ), - const SizedBox(width: 12), - Expanded( - child: Text( - _t(selectedLang['name'] ?? 'English'), - style: const TextStyle(color: Colors.black87, fontSize: 14), - ), - ), - const Icon(Icons.chevron_right, color: Colors.black54), - ], - ), - ), - ), - ], + const SizedBox(height: 8), + ], + ), ), ); } - Widget _buildAppearanceSelector() { - return Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 0), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: Colors.grey[900], - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 12), - Text( - _t("Appearance"), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ], - ), - ), - // Content - GestureDetector( - onTap: _showAppearancePopup, - child: Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(12), - bottomRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - // Preview box with target - ClipRRect( - borderRadius: BorderRadius.circular(8), - child: Container( - width: 70, - height: 70, - decoration: BoxDecoration( - border: Border.all(color: Colors.black12), - borderRadius: BorderRadius.circular(8), - color: TargetColors.getBackgroundColor(_selectedTarget), - ), - child: Image.asset( - _selectedTarget, - fit: BoxFit.contain, - errorBuilder: (context, error, stackTrace) { - return Icon(Icons.image_not_supported, color: Colors.grey[400]); - }, - ), - ), - ), - const SizedBox(width: 16), - // Details section - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text( - _t("Bullet:"), - style: const TextStyle( - color: Colors.black54, - fontSize: 12, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(width: 8), - Container( - width: 16, - height: 16, - decoration: BoxDecoration( - color: _getColorFromName(_selectedBulletColor), - shape: BoxShape.circle, - border: Border.all(color: Colors.black26, width: 1), - ), - ), - const SizedBox(width: 6), - Expanded( - child: Text( - _selectedBulletColor, - style: const TextStyle( - color: Colors.black87, - fontSize: 12, - fontWeight: FontWeight.w500, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - const SizedBox(height: 8), - Row( - children: [ - Text( - _t("Target:"), - style: const TextStyle( - color: Colors.black54, - fontSize: 12, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(width: 8), - Expanded( - child: Text( - _getTargetDisplayName(_selectedTarget), - style: const TextStyle( - color: Colors.black87, - fontSize: 12, - fontWeight: FontWeight.w500, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - ], - ), - ), - const SizedBox(width: 8), - Icon(Icons.chevron_right, color: Colors.black54), - ], - ), - ), - ), - ], - ), - ); - } - -void _showLanguagePopup() { - showDialog( - context: context, - builder: (context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + void _pickBulletColor(BuildContext context) { + final s = AppSettings.instance; + showModalBottomSheet( + context: context, + builder: (sheet) => SafeArea( child: Padding( - padding: const EdgeInsets.all(24), + padding: const EdgeInsets.fromLTRB(20, 0, 20, 20), child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text( - _t("Select Language"), - style: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - const SizedBox(height: 20), - ..._languages.map((lang) { - final isSelected = lang['name'] == _selectedLanguage; - - return Padding( - padding: const EdgeInsets.only(bottom: 12.0), - child: SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () async { - await _saveLanguage(lang['name']!); - if (context.mounted) { - Navigator.of(context).pop(); - } + _SheetTitle(s.t('Bullet color')), + Wrap( + spacing: 16, + runSpacing: 16, + alignment: WrapAlignment.center, + children: [ + for (final entry in AppSettings.bulletColors.entries) + GestureDetector( + onTap: () { + s.setBulletColor(entry.key); + Navigator.pop(sheet); }, - style: ElevatedButton.styleFrom( - backgroundColor: isSelected - ? _getColorFromName(_selectedBulletColor) - : Colors.grey[800], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - lang['flag']!, - style: const TextStyle(fontSize: 20), - ), - const SizedBox(width: 12), - Text( - _t(lang['name']!), - style: const TextStyle(fontSize: 16), - ), - ], + child: _ColorDot( + entry.value, + size: 48, + selected: entry.key == s.bulletColorName, ), ), - ), - ); - }), - const SizedBox(height: 8), - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: Text(_t("Cancel"), style: const TextStyle(color: Colors.white70)), + ], ), ], ), ), - ); - }, - ); -} + ), + ); + } - void _showAppearancePopup() { - String previewBulletColor = _selectedBulletColor; - String previewTarget = _selectedTarget; - int selectedTab = 0; // 0 for Bullet, 1 for Target - - showDialog( + void _pickTarget(BuildContext context) { + final s = AppSettings.instance; + showModalBottomSheet( context: context, - builder: (context) { - return StatefulBuilder( - builder: (context, innerSetState) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - insetPadding: const EdgeInsets.all(24), - child: SizedBox( - height: 700, - width: 400, - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - children: [ - Text( - _t("Appearance Settings"), - style: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - const SizedBox(height: 20), - - // Preview with multiple bullets on target - ALWAYS ON TOP - Container( - width: double.infinity, - height: 280, - decoration: BoxDecoration( - color: TargetColors.getBackgroundColor(previewTarget), - borderRadius: BorderRadius.circular(12), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(12), - child: Stack( - alignment: Alignment.center, - clipBehavior: Clip.hardEdge, - children: [ - Center( - child: Image.asset( - previewTarget, - fit: BoxFit.contain, - errorBuilder: (context, error, stackTrace) { - return Container( - color: Colors.grey[800], - child: const Center( - child: Icon(Icons.image_not_supported, color: Colors.white54), - ), - ); - }, - ), - ), - // Multiple preview bullets scattered around - Positioned( - left: 90, - top: 100, - child: _buildPreviewBullet(previewBulletColor), - ), - Positioned( - right: 90, - top: 110, - child: _buildPreviewBullet(previewBulletColor), - ), - Positioned( - left: 100, - bottom: 90, - child: _buildPreviewBullet(previewBulletColor), - ), - Positioned( - right: 95, - bottom: 100, - child: _buildPreviewBullet(previewBulletColor), - ), - Positioned( - left: 110, - top: 140, - child: _buildPreviewBullet(previewBulletColor), - ), - Positioned( - right: 110, - bottom: 140, - child: _buildPreviewBullet(previewBulletColor), - ), - ], - ), - ), - ), - const SizedBox(height: 24), - - // Tab Buttons and Content as one unit - Expanded( - child: Container( - decoration: BoxDecoration( - color: Colors.grey[800], - borderRadius: BorderRadius.circular(8), - ), - child: Column( - children: [ - // Selection Buttons (Tabs) - Row( - children: [ - Expanded( - child: ElevatedButton( - onPressed: () => innerSetState(() => selectedTab = 0), - style: ElevatedButton.styleFrom( - backgroundColor: selectedTab == 0 - ? _getColorFromName(previewBulletColor) - : Colors.grey[700], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 12), - shape: RoundedRectangleBorder( - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(8), - ), - ), - ), - child: Text( - _t("Bullet"), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - Expanded( - child: ElevatedButton( - onPressed: () => innerSetState(() => selectedTab = 1), - style: ElevatedButton.styleFrom( - backgroundColor: selectedTab == 1 - ? _getColorFromName(previewBulletColor) - : Colors.grey[700], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 12), - shape: RoundedRectangleBorder( - borderRadius: const BorderRadius.only( - topRight: Radius.circular(8), - ), - ), - ), - child: Text( - _t("Target"), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - ], - ), - // Tab Content - Expanded( - child: SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: selectedTab == 0 - ? Center( - child: Wrap( - spacing: 20, - runSpacing: 20, - alignment: WrapAlignment.center, - children: _bulletColors.map((colorName) { - final color = _getColorFromName(colorName); - final isSelected = colorName == previewBulletColor; - return GestureDetector( - onTap: () => innerSetState(() => previewBulletColor = colorName), - child: Container( - width: 62, - height: 62, - decoration: BoxDecoration( - color: color, - shape: BoxShape.circle, - border: Border.all( - color: isSelected ? Colors.white : Colors.white24, - width: isSelected ? 4 : 2, - ), - ), - ), - ); - }).toList(), - ), - ) - : Column( - mainAxisSize: MainAxisSize.min, - children: _availableTargets.map((targetPath) { - final isSelected = targetPath == previewTarget; - final displayName = _getTargetDisplayName(targetPath); - return Padding( - padding: const EdgeInsets.only(bottom: 8.0), - child: SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () => innerSetState(() => previewTarget = targetPath), - style: ElevatedButton.styleFrom( - backgroundColor: isSelected ? _getColorFromName(previewBulletColor) : Colors.grey[700], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), - ), - child: Text( - displayName, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle(fontSize: 12), - ), - ), - ), - ); - }).toList(), - ), - ), - ), - ], - ), - ), - ), - const SizedBox(height: 16), - // Action Buttons - Row( + isScrollControlled: true, + builder: (sheet) => DraggableScrollableSheet( + expand: false, + initialChildSize: 0.75, + maxChildSize: 0.95, + builder: (context, scroll) => Column( + children: [ + _SheetTitle(s.t('Target')), + Expanded( + child: GridView.builder( + controller: scroll, + padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.paddingOf(context).bottom), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + mainAxisSpacing: 12, + crossAxisSpacing: 12, + childAspectRatio: 0.8, + ), + itemCount: AppSettings.targets.length, + itemBuilder: (context, i) { + final path = AppSettings.targets[i]; + final selected = path == s.selectedTarget; + return GestureDetector( + onTap: () { + s.setTarget(path); + Navigator.pop(sheet); + }, + child: Column( children: [ Expanded( - child: ElevatedButton( - onPressed: () async { - await _saveBulletColor(previewBulletColor); - await _saveSelectedTarget(previewTarget); - if (context.mounted) { - Navigator.of(context).pop(); - } - }, - style: ElevatedButton.styleFrom( - backgroundColor: _getColorFromName(previewBulletColor), - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 12), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: selected ? s.bulletColor : Colors.transparent, + width: 3, + ), ), - child: Text(_t("Apply")), + child: _TargetThumb(path, radius: 9), ), ), - const SizedBox(width: 12), - Expanded( - child: TextButton( - onPressed: () => Navigator.of(context).pop(), - child: Text(_t("Cancel"), style: const TextStyle(color: Colors.white70)), + const SizedBox(height: 6), + Text( + s.targetName(path), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: selected ? Colors.white : Colors.white70, + fontWeight: selected ? FontWeight.bold : FontWeight.normal, ), ), ], ), - ], - ), - ), + ); + }, ), - ); - }, - ); - }, + ), + ], + ), + ), ); } +} - Widget _buildPreviewBullet(String bulletColor) { - const double bulletOpacity = 0.8; +class _SheetTitle extends StatelessWidget { + final String text; + + const _SheetTitle(this.text); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text( + text, + style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), + ), + ); + } +} + +class _ColorDot extends StatelessWidget { + final Color color; + final double size; + final bool selected; + + const _ColorDot(this.color, {required this.size, this.selected = false}); + + @override + Widget build(BuildContext context) { return Container( - width: 14, - height: 14, + width: size, + height: size, decoration: BoxDecoration( - color: _getColorFromName(bulletColor).withValues(alpha: bulletOpacity), + color: color, shape: BoxShape.circle, border: Border.all( - color: Colors.black, - width: 1, + color: selected ? Colors.white : Colors.black26, + width: selected ? 3 : 1, + ), + ), + child: selected ? const Icon(Icons.check_rounded, color: Colors.white) : null, + ); + } +} + +class _TargetThumb extends StatelessWidget { + final String path; + final double? size; + final double radius; + + const _TargetThumb(this.path, {this.size, this.radius = 6}); + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: BorderRadius.circular(radius), + child: Container( + width: size, + height: size, + color: TargetColors.getBackgroundColor(path), + padding: const EdgeInsets.all(2), + child: Image.asset( + path, + fit: BoxFit.contain, + cacheWidth: 300, + errorBuilder: (_, __, ___) => const Icon(Icons.image_not_supported, color: Colors.white54), ), ), ); } - - Widget _buildCameraList() { - return Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 0), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: Colors.grey[900], - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 12), - Text( - _t("Camera Settings"), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ], - ), - ), - // Content - all cameras - ...List.generate(6, (index) { - return GestureDetector( - onTap: () => _editCameraIP(index), - child: Column( - children: [ - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: index == 5 - ? const BorderRadius.only( - bottomLeft: Radius.circular(12), - bottomRight: Radius.circular(12), - ) - : null, - border: index < 5 - ? Border( - bottom: BorderSide( - color: Colors.grey[400]!, - width: 1, - ), - ) - : null, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "${_t('Camera')} ${index + 1}", - style: const TextStyle( - fontWeight: FontWeight.bold, - color: Colors.black87, - ), - ), - Text( - _cameraIPs[index], - style: const TextStyle(color: Colors.black54), - ), - ], - ), - const Icon(Icons.chevron_right, color: Colors.black54), - ], - ), - ), - ], - ), - ); - }), - ], - ), - ); -} - - Widget _buildNotifyToggle(String label, bool value, ValueChanged onChanged) { - return Padding( - padding: const EdgeInsets.symmetric(vertical: 4), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text(label, style: const TextStyle(color: Colors.black87, fontSize: 14)), - Switch( - value: value, - onChanged: onChanged, - activeThumbColor: _getColorFromName(_selectedBulletColor), - ), - ], - ), - ); - } - - Widget _buildNotificationSettings() { - return Container( - margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 0), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Header - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: Colors.grey[900], - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12), - ), - ), - child: Row( - children: [ - Container( - width: 4, - height: 16, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2), - ), - ), - const SizedBox(width: 12), - Expanded( - child: Text( - _t('Notifications'), - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ), - GestureDetector( - onTap: () async { - await NotificationService().scheduleTestNotification(); - }, - child: const Icon(Icons.notifications_active_outlined, color: Colors.white, size: 20), - ), - ], - ), - ), - // Hours before picker - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(12), - bottomRight: Radius.circular(12), - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 4), - Text( - _t('Event types'), - style: const TextStyle( - fontWeight: FontWeight.bold, - color: Colors.black87, - ), - ), - const SizedBox(height: 8), - _buildNotifyToggle(_t('Dežuranje'), _notifyDezuranje, (v) { - setState(() => _notifyDezuranje = v); - _saveNotifyType('notifyDezuranje', v); - }), - _buildNotifyToggle(_t('Sestanek'), _notifySestanek, (v) { - setState(() => _notifySestanek = v); - _saveNotifyType('notifySestanek', v); - }), - _buildNotifyToggle(_t('Tekma'), _notifyTekma, (v) { - setState(() => _notifyTekma = v); - _saveNotifyType('notifyTekma', v); - }), - const SizedBox(height: 16), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - _t('Notify before event'), - style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.black87), - ), - Text( - _notificationHours == 1 - ? '1 ${_t('hour')}' - : '$_notificationHours ${_t('hours')}', - style: TextStyle( - color: _getColorFromName(_selectedBulletColor), - fontWeight: FontWeight.bold, - fontSize: 13, - ), - ), - ], - ), - const SizedBox(height: 12), - ClipRRect( - borderRadius: BorderRadius.circular(10), - child: Row( - children: _notificationHourOptions.asMap().entries.map((entry) { - final i = entry.key; - final hours = entry.value; - final isSelected = hours == _notificationHours; - final label = '${hours}h'; - final isFirst = i == 0; - final isLast = i == _notificationHourOptions.length - 1; - return Expanded( - child: GestureDetector( - onTap: () => _saveNotificationHours(hours), - child: Container( - padding: const EdgeInsets.symmetric(vertical: 10), - decoration: BoxDecoration( - color: isSelected - ? _getColorFromName(_selectedBulletColor) - : Colors.grey[700], - border: Border( - right: isLast - ? BorderSide.none - : BorderSide(color: Colors.grey[600]!, width: 1), - ), - borderRadius: isFirst - ? const BorderRadius.only(topLeft: Radius.circular(10), bottomLeft: Radius.circular(10)) - : isLast - ? const BorderRadius.only(topRight: Radius.circular(10), bottomRight: Radius.circular(10)) - : BorderRadius.zero, - ), - child: Text( - label, - textAlign: TextAlign.center, - style: TextStyle( - color: Colors.white, - fontSize: 12, - fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - ), - ), - ), - ), - ); - }).toList(), - ), - ), - ], - ), - ), - ], - ), - ); - } } diff --git a/lib/screens/spectator_screen.dart b/lib/screens/spectator_screen.dart index 48ff921..8000bc5 100644 --- a/lib/screens/spectator_screen.dart +++ b/lib/screens/spectator_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_mjpeg/flutter_mjpeg.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../utils/translations.dart'; +import '../services/wifi_binding.dart'; class SpectatorScreen extends StatefulWidget { final String selectedLanguage; @@ -20,18 +21,28 @@ class _SpectatorScreenState extends State { List _enabledCameras = List.generate(6, (_) => false); // Which cameras have IPs configured List> _cameras = []; Color _bulletColor = Colors.blue; // default/fallback bullet color + late final Future _wifiReady; + @override void initState() { super.initState(); + _wifiReady = WifiBinding.acquire(); _loadCameras(); _loadBulletColor(); } + @override + void dispose() { + WifiBinding.release(); + super.dispose(); + } + String _t(String key) { return AppTranslations.translate(key, widget.selectedLanguage); } Future _loadCameras() async { + await _wifiReady; // streams must start after traffic is pinned to Wi-Fi final prefs = await SharedPreferences.getInstance(); List> cameras = []; List enabledCameras = List.generate(6, (_) => false); diff --git a/lib/screens/stream_screen.dart b/lib/screens/stream_screen.dart index 986c61e..5ed1995 100644 --- a/lib/screens/stream_screen.dart +++ b/lib/screens/stream_screen.dart @@ -12,41 +12,34 @@ import 'yolo_detector.dart'; import 'preview_screen.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import '../utils/translations.dart'; +import '../widgets/camera_sheet.dart'; +import '../widgets/image_settings.dart'; +import '../services/wifi_binding.dart'; -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 +// Top-level: runs in background isolate via compute(). +// Crops the capture to a square; filters are already baked into the screenshot. +Uint8List _processStreamImage(Uint8List bytes) { final decoded = img.decodeImage(bytes)!; final w = decoded.width, h = decoded.height; final size = w < h ? w : h; - img.Image cropped = img.copyCrop(decoded, + final 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)); + return Uint8List.fromList(img.encodeJpg(cropped)); } class CameraStreamScreen extends StatefulWidget { - final int cameraIndex; + final int cameraIndex; // shooting position 1–6 + final String? ip; // chosen camera; falls back to the saved IP of the position + final String? location; // strelišče the camera belongs to - const CameraStreamScreen({super.key, required this.cameraIndex}); + const CameraStreamScreen( + {super.key, required this.cameraIndex, this.ip, this.location}); + + // Image settings are kept per camera, i.e. per position and location + String get settingsId => + location == null ? '$cameraIndex' : '${cameraIndex}_$location'; + String get title => + location == null ? '$cameraIndex' : '$cameraIndex · $location'; @override State createState() => _CameraStreamScreenState(); @@ -60,15 +53,11 @@ class _CameraStreamScreenState extends State final ScreenshotController _screenshotController = ScreenshotController(); final TransformationController _transformationController = TransformationController(); - ImageFilterType _selectedFilter = ImageFilterType.none; + ImageAdjustments _image = const ImageAdjustments(); late YOLODetector _yoloDetector; int _numberOfBullets = 5; - // Brightness and contrast controls - double _brightness = 0.0; - double _contrast = 1.0; - late AnimationController _zoomAnimController; Animation? _zoomAnimation; Matrix4? _originalMatrix; @@ -121,10 +110,13 @@ class _CameraStreamScreenState extends State bool _reloadEnabled = false; bool _waitEnabled = false; + late final Future _wifiReady; + Future _loadAllPrefs() async { + await _wifiReady; // stream must start after traffic is pinned to Wi-Fi final prefs = await SharedPreferences.getInstance(); - final filterIndex = prefs.getInt('selectedFilter'); - final url = prefs.getString('cameraIP_${widget.cameraIndex}'); + final image = await ImageAdjustments.load(widget.settingsId); + final url = widget.ip ?? prefs.getString('cameraIP_${widget.cameraIndex}'); final streamUrl = (url != null && url.trim().isNotEmpty) ? (url.startsWith(RegExp(r"https?://")) ? url : "http://$url") : null; @@ -137,15 +129,9 @@ class _CameraStreamScreenState extends State 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; + _image = image; _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; @@ -184,6 +170,7 @@ class _CameraStreamScreenState extends State @override void initState() { super.initState(); + _wifiReady = WifiBinding.acquire(); _loadAllPrefs(); YOLODetector.create().then((detector) => _yoloDetector = detector); @@ -218,12 +205,6 @@ class _CameraStreamScreenState extends State }); } - Future _saveBrightnessContrast() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setDouble('brightness', _brightness); - await prefs.setDouble('contrast', _contrast); - } - Color _getColorFromName(String colorName) { switch (colorName.toLowerCase()) { case 'blue': @@ -268,6 +249,8 @@ class _CameraStreamScreenState extends State statusBarIconBrightness: Brightness.light, // white icons systemNavigationBarColor: Colors.grey[900], systemNavigationBarIconBrightness: Brightness.light, + // No grey scrim behind 3-button navigation; we paint the strip ourselves + systemNavigationBarContrastEnforced: false, ), ); } @@ -282,7 +265,8 @@ class _CameraStreamScreenState extends State Future _loadStreamUrl() async { final prefs = await SharedPreferences.getInstance(); - String? url = prefs.getString('cameraIP_${widget.cameraIndex}'); + String? url = + widget.ip ?? prefs.getString('cameraIP_${widget.cameraIndex}'); setState(() { _streamUrl = (url != null && url.trim().isNotEmpty) @@ -328,8 +312,7 @@ class _CameraStreamScreenState extends State final dir = await getApplicationDocumentsDirectory(); final path = '${dir.path}/ip_capture_temp.jpg'; - final processedBytes = await compute( - _processStreamImage, [imageBytes, _selectedFilter.index]); + final processedBytes = await compute(_processStreamImage, imageBytes); final file = File(path)..writeAsBytesSync(processedBytes); // Detect objects in the image using YOLO @@ -396,232 +379,49 @@ class _CameraStreamScreenState extends State } void _showImageSettingsDialog() { - 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, - 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(), - ), - ], - ), - 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: () { - setState(() { - _brightness = 0.0; - _contrast = 1.0; - }); - setDialogState(() {}); - _saveBrightnessContrast(); - }, - child: Text(_t('Reset'), - style: const TextStyle(color: Colors.white54)), - ), - ), - ], - ), - ), - ); - }, - ); - }, + showImageSettingsSheet( + context, + initial: _image, + settingsId: widget.settingsId, + cameraLabel: "${_t('Camera')} ${widget.title}", + accent: _bulletColor, + t: _t, + onChanged: (value) => setState(() => _image = value), ); } 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); - } + showCameraSheet( + context, + builder: (sheet) => StatefulBuilder( + builder: (context, setSheetState) { + Future setCount(int count) async { + final clamped = count.clamp(1, 10); + setState(() => _numberOfBullets = clamped); + setSheetState(() {}); + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt('bulletCount', clamped); + } - 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')), - ), - ], - ), + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + CameraSheetHeader( + title: _t('Select the number of bullets'), + subtitle: '1 – 10', ), - ); - }, - ); - }, + SheetStepper( + value: _numberOfBullets, + min: 1, + max: 10, + accent: _bulletColor, + onChanged: setCount, + ), + const SizedBox(height: 8), + ], + ); + }, + ), ); } @@ -706,6 +506,7 @@ class _CameraStreamScreenState extends State _flashController.dispose(); _zoomAnimController.dispose(); _yoloDetector.close(); + WifiBinding.release(); _restoreScreenSettings(); _setSystemBarStyle(); super.dispose(); @@ -1470,8 +1271,8 @@ class _CameraStreamScreenState extends State } void _showTimerDialog() { - showDialog( - context: context, + showCameraSheet( + context, builder: (ctx) => _TimerConfigDialog( shootSeconds: _shootSeconds, reloadSeconds: _reloadSecondsRaw, @@ -1510,142 +1311,11 @@ class _CameraStreamScreenState extends State ); } - ColorFilter _buildColorFilter() { - // 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, - ]; - } - - // 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)); - } - - List _multiplyMatrices(List a, List b) { - // For simplicity, just apply brightness/contrast on top of base filter - final result = []; - - for (int i = 0; i < a.length; i++) { - result.add(a[i]); - } - - // 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( appBar: AppBar( - title: Text("${_t('Camera')} ${widget.cameraIndex}"), + title: Text("${_t('Camera')} ${widget.title}"), backgroundColor: Colors.grey[900], foregroundColor: Colors.white, leading: IconButton( @@ -1682,26 +1352,29 @@ class _CameraStreamScreenState extends State height: constraints.maxHeight, child: RepaintBoundary( child: ColorFiltered( - colorFilter: _buildColorFilter(), - child: Mjpeg( - key: ValueKey(_streamUrl), - stream: _streamUrl!, - isLive: true, - fit: BoxFit.contain, - error: (context, error, stackTrace) { - // Mark as error so we can display error placeholder outside filters - WidgetsBinding.instance - .addPostFrameCallback((_) { - if (mounted) { - setState(() { - _isError = true; - }); - } - }); - return SizedBox.expand( - child: Container(color: Colors.black), - ); - }, + colorFilter: _image.colorFilter, + child: RotatedBox( + quarterTurns: _image.quarterTurns, + child: Mjpeg( + key: ValueKey(_streamUrl), + stream: _streamUrl!, + isLive: true, + fit: BoxFit.contain, + error: (context, error, stackTrace) { + // Mark as error so we can display error placeholder outside filters + WidgetsBinding.instance + .addPostFrameCallback((_) { + if (mounted) { + setState(() { + _isError = true; + }); + } + }); + return SizedBox.expand( + child: Container(color: Colors.black), + ); + }, + ), ), ), ), @@ -1942,12 +1615,13 @@ class _CameraStreamScreenState extends State const SizedBox(height: 12), Row( children: [ - const Icon(Icons.signal_cellular_off, + // Mobile data can stay on: the app pins camera traffic to Wi-Fi + const Icon(Icons.videocam_outlined, color: Colors.white, size: 18), const SizedBox(width: 12), Expanded( child: Text( - _t("Mobile data is disabled"), + _t("Cameras and PC are switched on"), style: const TextStyle( color: Colors.white70, fontSize: 14, @@ -2230,187 +1904,158 @@ class _TimerConfigDialogState extends State<_TimerConfigDialog> { @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, + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CameraSheetHeader( + title: _t('Shooting Timer'), + icon: Icons.timer, + iconColor: c, + ), + + // Single / Full target + Row( 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), + _buildTargetPill(false), + const SizedBox(width: 8), + _buildTargetPill(true), + ], + ), + const SizedBox(height: 12), + const Divider(color: Colors.white12, height: 4), + const SizedBox(height: 8), - // Single / Full target + // 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: [ - _buildTargetPill(false), + Icon(Icons.article_outlined, + color: _changeTargetEnabled ? Colors.green : Colors.white38, + size: 18), 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, + Text(_t('Change target sign'), + style: TextStyle( color: _changeTargetEnabled - ? Colors.green + ? Colors.white : 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); - }, - ), + fontSize: 15)), ], ), + Switch( + value: _changeTargetEnabled, + activeThumbColor: Colors.green, + onChanged: (v) { + setState(() => _changeTargetEnabled = v); + widget.onChangeTargetToggle(v); + }, + ), ], ), - ), + ], ); } } diff --git a/lib/screens/target_screen.dart b/lib/screens/target_screen.dart index b36757c..4f70cf8 100644 --- a/lib/screens/target_screen.dart +++ b/lib/screens/target_screen.dart @@ -1,153 +1,133 @@ import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'stream_screen.dart'; // Import the camera stream screen -import '../utils/translations.dart'; -import '../utils/target_colors.dart'; +import '../services/app_settings.dart'; +import '../theme/app_theme.dart'; +import 'camera_settings_screen.dart'; +import 'stream_screen.dart'; -class TargetScreen extends StatefulWidget { +/// Shooting: one tile per position. A position with cameras at several +/// locations asks where we are shooting before opening the stream. +class TargetScreen extends StatelessWidget { const TargetScreen({super.key}); - @override - State createState() => _TargetScreenState(); -} - -class _TargetScreenState extends State { - List _cameraButtonsEnabled = - List.generate(6, (_) => false); // Initially, all buttons are disabled - String _selectedLanguage = 'English'; - late Color _backgroundColor; - - @override - void initState() { - super.initState(); - // Initialize with default target background color - _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); - _loadLanguage(); - _loadSelectedTargetColor(); - _loadCameraData(); - } - - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - 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); - }); - } - - /// Load the camera IPs from SharedPreferences and update button status - Future _loadCameraData() async { - final prefs = await SharedPreferences.getInstance(); - final List defaultIPs = [ - '192.168.0.134:9081', - '192.168.0.134:9082', - '192.168.0.134:9083', - '192.168.0.134:9084', - '192.168.0.134:9085', - '192.168.0.134:9086', - ]; - - List cameraDataStatus = List.generate(6, (index) { - String key = 'cameraIP_${index + 1}'; - - if (!prefs.containsKey(key)) { - prefs.setString(key, defaultIPs[index]); - return true; // Default set - } - - String? ip = prefs.getString(key); - return ip != null && ip.isNotEmpty && ip != 'Not Set'; - }); - - if (!mounted) return; - setState(() { - _cameraButtonsEnabled = cameraDataStatus; - }); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: _backgroundColor, - body: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32), + void _openPosition(BuildContext context, int position) { + final s = AppSettings.instance; + final cameras = s.cameras.camerasAt(position); + if (cameras.isEmpty) { + Navigator.push(context, MaterialPageRoute(builder: (_) => const CameraSettingsScreen())); + return; + } + if (cameras.length == 1) { + _openStream(context, position, cameras.keys.first, cameras.values.first); + return; + } + showModalBottomSheet( + context: context, + builder: (sheet) => SafeArea( child: Column( + mainAxisSize: MainAxisSize.min, children: [ - Expanded( - child: Column( - children: [ - // Camera grid (6 cameras) - Expanded( - child: GridView.builder( - itemCount: 6, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - mainAxisSpacing: 16, - crossAxisSpacing: 16, - childAspectRatio: 1, - ), - itemBuilder: (context, index) { - final isEnabled = _cameraButtonsEnabled[index]; - return GestureDetector( - onTap: isEnabled - ? () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => - CameraStreamScreen(cameraIndex: index + 1), - ), - ); - } - : null, - child: Container( - decoration: BoxDecoration( - color: isEnabled ? Colors.grey[900] : Colors.grey[300], - borderRadius: BorderRadius.circular(16), - ), - padding: const EdgeInsets.all(16), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - Icons.videocam_rounded, - color: isEnabled ? Colors.white : Colors.grey[500], - size: 36, - ), - const SizedBox(height: 12), - Text( - "${_t('Camera')} ${index + 1}", - textAlign: TextAlign.center, - style: TextStyle( - color: isEnabled ? Colors.white : Colors.grey[600], - fontSize: 20, - fontWeight: FontWeight.w600, - ), - ), - ], - ), - ), - ); - }, - ), - ), - ], - ), + Text( + s.t('Where are we shooting?'), + style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), ), + Text( + '${s.t('Camera')} $position', + style: const TextStyle(color: Colors.white54, fontSize: 12), + ), + const SizedBox(height: 8), + for (final entry in cameras.entries) + ListTile( + leading: Icon(Icons.place_rounded, color: s.bulletColor), + title: Text(entry.key, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600)), + subtitle: Text(entry.value, style: const TextStyle(color: Colors.white54)), + trailing: entry.key == s.cameras.activeLocation + ? Icon(Icons.check_rounded, color: s.bulletColor) + : const Icon(Icons.chevron_right, color: Colors.white38), + onTap: () { + Navigator.pop(sheet); + _openStream(context, position, entry.key, entry.value); + }, + ), + const SizedBox(height: 8), ], ), ), ); } + + void _openStream(BuildContext context, int position, String location, String ip) { + AppSettings.instance.setActiveLocation(location); + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CameraStreamScreen(cameraIndex: position, ip: ip, location: location), + ), + ); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final s = AppSettings.instance; + final setup = s.cameras; + + return GridView.builder( + padding: const EdgeInsets.fromLTRB(24, 32, 24, 32), + itemCount: setup.positions, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisSpacing: 16, + crossAxisSpacing: 16, + ), + itemBuilder: (context, i) { + final position = i + 1; + final locations = setup.camerasAt(position).keys.toList(); + final enabled = locations.isNotEmpty; + final surf = Surfaces.current; + + return Material( + color: enabled ? Colors.grey[900] : surf.card, + borderRadius: BorderRadius.circular(16), + child: InkWell( + borderRadius: BorderRadius.circular(16), + onTap: () => _openPosition(context, position), + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + enabled ? Icons.videocam_rounded : Icons.videocam_off_rounded, + color: enabled ? Colors.white : surf.textSecondary, + size: 36, + ), + const SizedBox(height: 12), + Text( + '${s.t('Camera')} $position', + style: TextStyle( + color: enabled ? Colors.white : surf.textSecondary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 4), + Text( + enabled ? locations.join(' · ') : s.t('Not set up'), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: enabled ? Colors.white60 : surf.textSecondary), + ), + ], + ), + ), + ), + ); + }, + ); + }, + ); + } } diff --git a/lib/screens/target_view.dart b/lib/screens/target_view.dart index 3089e87..83f20b3 100644 --- a/lib/screens/target_view.dart +++ b/lib/screens/target_view.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; +import '../theme/app_theme.dart'; import 'package:flutter/services.dart' show rootBundle; import 'dart:convert'; import 'package:image/image.dart' as img; @@ -85,9 +86,9 @@ class _TargetViewScreenState extends State { _backgroundColor = _getBackgroundColorForTarget(selectedTarget); } - Color _getBackgroundColorForTarget(String targetPath) { - return TargetColors.getBackgroundColor(targetPath); - } + // One source of truth for target colors (utils/target_colors.dart) + Color _getBackgroundColorForTarget(String targetPath) => + TargetColors.getBackgroundColor(targetPath); Future _loadBulletColor() async { final prefs = await SharedPreferences.getInstance(); @@ -708,7 +709,7 @@ class _TargetViewScreenState extends State { Container( height: 30, decoration: BoxDecoration( - color: Colors.grey[300], + color: Surfaces.current.card, borderRadius: const BorderRadius.only( topLeft: Radius.circular(16), topRight: Radius.circular(16), @@ -719,10 +720,10 @@ class _TargetViewScreenState extends State { fit: BoxFit.scaleDown, child: Text( '${count}x', - style: const TextStyle( + style: TextStyle( fontWeight: FontWeight.bold, fontSize: 14, - color: Colors.black87, + color: Surfaces.current.textPrimary, ), ), ), @@ -801,7 +802,7 @@ class _TargetViewScreenState extends State { Container( height: 30, decoration: BoxDecoration( - color: Colors.grey[300], + color: Surfaces.current.card, borderRadius: const BorderRadius.only( topLeft: Radius.circular(16), topRight: Radius.circular(16), @@ -810,10 +811,10 @@ class _TargetViewScreenState extends State { alignment: Alignment.center, child: Text( '${index + 1}', - style: const TextStyle( + style: TextStyle( fontWeight: FontWeight.bold, fontSize: 14, - color: Colors.black87, + color: Surfaces.current.textPrimary, ), ), ), diff --git a/lib/services/app_settings.dart b/lib/services/app_settings.dart new file mode 100644 index 0000000..53d4e2f --- /dev/null +++ b/lib/services/app_settings.dart @@ -0,0 +1,329 @@ +import 'dart:convert'; +import 'dart:isolate'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../models/camera_setup.dart'; +import '../models/contact.dart'; +import 'club_crypto.dart'; +import '../utils/target_colors.dart'; +import '../utils/translations.dart'; + +/// Single source of truth for user settings. Loaded once in main(); widgets +/// rebuild via ListenableBuilder(listenable: AppSettings.instance, ...). +/// +/// Writes the same SharedPreferences keys the rest of the app already reads, +/// so screens can migrate to this class one at a time. +class AppSettings extends ChangeNotifier { + AppSettings._(); + static final AppSettings instance = AppSettings._(); + + static const String defaultTarget = 'assets/target.png'; + static const List reminderHourOptions = [1, 2, 3, 6, 12, 24, 48]; + + static const List> languages = [ + {'name': 'English', 'flag': '🇬🇧'}, + {'name': 'Slovenian', 'flag': '🇸🇮'}, + ]; + + static const Map bulletColors = { + 'Blue': Colors.blue, + 'Green': Colors.green, + 'Yellow': Colors.yellow, + 'Purple': Colors.purple, + 'Cyan': Colors.cyan, + 'Teal': Colors.teal, + 'Indigo': Colors.indigo, + 'Pink': Colors.pink, + 'Lime': Colors.lime, + 'Mint': Colors.greenAccent, + 'Orange': Colors.orange, + 'Violet': Colors.deepPurpleAccent, + 'Amber': Colors.amber, + 'Brown': Colors.brown, + 'Grey': Colors.grey, + }; + + static final List targets = [ + defaultTarget, + for (int i = 1; i <= 35; i++) + if (i != 13) 'assets/targets/Target$i.jpg', // 13 was removed + ]; + + late SharedPreferences _prefs; + + String _language = 'English'; + bool _followSystemLanguage = false; + String _bulletColorName = 'Blue'; + String _selectedTarget = defaultTarget; + int _reminderHours = 1; + bool _notifyDezuranje = true; + bool _notifySestanek = true; + bool _notifyTekma = true; + CameraSetup _cameras = const CameraSetup(); + List? _clubContacts; // null until the club code is entered + + String get language => _language; + bool get followSystemLanguage => _followSystemLanguage; + + // Phone language (or Android 13+ per-app language) mapped to our two languages + static String get systemLanguage => + WidgetsBinding.instance.platformDispatcher.locale.languageCode == 'sl' ? 'Slovenian' : 'English'; + String get bulletColorName => _bulletColorName; + Color get bulletColor => bulletColors[_bulletColorName] ?? Colors.blue; + String get selectedTarget => _selectedTarget; + Color get backgroundColor => TargetColors.getBackgroundColor(_selectedTarget); + bool get isLightBackground => backgroundColor.computeLuminance() > 0.4; + int get reminderHours => _reminderHours; + bool get notifyDezuranje => _notifyDezuranje; + bool get notifySestanek => _notifySestanek; + bool get notifyTekma => _notifyTekma; + CameraSetup get cameras => _cameras; + + /// Calendar, reminders and contacts are for club members only. + bool get clubUnlocked => _clubContacts != null; + List get clubContacts => _clubContacts ?? const []; + + String t(String key) => AppTranslations.translate(key, _language); + + String targetName(String path) { + if (path == defaultTarget) return t('Default Target'); + return t(path.replaceAll('assets/targets/', '').replaceAll('.jpg', '')); + } + + Future load() async { + _prefs = await SharedPreferences.getInstance(); + // New installs follow the phone; an explicit earlier choice stays as it is + final saved = _prefs.getString('language'); + _followSystemLanguage = _prefs.getBool('languageFollowsSystem') ?? saved == null; + _language = _followSystemLanguage ? systemLanguage : saved!; + await _prefs.setString('language', _language); // other screens read this key + WidgetsBinding.instance.platformDispatcher.onLocaleChanged = _onSystemLocaleChanged; + + final color = _prefs.getString('bulletColor') ?? 'Blue'; + _bulletColorName = bulletColors.containsKey(color) ? color : 'Blue'; + + _selectedTarget = _prefs.getString('selectedTarget') ?? defaultTarget; + if (!targets.contains(_selectedTarget)) { + // Target no longer shipped: fall back so screens reading prefs don't load a missing image + _selectedTarget = defaultTarget; + await _prefs.setString('selectedTarget', defaultTarget); + } + _reminderHours = _prefs.getInt('notificationHours_single') ?? 1; + _notifyDezuranje = _prefs.getBool('notifyDezuranje') ?? true; + _notifySestanek = _prefs.getBool('notifySestanek') ?? true; + _notifyTekma = _prefs.getBool('notifyTekma') ?? true; + + final clubData = _prefs.getString('clubData'); + if (clubData != null) { + _clubContacts = _parseContacts(clubData); + _refreshClubData(); // picks up contact changes shipped in an app update + } + + final setup = _prefs.getString('cameraSetup'); + if (setup != null) { + _cameras = CameraSetup.fromJson(jsonDecode(setup) as Map); + } else { + // Before locations existed: the six single IPs become location "Kovinar" + final old = { + for (int p = 1; p <= CameraSetup.maxPositions; p++) + if ((_prefs.getString('cameraIP_$p') ?? '').isNotEmpty) p: {'Kovinar': _prefs.getString('cameraIP_$p')!}, + }; + if (old.isNotEmpty) { + _cameras = CameraSetup(locations: const ['Kovinar'], ips: old, activeLocation: 'Kovinar'); + await _saveCameras(); + } + } + } + + Future setLanguage(String value) async { + _language = value; + _followSystemLanguage = false; + notifyListeners(); + await _prefs.setString('language', value); + await _prefs.setBool('languageFollowsSystem', false); + } + + Future useSystemLanguage() async { + _followSystemLanguage = true; + _language = systemLanguage; + notifyListeners(); + await _prefs.setString('language', _language); + await _prefs.setBool('languageFollowsSystem', true); + } + + void _onSystemLocaleChanged() { + if (_followSystemLanguage && systemLanguage != _language) useSystemLanguage(); + } + + Future setBulletColor(String name) async { + _bulletColorName = name; + notifyListeners(); + await _prefs.setString('bulletColor', name); + } + + Future setTarget(String path) async { + _selectedTarget = path; + notifyListeners(); + await _prefs.setString('selectedTarget', path); + } + + Future setReminderHours(int hours) async { + _reminderHours = hours; + notifyListeners(); + await _prefs.setInt('notificationHours_single', hours); + await _prefs.setStringList('notificationHours', [hours.toString()]); + } + + Future setNotifyDezuranje(bool v) => _setNotify('notifyDezuranje', v, () => _notifyDezuranje = v); + Future setNotifySestanek(bool v) => _setNotify('notifySestanek', v, () => _notifySestanek = v); + Future setNotifyTekma(bool v) => _setNotify('notifyTekma', v, () => _notifyTekma = v); + + Future _setNotify(String key, bool value, VoidCallback apply) async { + apply(); + notifyListeners(); + await _prefs.setBool(key, value); + } + + Future _setCameras(CameraSetup next) async { + _cameras = next; + notifyListeners(); + await _saveCameras(); + } + + // Also fills the old cameraIP_1…6 keys (last chosen location) for screens + // that still read them, like the spectator view. + Future _saveCameras() async { + await _prefs.setString('cameraSetup', jsonEncode(_cameras.toJson())); + for (int p = 1; p <= CameraSetup.maxPositions; p++) { + final at = p <= _cameras.positions ? _cameras.camerasAt(p) : {}; + final ip = at[_cameras.activeLocation] ?? (at.isEmpty ? '' : at.values.first); + await _prefs.setString('cameraIP_$p', ip); + } + } + + Future addLocation(String name) async { + if (name.isEmpty || _cameras.locations.contains(name)) return false; + await _setCameras(_cameras.copyWith(locations: [..._cameras.locations, name])); + return true; + } + + Future renameLocation(String from, String to) async { + if (to.isEmpty || (to != from && _cameras.locations.contains(to))) return false; + final ips = _cameras.ipsCopy(); + for (final m in ips.values) { + if (m.containsKey(from)) m[to] = m.remove(from)!; + } + await _setCameras(CameraSetup( + locations: [for (final l in _cameras.locations) l == from ? to : l], + positions: _cameras.positions, + ips: ips, + activeLocation: _cameras.activeLocation == from ? to : _cameras.activeLocation, + clubLocation: _cameras.clubLocation == from ? to : _cameras.clubLocation, + )); + return true; + } + + Future removeLocation(String name) async { + final ips = _cameras.ipsCopy(); + for (final m in ips.values) { + m.remove(name); + } + await _setCameras(CameraSetup( + locations: [for (final l in _cameras.locations) if (l != name) l], + positions: _cameras.positions, + ips: ips, + activeLocation: _cameras.activeLocation == name ? null : _cameras.activeLocation, + clubLocation: _cameras.clubLocation == name ? null : _cameras.clubLocation, + )); + } + + Future setPositionCount(int count) => + _setCameras(_cameras.copyWith(positions: count.clamp(1, CameraSetup.maxPositions))); + + Future setCameraIp(int position, String location, String ip) { + final ips = _cameras.ipsCopy(); + (ips[position] ??= {})[location] = ip.trim(); + return _setCameras(_cameras.copyWith(ips: ips)); + } + + /// Points every position of [location] at one host with consecutive ports (9081, 9082, ...). + Future setLocationHost(String location, String host) { + final ips = _cameras.ipsCopy(); + for (int p = 1; p <= _cameras.positions; p++) { + (ips[p] ??= {})[location] = '$host:${CameraSetup.firstPort + p - 1}'; + } + return _setCameras(_cameras.copyWith(ips: ips)); + } + + Future setActiveLocation(String location) => _setCameras(_cameras.copyWith(activeLocation: location)); + + // Club data may carry the club's cameras: {"cameras": {"location": "Kovinar", "ips": [...]}} + Future _applyClubCameras(String plaintext) async { + final data = (jsonDecode(plaintext) as Map)['cameras'] as Map?; + if (data == null) return; + final location = data['location'] as String; + final clubIps = [for (final ip in data['ips'] as List) ip as String]; + final ips = _cameras.ipsCopy(); + for (int i = 0; i < clubIps.length && i < CameraSetup.maxPositions; i++) { + (ips[i + 1] ??= {})[location] = clubIps[i]; + } + await _setCameras(_cameras.copyWith( + locations: _cameras.locations.contains(location) ? null : [location, ..._cameras.locations], + positions: clubIps.length.clamp(_cameras.positions, CameraSetup.maxPositions), + ips: ips, + activeLocation: _cameras.activeLocation ?? location, + clubLocation: location, + )); + } + + /// Decrypts the bundled club data with [code]. Returns false if the code is wrong. + Future unlockClub(String code) async { + final encrypted = await _loadClubAsset(); + if (encrypted == null) return false; // asset missing: run tool/encrypt_club_data.dart + + // Key derivation is deliberately slow; keep it off the UI thread + final plaintext = await Isolate.run(() => ClubCrypto.decrypt(encrypted, code)); + if (plaintext == null) return false; + + _clubContacts = _parseContacts(plaintext); + notifyListeners(); + await _applyClubCameras(plaintext); + await _prefs.setString('clubData', plaintext); + await _prefs.setString('clubCode', code); + await _prefs.setString('clubDataSource', encrypted); + return true; + } + + Future lockClub() async { + _clubContacts = null; + notifyListeners(); + final clubLocation = _cameras.clubLocation; + if (clubLocation != null) await removeLocation(clubLocation); + await _prefs.remove('clubData'); + await _prefs.remove('clubCode'); + await _prefs.remove('clubDataSource'); + } + + /// If the bundled club.enc changed since unlocking (new app version), decrypt + /// it again with the saved code. A changed club code locks the phone again. + Future _refreshClubData() async { + final encrypted = await _loadClubAsset(); + final code = _prefs.getString('clubCode'); + if (encrypted == null || encrypted == _prefs.getString('clubDataSource')) return; + if (code == null || !await unlockClub(code)) await lockClub(); + } + + static Future _loadClubAsset() async { + try { + return await rootBundle.loadString('assets/club.enc'); + } catch (_) { + return null; + } + } + + static List _parseContacts(String json) { + final list = (jsonDecode(json) as Map)['contacts'] as List; + return list.map((c) => Contact.fromJson(c as Map)).toList(); + } +} diff --git a/lib/services/club_crypto.dart b/lib/services/club_crypto.dart new file mode 100644 index 0000000..ab6a10d --- /dev/null +++ b/lib/services/club_crypto.dart @@ -0,0 +1,49 @@ +import 'dart:convert'; +import 'package:cryptography/cryptography.dart'; + +/// Encrypts/decrypts the club data (contacts) with the club code as the key, +/// so the data can ship inside the public app but is unreadable without the code. +/// +/// No Flutter imports: also used by tool/encrypt_club_data.dart. +/// File format (assets/club.enc): JSON {v, salt, nonce, cipher, mac}, base64 values. +class ClubCrypto { + static const int _iterations = 100000; + static final _aes = AesGcm.with256bits(); + + /// Codes are compared ignoring case and surrounding spaces. + static String normalize(String code) => code.trim().toLowerCase(); + + static Future _deriveKey(String code, List salt) { + return Pbkdf2(macAlgorithm: Hmac.sha256(), iterations: _iterations, bits: 256) + .deriveKeyFromPassword(password: normalize(code), nonce: salt); + } + + static Future encrypt(String plaintext, String code) async { + final salt = SecretKeyData.random(length: 16).bytes; + final key = await _deriveKey(code, salt); + final box = await _aes.encrypt(utf8.encode(plaintext), secretKey: key); + return jsonEncode({ + 'v': 1, + 'salt': base64Encode(salt), + 'nonce': base64Encode(box.nonce), + 'cipher': base64Encode(box.cipherText), + 'mac': base64Encode(box.mac.bytes), + }); + } + + /// Returns the plaintext, or null if the code is wrong. + static Future decrypt(String encrypted, String code) async { + final data = jsonDecode(encrypted) as Map; + final key = await _deriveKey(code, base64Decode(data['salt'])); + final box = SecretBox( + base64Decode(data['cipher']), + nonce: base64Decode(data['nonce']), + mac: Mac(base64Decode(data['mac'])), + ); + try { + return utf8.decode(await _aes.decrypt(box, secretKey: key)); + } on SecretBoxAuthenticationError { + return null; + } + } +} diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index ea2577a..6b7a178 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -3,6 +3,7 @@ import 'package:timezone/timezone.dart' as tz; import 'package:timezone/data/latest.dart' as tz; import 'package:flutter_timezone/flutter_timezone.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../services/app_settings.dart'; import '../services/google_calendar_service.dart'; class NotificationService { @@ -92,6 +93,10 @@ class NotificationService { /// Fetches the calendar and reschedules all reminders. Call on app start /// and whenever notification settings change. Future rescheduleFromCalendar() async { + if (!AppSettings.instance.clubUnlocked) { + await cancelAll(); // reminders are a club-member feature + return; + } final service = GoogleCalendarService(); try { final now = DateTime.now(); @@ -172,28 +177,6 @@ class NotificationService { } catch (_) {} } - Future scheduleTestNotification() async { - try { - await initialize(); - final prefs = await SharedPreferences.getInstance(); - final isSlovenian = (prefs.getString('language') ?? 'English') == 'Slovenian'; - await _plugin.show( - 9999, - isSlovenian ? 'Testno obvestilo' : 'Test Notification', - isSlovenian ? 'Obvestila delujejo!' : 'Notifications are working!', - _notifDetails, - ); - final in10s = DateTime.now().add(const Duration(seconds: 10)); - await _scheduleNotification( - id: 9998, - title: isSlovenian ? 'Načrtovano testno obvestilo' : 'Scheduled Test', - body: isSlovenian ? 'Načrtovana obvestila delujejo!' : 'Scheduled notifications are working!', - scheduledDate: in10s, - mode: await _scheduleMode(), - ); - } catch (_) {} - } - Future _scheduleNotification({ required int id, required String title, diff --git a/lib/services/target_repository.dart b/lib/services/target_repository.dart new file mode 100644 index 0000000..9c6b803 --- /dev/null +++ b/lib/services/target_repository.dart @@ -0,0 +1,217 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:path_provider/path_provider.dart'; + +/// One saved target (a JSON file written by the preview screen). +class TargetRecord { + final File file; + final DateTime shotAt; + final int score; + final int shots; + + const TargetRecord( + {required this.file, + required this.shotAt, + required this.score, + required this.shots}); +} + +/// A folder of targets: one training or tournament. +class Session { + final String name; + final bool isTournament; + final DateTime date; + final List targets; // oldest first + + const Session( + {required this.name, + required this.isTournament, + required this.date, + required this.targets}); + + int get totalScore => targets.fold(0, (sum, t) => sum + t.score); + int get shots => targets.fold(0, (sum, t) => sum + t.shots); + double? get averagePerShot => shots == 0 ? null : totalScore / shots; + List get files => [for (final t in targets) t.file]; + + /// The same session limited to targets with [shots] bullets (null = all). + Session onlyShots(int? shots) => shots == null + ? this + : Session(name: name, isTournament: isTournament, date: date, targets: [ + for (final t in targets) + if (t.shots == shots) t, + ]); +} + +/// Aggregates over any set of sessions (trainings or tournaments of one format). +class ShooterStats { + final int sessions; + final int targets; + final int shots; + final TargetRecord? best; + final double? averageTarget; + final double? averagePerShot; + + const ShooterStats._({ + required this.sessions, + required this.targets, + required this.shots, + required this.best, + required this.averageTarget, + required this.averagePerShot, + }); + + factory ShooterStats.of(List sessions) { + final all = [for (final s in sessions) ...s.targets]; + final shots = all.fold(0, (sum, t) => sum + t.shots); + final total = all.fold(0, (sum, t) => sum + t.score); + final ranked = [...all]..sort((a, b) => b.score.compareTo(a.score)); + final mean = all.isEmpty ? null : total / all.length; + + return ShooterStats._( + sessions: sessions.length, + targets: all.length, + shots: shots, + best: ranked.isEmpty ? null : ranked.first, + averageTarget: mean, + averagePerShot: shots == 0 ? null : total / shots, + ); + } +} + +/// Reads and edits the saved targets under /saved_images//. +class TargetRepository { + static Future _root() async { + final dir = Directory( + '${(await getApplicationDocumentsDirectory()).path}/saved_images'); + if (!await dir.exists()) await dir.create(recursive: true); + return dir; + } + + /// Sessions, newest first. With [year], only that year's target files are read. + static Future> loadSessions({int? year}) async { + final sessions = []; + + for (final folder in await _folders()) { + if (year != null && folder.date.year != year) continue; + final targets = []; + for (final file in folder.targetFiles) { + final record = await _readTarget(file); + if (record != null) targets.add(record); + } + targets.sort((a, b) => a.shotAt.compareTo(b.shotAt)); + sessions.add(Session( + name: folder.name, + isTournament: folder.isTournament, + date: folder.date, + targets: targets, + )); + } + + sessions.sort((a, b) => b.date.compareTo(a.date)); + return sessions; + } + + /// Years that have at least one session, newest first. Reads only metadata. + static Future> years() async { + final years = {for (final f in await _folders()) f.date.year}.toList(); + return years..sort((a, b) => b.compareTo(a)); + } + + // Cheap pass over the folders: metadata + file names, no target files read + static Future> _folders() async { + final root = await _root(); + final result = <_FolderInfo>[]; + for (final folder in root.listSync().whereType()) { + final meta = await _readMetadata(folder); + final files = [ + for (final f in folder.listSync().whereType()) + if (f.path.endsWith('.json') && !f.path.endsWith('metadata.json')) f, + ]; + final fileTimes = files.map(_timeFromFileName).whereType().toList()..sort(); + result.add(_FolderInfo( + name: folder.path.split('/').last, + isTournament: meta['isTournament'] == true, + date: DateTime.tryParse(meta['createdAt'] ?? '') ?? + (fileTimes.isNotEmpty ? fileTimes.first : folder.statSync().changed), + targetFiles: files, + )); + } + return result; + } + + static Future> _readMetadata(Directory folder) async { + final file = File('${folder.path}/metadata.json'); + if (!await file.exists()) return {}; + try { + return jsonDecode(await file.readAsString()) as Map; + } catch (_) { + return {}; + } + } + + static Future _readTarget(File file) async { + try { + final data = + jsonDecode(await file.readAsString()) as Map; + final score = data['totalScore']; + return TargetRecord( + file: file, + shotAt: _timeFromFileName(file) ?? file.statSync().modified, + score: score is int ? score : 0, + // Older saves have no bulletCount: fall back to the detected bullets + shots: data['bulletCount'] as int? ?? + (data['bullets'] as List?)?.length ?? + 0, + ); + } catch (_) { + return null; + } + } + + // File names look like target_2026-10-26_17-5-3.json (see preview_screen _performSave) + static DateTime? _timeFromFileName(File file) { + final match = RegExp(r'target_(\d+)-(\d+)-(\d+)_(\d+)-(\d+)-(\d+)\.json$') + .firstMatch(file.path); + if (match == null) return null; + final p = [for (int i = 1; i <= 6; i++) int.parse(match.group(i)!)]; + return DateTime(p[0], p[1], p[2], p[3], p[4], p[5]); + } + + /// Renames a session and/or changes its type. Returns false if the new name is taken. + static Future updateSession(Session session, + {required String name, required bool isTournament}) async { + final root = await _root(); + var folder = Directory('${root.path}/${session.name}'); + if (name != session.name) { + final target = Directory('${root.path}/$name'); + if (await target.exists()) return false; + folder = await folder.rename(target.path); + } + final metaFile = File('${folder.path}/metadata.json'); + final meta = await _readMetadata(folder); + await metaFile.writeAsString(jsonEncode({ + 'isTournament': isTournament, + 'createdAt': meta['createdAt'] ?? session.date.toIso8601String(), + })); + return true; + } + + static Future deleteSession(Session session) async { + final folder = Directory('${(await _root()).path}/${session.name}'); + if (await folder.exists()) await folder.delete(recursive: true); + } + + static Future deleteTarget(TargetRecord target) async { + if (await target.file.exists()) await target.file.delete(); + } +} + +class _FolderInfo { + final String name; + final bool isTournament; + final DateTime date; + final List targetFiles; + + const _FolderInfo({required this.name, required this.isTournament, required this.date, required this.targetFiles}); +} diff --git a/lib/services/wifi_binding.dart b/lib/services/wifi_binding.dart new file mode 100644 index 0000000..7b0e26a --- /dev/null +++ b/lib/services/wifi_binding.dart @@ -0,0 +1,29 @@ +import 'dart:io'; +import 'package:flutter/services.dart'; + +/// Routes the app's traffic over Wi-Fi while camera screens are open, so the +/// cameras stay reachable when the range Wi-Fi has no internet and Android +/// would otherwise prefer mobile data. Other apps are not affected. +class WifiBinding { + static const _channel = MethodChannel('si.sdkkovinar.app/network'); + static int _users = 0; + + /// Call from initState; await before connecting to a camera. + static Future acquire() async { + _users++; + if (_users > 1 || !Platform.isAndroid) return; + try { + await _channel.invokeMethod('bindToWifi'); + } catch (_) {} + } + + /// Call from dispose. + static Future release() async { + if (_users == 0) return; + _users--; + if (_users > 0 || !Platform.isAndroid) return; + try { + await _channel.invokeMethod('unbind'); + } catch (_) {} + } +} diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart new file mode 100644 index 0000000..14106fc --- /dev/null +++ b/lib/theme/app_theme.dart @@ -0,0 +1,66 @@ +import 'package:flutter/material.dart'; +import '../services/app_settings.dart'; + +/// Shared colors and component styles. Prefer these over hardcoded +/// Colors.grey[...] so screens look alike and can be restyled in one place. +class AppTheme { + static final Color bar = Colors.grey[900]!; // app bar, bottom nav, sheets + static final Color sheet = Colors.grey[900]!; + + static ThemeData light() { + return ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.white), + useMaterial3: true, + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: sheet, + showDragHandle: true, + dragHandleColor: Colors.white24, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + ), + dialogTheme: DialogThemeData( + backgroundColor: sheet, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + titleTextStyle: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), + contentTextStyle: const TextStyle(color: Colors.white70, fontSize: 14), + ), + ); + } + + static ThemeData dark() { + return light().copyWith( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue, brightness: Brightness.dark), + ); + } +} + +/// Card and text colors that stay readable on the current target background +/// (which can be anything from white to red to black). +class Surfaces { + final Color card; + final Color divider; + final Color textPrimary; + final Color textSecondary; + + const Surfaces._({ + required this.card, + required this.divider, + required this.textPrimary, + required this.textSecondary, + }); + + static Surfaces get current => AppSettings.instance.isLightBackground + ? Surfaces._( + card: Colors.grey[300]!, // same grey as calendar cards + divider: Colors.grey[400]!, + textPrimary: Colors.black87, + textSecondary: Colors.black54, + ) + : Surfaces._( + card: Colors.grey[850]!, + divider: Colors.grey[700]!, + textPrimary: Colors.white, + textSecondary: Colors.white60, + ); +} diff --git a/lib/utils/target_colors.dart b/lib/utils/target_colors.dart index 4df6754..b1f6ece 100644 --- a/lib/utils/target_colors.dart +++ b/lib/utils/target_colors.dart @@ -15,7 +15,6 @@ class TargetColors { 'assets/targets/Target10.jpg': Color(0xFF98926E), // Olive green 'assets/targets/Target11.jpg': Color(0xFF13132B), // Dark blue 'assets/targets/Target12.jpg': Color(0xFFF5F4EF), // Off-white - 'assets/targets/Target13.jpg': Color(0xFF174AA5), // Blue 'assets/targets/Target14.jpg': Color(0xFFFEE05E), // Light yellow 'assets/targets/Target15.jpg': Color(0xFFFFFFFF), // White 'assets/targets/Target16.jpg': Color(0xFF000000), // Black diff --git a/lib/utils/translations.dart b/lib/utils/translations.dart index 13db105..6132517 100644 --- a/lib/utils/translations.dart +++ b/lib/utils/translations.dart @@ -48,100 +48,140 @@ class AppTranslations { 'Slovenian': 'Privzeta tarča', }, 'Target1': { - 'English': 'Target 1', - 'Slovenian': 'Tarča 1', + 'English': 'Leaf Wreath', + 'Slovenian': 'Lovorov venec', }, 'Target2': { - 'English': 'Target 2', - 'Slovenian': 'Tarča 2', + 'English': 'Spring Meadow', + 'Slovenian': 'Pomladni travnik', }, 'Target3': { - 'English': 'Target 3', - 'Slovenian': 'Tarča 3', + 'English': 'Stone', + 'Slovenian': 'Kamen', }, 'Target4': { - 'English': 'Target 4', - 'Slovenian': 'Tarča 4', + 'English': 'Royal Red', + 'Slovenian': 'Kraljevsko rdeča', }, 'Target5': { - 'English': 'Target 5', - 'Slovenian': 'Tarča 5', + 'English': 'Flames', + 'Slovenian': 'Plameni', }, 'Target6': { - 'English': 'Target 6', - 'Slovenian': 'Tarča 6', + 'English': 'Classic Beige', + 'Slovenian': 'Klasična bež', }, 'Target7': { - 'English': 'Target 7', - 'Slovenian': 'Tarča 7', + 'English': 'Sunny Yellow', + 'Slovenian': 'Sončno rumena', }, 'Target8': { - 'English': 'Target 8', - 'Slovenian': 'Tarča 8', + 'English': 'Wave', + 'Slovenian': 'Val', }, 'Target9': { - 'English': 'Target 9', - 'Slovenian': 'Tarča 9', + 'English': 'Frost', + 'Slovenian': 'Ivje', }, 'Target10': { - 'English': 'Target 10', - 'Slovenian': 'Tarča 10', + 'English': 'Military', + 'Slovenian': 'Vojaška', }, 'Target11': { - 'English': 'Target 11', - 'Slovenian': 'Tarča 11', + 'English': 'Galaxy', + 'Slovenian': 'Galaksija', }, 'Target12': { - 'English': 'Target 12', - 'Slovenian': 'Tarča 12', - }, - 'Target13': { - 'English': 'Target 13', - 'Slovenian': 'Tarča 13', + 'English': 'Olive Branch', + 'Slovenian': 'Oljčna vejica', }, 'Target14': { - 'English': 'Target 14', - 'Slovenian': 'Tarča 14', + 'English': 'Rainbow', + 'Slovenian': 'Mavrica', }, 'Target15': { - 'English': 'Target 15', - 'Slovenian': 'Tarča 15', + 'English': 'Tribal', + 'Slovenian': 'Plemenska', }, 'Target16': { - 'English': 'Target 16', - 'Slovenian': 'Tarča 16', + 'English': 'Inferno', + 'Slovenian': 'Inferno', }, 'Target17': { - 'English': 'Target 17', - 'Slovenian': 'Tarča 17', + 'English': 'Navy Gold', + 'Slovenian': 'Modro-zlata', }, 'Target18': { - 'English': 'Target 18', - 'Slovenian': 'Tarča 18', + 'English': 'Ice Crystal', + 'Slovenian': 'Ledeni kristal', }, 'Target19': { - 'English': 'Target 19', - 'Slovenian': 'Tarča 19', + 'English': 'Orange', + 'Slovenian': 'Oranžna', }, 'Target20': { - 'English': 'Target 20', - 'Slovenian': 'Tarča 20', + 'English': 'Sky Blue', + 'Slovenian': 'Nebesno modra', }, 'Target21': { - 'English': 'Target 21', - 'Slovenian': 'Tarča 21', + 'English': 'Christmas Wreath', + 'Slovenian': 'Božični venec', }, 'Target22': { - 'English': 'Target 22', - 'Slovenian': 'Tarča 22', + 'English': 'Paint Splash', + 'Slovenian': 'Barvni pljusk', }, 'Target23': { - 'English': 'Target 23', - 'Slovenian': 'Tarča 23', + 'English': 'Monochrome', + 'Slovenian': 'Črno-bela', }, 'Target24': { - 'English': 'Target 24', - 'Slovenian': 'Tarča 24', + 'English': 'Graphite', + 'Slovenian': 'Grafit', + }, + 'Target25': { + 'English': 'Graffiti', + 'Slovenian': 'Grafiti', + }, + 'Target26': { + 'English': 'Binary', + 'Slovenian': 'Binarna', + }, + 'Target27': { + 'English': 'Confetti', + 'Slovenian': 'Konfeti', + }, + 'Target28': { + 'English': 'Shards', + 'Slovenian': 'Črepinje', + }, + 'Target29': { + 'English': 'Neon', + 'Slovenian': 'Neon', + }, + 'Target30': { + 'English': 'Ink Splatter', + 'Slovenian': 'Packe črnila', + }, + 'Target31': { + 'English': 'Christmas Red', + 'Slovenian': 'Božično rdeča', + }, + 'Target32': { + 'English': 'Holly', + 'Slovenian': 'Bodika', + }, + 'Target33': { + 'English': 'Easter', + 'Slovenian': 'Velikonočna', + }, + 'Target34': { + 'English': 'Easter Bunny', + 'Slovenian': 'Velikonočni zajček', + }, + 'Target35': { + 'English': 'Hearts', + 'Slovenian': 'Srčki', }, // Camera settings @@ -784,9 +824,9 @@ class AppTranslations { 'English': 'WiFi is enabled', 'Slovenian': 'WiFi je vključen', }, - 'Mobile data is disabled': { - 'English': 'Mobile data is disabled', - 'Slovenian': 'Mobilni podatki so onemogočeni', + 'Cameras and PC are switched on': { + 'English': 'Cameras and PC are switched on', + 'Slovenian': 'Kamere in računalnik so vklopljeni', }, 'Reload': { 'English': 'Reload', @@ -978,6 +1018,268 @@ class AppTranslations { 'English': 'Competitions', 'Slovenian': 'Tekme', }, + // Settings (v1.2 redesign) + 'Bullet color': { + 'English': 'Bullet color', + 'Slovenian': 'Barva zadetkov', + }, + 'Remind me': { + 'English': 'Remind me', + 'Slovenian': 'Opomni me', + }, + '{n} h before': { + 'English': '{n} h before', + 'Slovenian': '{n} h prej', + }, + 'Cameras': { + 'English': 'Cameras', + 'Slovenian': 'Kamere', + }, + '{n} cameras': { + 'English': '{n} cameras', + 'Slovenian': '{n} kamer', + }, + 'Quick setup': { + 'English': 'Quick setup', + 'Slovenian': 'Hitra nastavitev', + }, + 'Set all cameras from one IP': { + 'English': 'Set all cameras from one IP', + 'Slovenian': 'Nastavi vse kamere z enim IP', + }, + 'Ports {from}–{to}': { + 'English': 'Ports {from}–{to}', + 'Slovenian': 'Vrata {from}–{to}', + }, + // Club access + 'Club': { + 'English': 'Club', + 'Slovenian': 'Klub', + }, + 'Club code': { + 'English': 'Club code', + 'Slovenian': 'Klubska koda', + }, + 'Unlocks calendar and contacts': { + 'English': 'Unlocks calendar and contacts', + 'Slovenian': 'Odklene koledar in kontakte', + }, + 'Member access': { + 'English': 'Member access', + 'Slovenian': 'Članski dostop', + }, + 'Calendar and contacts unlocked': { + 'English': 'Calendar and contacts unlocked', + 'Slovenian': 'Koledar in kontakti odklenjeni', + }, + 'Remove': { + 'English': 'Remove', + 'Slovenian': 'Odstrani', + }, + 'Remove club access from this phone?': { + 'English': 'Remove club access from this phone?', + 'Slovenian': 'Odstranim članski dostop s tega telefona?', + }, + 'Club access unlocked': { + 'English': 'Club access unlocked', + 'Slovenian': 'Članski dostop odklenjen', + }, + 'Wrong club code': { + 'English': 'Wrong club code', + 'Slovenian': 'Napačna klubska koda', + }, + 'Unlock': { + 'English': 'Unlock', + 'Slovenian': 'Odkleni', + }, + 'Total': { + 'English': 'Total', + 'Slovenian': 'Skupaj', + }, + 'No training selected': { + 'English': 'No training selected', + 'Slovenian': 'Ni izbranega treninga', + }, + 'Save to folder': { + 'English': 'Save to folder', + 'Slovenian': 'Shrani v mapo', + }, + 'All': { + 'English': 'All', + 'Slovenian': 'Vse', + }, + 'Statistics': { + 'English': 'Statistics', + 'Slovenian': 'Statistika', + }, + 'Best target': { + 'English': 'Best target', + 'Slovenian': 'Najboljša tarča', + }, + 'Average target': { + 'English': 'Average target', + 'Slovenian': 'Povprečna tarča', + }, + 'Average per shot': { + 'English': 'Average per shot', + 'Slovenian': 'Povprečje na strel', + }, + 'shots': { + 'English': 'shots', + 'Slovenian': 'strelov', + }, + 'Sessions': { + 'English': 'Trainings & tournaments', + 'Slovenian': 'Treningi in tekme', + }, + 'Trainings': { + 'English': 'Trainings', + 'Slovenian': 'Treningi', + }, + 'Sort by Date': { + 'English': 'By date', + 'Slovenian': 'Po datumu', + }, + 'Sort by Score': { + 'English': 'By score', + 'Slovenian': 'Po rezultatu', + }, + 'Tournaments': { + 'English': 'Tournaments', + 'Slovenian': 'Tekmovanja', + }, + 'last': { + 'English': 'last', + 'Slovenian': 'zadnji', + }, + 'Progress': { + 'English': 'Progress', + 'Slovenian': 'Napredek', + }, + 'History': { + 'English': 'History', + 'Slovenian': 'Zgodovina', + }, + 'Average per shot by session': { + 'English': 'Average per shot by session', + 'Slovenian': 'Povprečje na strel po treningih', + }, + 'Shoot at least two sessions to see your progress': { + 'English': 'Shoot at least two sessions to see your progress', + 'Slovenian': 'Za prikaz napredka potrebuješ vsaj dva treninga', + }, + 'Edit': { + 'English': 'Edit', + 'Slovenian': 'Uredi', + }, + 'Delete': { + 'English': 'Delete', + 'Slovenian': 'Izbriši', + }, + 'A folder with this name already exists': { + 'English': 'A folder with this name already exists', + 'Slovenian': 'Mapa s tem imenom že obstaja', + }, + 'last training': { + 'English': 'vs. last training', + 'Slovenian': 'zadnji trening', + }, + 'shot': { + 'English': 'shot', + 'Slovenian': 'strel', + }, + 'Best results': { + 'English': 'Best results', + 'Slovenian': 'Najboljši rezultati', + }, + 'Saved targets and your statistics will appear here': { + 'English': 'Saved targets and your statistics will appear here', + 'Slovenian': 'Tukaj se bodo prikazale shranjene tarče in tvoja statistika', + }, + 'Year': { + 'English': 'Year', + 'Slovenian': 'Leto', + }, + 'High contrast': { + 'English': 'High contrast', + 'Slovenian': 'Visok kontrast', + }, + 'Rotate': { + 'English': 'Rotate', + 'Slovenian': 'Zasukaj', + }, + 'Saved for this camera': { + 'English': 'saved for this camera', + 'Slovenian': 'shranjeno za to kamero', + }, + 'Image Settings': { + 'English': 'Image Settings', + 'Slovenian': 'Nastavitve slike', + }, + 'Where are we shooting?': { + 'English': 'Where are we shooting?', + 'Slovenian': 'Kje streljamo?', + }, + 'Not set up': { + 'English': 'Not set up', + 'Slovenian': 'Ni nastavljeno', + }, + 'Locations': { + 'English': 'Locations', + 'Slovenian': 'Strelišča', + }, + 'Location': { + 'English': 'Location', + 'Slovenian': 'Strelišče', + }, + 'Add location': { + 'English': 'Add location', + 'Slovenian': 'Dodaj strelišče', + }, + 'Added with the club code': { + 'English': 'Added with the club code', + 'Slovenian': 'Dodano s klubsko kodo', + }, + 'Positions': { + 'English': 'Positions', + 'Slovenian': 'Pozicije', + }, + 'Number of positions': { + 'English': 'Number of positions', + 'Slovenian': 'Število pozicij', + }, + 'e.g. Home': { + 'English': 'e.g. Home', + 'Slovenian': 'npr. Doma', + }, + 'This location already exists': { + 'English': 'This location already exists', + 'Slovenian': 'To strelišče že obstaja', + }, + 'Exposure': { + 'English': 'Exposure', + 'Slovenian': 'Osvetlitev', + }, + 'Zoom': { + 'English': 'Zoom', + 'Slovenian': 'Povečava', + }, + 'Flashlight': { + 'English': 'Flashlight', + 'Slovenian': 'Svetilka', + }, + 'Settings icon: exposure, zoom and flashlight': { + 'English': 'Settings icon: exposure, zoom and flashlight', + 'Slovenian': 'Ikona nastavitev: osvetlitev, povečava in svetilka', + }, + 'Automatic (phone language)': { + 'English': 'Automatic (phone language)', + 'Slovenian': 'Samodejno (jezik telefona)', + }, + 'Member access is currently available only for SDK Kovinar Muta. Support for other clubs may be added in the future.': { + 'English': 'Member access is currently available only for SDK Kovinar Muta. Support for other clubs may be added in the future.', + 'Slovenian': 'Članski dostop je trenutno na voljo samo za SDK Kovinar Muta. V prihodnje bo morda podprt tudi za druge klube.', + }, }; static String translate(String key, String language) { diff --git a/lib/widgets/bar_tabs.dart b/lib/widgets/bar_tabs.dart new file mode 100644 index 0000000..2c2b483 --- /dev/null +++ b/lib/widgets/bar_tabs.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import '../theme/app_theme.dart'; + +class BarTab { + final String label; + final IconData icon; + + const BarTab(this.label, this.icon); +} + +/// Tab strip that continues the dark app bar (Koledar/Stiki, Knjiga filters). +/// The selected tab is a white pill; [trailing] sits at the right end. +class BarTabs extends StatelessWidget { + final List tabs; + final int selected; + final ValueChanged onSelect; + final Widget? trailing; + + const BarTabs({ + super.key, + required this.tabs, + required this.selected, + required this.onSelect, + this.trailing, + }); + + @override + Widget build(BuildContext context) { + return Container( + color: AppTheme.bar, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + child: Row( + children: [ + for (int i = 0; i < tabs.length; i++) ...[ + if (i > 0) const SizedBox(width: 6), + Expanded(child: _tab(tabs[i], i == selected, () => onSelect(i))), + ], + if (trailing != null) trailing!, + ], + ), + ); + } + + Widget _tab(BarTab tab, bool active, VoidCallback onTap) { + final color = active ? Colors.black : Colors.grey[400]; + return 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), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(tab.icon, color: color, size: 18), + const SizedBox(width: 6), + Flexible( + child: Text( + tab.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: color), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/bottom_nav.dart b/lib/widgets/bottom_nav.dart index f16137c..3cc2db5 100644 --- a/lib/widgets/bottom_nav.dart +++ b/lib/widgets/bottom_nav.dart @@ -1,48 +1,43 @@ import 'package:flutter/material.dart'; -import '../utils/translations.dart'; +import '../theme/app_theme.dart'; class BottomNavBar extends StatelessWidget { final int selectedIndex; - final Function(int) onItemTapped; - final String selectedLanguage; + final ValueChanged onItemTapped; + final List items; const BottomNavBar({ super.key, required this.selectedIndex, required this.onItemTapped, - required this.selectedLanguage, + required this.items, }); - String _t(String key) { - return AppTranslations.translate(key, selectedLanguage); - } - @override -Widget build(BuildContext context) { - return SafeArea( - child: SizedBox( - height: 80, - child: BottomNavigationBar( - backgroundColor: Colors.grey[900], - currentIndex: selectedIndex, - onTap: onItemTapped, - showSelectedLabels: true, - showUnselectedLabels: true, - type: BottomNavigationBarType.fixed, - selectedFontSize: 12, - unselectedFontSize: 12, - selectedItemColor: Colors.white, - unselectedItemColor: Colors.white70, - items: [ - BottomNavigationBarItem(icon: const Icon(Icons.book), label: _t("Book")), - BottomNavigationBarItem(icon: const Icon(Icons.my_location), label: _t("Shooting")), - BottomNavigationBarItem(icon: const Icon(Icons.camera_alt), label: _t("Camera")), - BottomNavigationBarItem(icon: const Icon(Icons.calendar_today), label: _t("Calendar")), - BottomNavigationBarItem(icon: const Icon(Icons.settings), label: _t("Settings")), - ], + Widget build(BuildContext context) { + // Paint the gesture-bar strip below the nav too (edge-to-edge since targetSdk 35), + // otherwise the target background color shows through as a thin line. + return ColoredBox( + color: AppTheme.bar, + child: SafeArea( + top: false, + child: SizedBox( + height: 80, + child: BottomNavigationBar( + backgroundColor: AppTheme.bar, + currentIndex: selectedIndex, + onTap: onItemTapped, + showSelectedLabels: true, + showUnselectedLabels: true, + type: BottomNavigationBarType.fixed, + selectedFontSize: 12, + unselectedFontSize: 12, + selectedItemColor: Colors.white, + unselectedItemColor: Colors.white70, + items: items, + ), + ), ), - ), - ); -} - + ); + } } diff --git a/lib/widgets/camera_sheet.dart b/lib/widgets/camera_sheet.dart new file mode 100644 index 0000000..34cf27c --- /dev/null +++ b/lib/widgets/camera_sheet.dart @@ -0,0 +1,236 @@ +import 'package:flutter/material.dart'; + +/// Bottom sheet used by every menu on the camera stream: the live image stays +/// visible and undimmed above it, so changes can be judged immediately. +Future showCameraSheet(BuildContext context, + {required WidgetBuilder builder}) { + return showModalBottomSheet( + context: context, + barrierColor: Colors.transparent, + backgroundColor: Colors.grey[900], + isScrollControlled: + true, // tall content (timer) may use more than half the screen + builder: (sheet) => SafeArea( + child: ConstrainedBox( + constraints: + BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.75), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(20, 0, 20, 16), + child: builder(sheet), + ), + ), + ), + ); +} + +/// Title (+ optional subtitle) on the left, optional action on the right. +class CameraSheetHeader extends StatelessWidget { + final String title; + final String? subtitle; + final IconData? icon; + final Color? iconColor; + final Widget? trailing; + + const CameraSheetHeader({ + super.key, + required this.title, + this.subtitle, + this.icon, + this.iconColor, + this.trailing, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + if (icon != null) ...[ + Icon(icon, color: iconColor ?? Colors.white, size: 22), + const SizedBox(width: 8), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, + style: const TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.bold)), + if (subtitle != null) + Text(subtitle!, + style: + const TextStyle(color: Colors.white54, fontSize: 12)), + ], + ), + ), + if (trailing != null) trailing!, + ], + ), + ); + } +} + +/// Icon, label, slider and current value in one row. +class SheetSlider extends StatelessWidget { + final IconData icon; + final String label; + final String valueText; + final double value; + final double min; + final double max; + final Color accent; + final ValueChanged onChanged; + + const SheetSlider({ + required this.icon, + required this.label, + required this.valueText, + required this.value, + required this.min, + required this.max, + required this.accent, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Icon(icon, color: Colors.white54, size: 20), + const SizedBox(width: 8), + SizedBox( + width: 72, + child: Text(label, + style: const TextStyle(color: Colors.white, fontSize: 13)), + ), + Expanded( + child: Slider( + value: value.clamp(min, max), + min: min, + max: max, + activeColor: accent, + inactiveColor: Colors.white24, + onChanged: onChanged, + ), + ), + SizedBox( + width: 46, + child: Text( + valueText, + textAlign: TextAlign.right, + style: const TextStyle( + color: Colors.white70, + fontSize: 13, + fontFeatures: [FontFeature.tabularFigures()]), + ), + ), + ], + ); + } +} + +/// Wide button that shows an on/off state with the accent color. +class SheetToggle extends StatelessWidget { + final IconData icon; + final String label; + final bool active; + final Color accent; + final VoidCallback onTap; + + const SheetToggle({ + required this.icon, + required this.label, + required this.active, + required this.accent, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return Material( + color: active + ? accent.withValues(alpha: 0.18) + : Colors.white.withValues(alpha: 0.06), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: + BorderSide(color: active ? accent : Colors.transparent, width: 1.5), + ), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 18, color: active ? accent : Colors.white70), + const SizedBox(width: 6), + Flexible( + child: Text( + label, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + color: active ? Colors.white : Colors.white70), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// Big number with − / + buttons, used for the bullet count. +class SheetStepper extends StatelessWidget { + final int value; + final int min; + final int max; + final Color accent; + final ValueChanged onChanged; + + const SheetStepper({ + super.key, + required this.value, + required this.min, + required this.max, + required this.accent, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + Widget button(IconData icon, bool enabled, int next) => IconButton( + onPressed: enabled ? () => onChanged(next) : null, + icon: Icon(icon, color: Colors.white, size: 28), + style: IconButton.styleFrom( + backgroundColor: + Colors.white.withValues(alpha: enabled ? 0.12 : 0.04), + shape: const CircleBorder(), + minimumSize: const Size(56, 56), + ), + ); + + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + button(Icons.remove, value > min, value - 1), + SizedBox( + width: 120, + child: Text( + '$value', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 56, fontWeight: FontWeight.bold, color: accent), + ), + ), + button(Icons.add, value < max, value + 1), + ], + ); + } +} diff --git a/lib/widgets/image_settings.dart b/lib/widgets/image_settings.dart new file mode 100644 index 0000000..c8a7ac1 --- /dev/null +++ b/lib/widgets/image_settings.dart @@ -0,0 +1,258 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'camera_sheet.dart'; + +enum ImageFilterType { none, greyscale, invert, highContrast } + +/// Live-image adjustments for one camera stream. Saved per camera, because +/// lighting differs from lane to lane. +class ImageAdjustments { + final ImageFilterType filter; + final double brightness; // -1 … 1 + final double contrast; // 0.5 … 2 + final int quarterTurns; // 0–3, for cameras mounted sideways + + const ImageAdjustments({ + this.filter = ImageFilterType.none, + this.brightness = 0, + this.contrast = 1, + this.quarterTurns = 0, + }); + + ImageAdjustments copyWith({ + ImageFilterType? filter, + double? brightness, + double? contrast, + int? quarterTurns, + }) { + return ImageAdjustments( + filter: filter ?? this.filter, + brightness: brightness ?? this.brightness, + contrast: contrast ?? this.contrast, + quarterTurns: quarterTurns ?? this.quarterTurns, + ); + } + + /// Keeps rotation, resets the picture itself. + ImageAdjustments resetPicture() => + copyWith(filter: ImageFilterType.none, brightness: 0, contrast: 1); + + // Older versions stored one global setting; use it until a camera has its own + static Future load(String camera) async { + final p = await SharedPreferences.getInstance(); + final filter = + p.getInt('filter_cam$camera') ?? p.getInt('selectedFilter') ?? 0; + return ImageAdjustments( + filter: ImageFilterType + .values[filter.clamp(0, ImageFilterType.values.length - 1)], + brightness: p.getDouble('brightness_cam$camera') ?? + p.getDouble('brightness') ?? + 0, + contrast: + p.getDouble('contrast_cam$camera') ?? p.getDouble('contrast') ?? 1, + quarterTurns: p.getInt('rotation_cam$camera') ?? 0, + ); + } + + Future save(String camera) async { + final p = await SharedPreferences.getInstance(); + await p.setInt('filter_cam$camera', filter.index); + await p.setDouble('brightness_cam$camera', brightness); + await p.setDouble('contrast_cam$camera', contrast); + await p.setInt('rotation_cam$camera', quarterTurns); + } + + /// Filter first, then contrast around mid-grey and brightness on top. + ColorFilter get colorFilter { + const lum = [0.2126, 0.7152, 0.0722]; + final List base = switch (filter) { + ImageFilterType.greyscale || ImageFilterType.highContrast => [ + ...lum, 0, 0, // + ...lum, 0, 0, + ...lum, 0, 0, + 0, 0, 0, 1, 0, + ], + ImageFilterType.invert => [ + -1, 0, 0, 0, 255, // + 0, -1, 0, 0, 255, + 0, 0, -1, 0, 255, + 0, 0, 0, 1, 0, + ], + ImageFilterType.none => [ + 1, 0, 0, 0, 0, // + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + ], + }; + // High contrast makes dark holes stand out on a light target + final c = contrast * (filter == ImageFilterType.highContrast ? 2.2 : 1); + final m = [...base]; + for (final row in [0, 5, 10]) { + for (int i = 0; i < 4; i++) { + m[row + i] *= c; + } + m[row + 4] = m[row + 4] * c + 128 * (1 - c) + brightness * 255; + } + return ColorFilter.matrix(m); + } +} + +/// Bottom sheet that leaves the live image visible, so every change is seen immediately. +Future showImageSettingsSheet( + BuildContext context, { + required ImageAdjustments initial, + required String settingsId, + required String cameraLabel, + required Color accent, + required String Function(String) t, + required ValueChanged onChanged, +}) { + var value = initial; + return showCameraSheet( + context, + builder: (sheet) => StatefulBuilder( + builder: (context, setSheetState) { + void update(ImageAdjustments next) { + setSheetState(() => value = next); + onChanged(next); + next.save(settingsId); + } + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CameraSheetHeader( + title: t('Image Settings'), + subtitle: '$cameraLabel · ${t('Saved for this camera')}', + trailing: TextButton.icon( + style: TextButton.styleFrom(foregroundColor: Colors.white70), + icon: const Icon(Icons.restart_alt_rounded, size: 18), + label: Text(t('Reset')), + onPressed: () => update(value.resetPicture()), + ), + ), + Row( + children: [ + for (final (f, icon, label) in [ + (ImageFilterType.none, Icons.image_outlined, 'None'), + ( + ImageFilterType.greyscale, + Icons.filter_b_and_w_rounded, + 'Greyscale' + ), + ( + ImageFilterType.highContrast, + Icons.contrast_rounded, + 'High contrast' + ), + ( + ImageFilterType.invert, + Icons.invert_colors_rounded, + 'Invert' + ), + ]) ...[ + if (f != ImageFilterType.none) const SizedBox(width: 8), + Expanded( + child: _FilterTile( + icon: icon, + label: t(label), + selected: value.filter == f, + accent: accent, + onTap: () => update(value.copyWith(filter: f)), + ), + ), + ], + ], + ), + const SizedBox(height: 14), + SheetSlider( + icon: Icons.brightness_6_rounded, + label: t('Brightness'), + valueText: + '${value.brightness >= 0 ? '+' : ''}${(value.brightness * 100).round()}', + value: value.brightness, + min: -1, + max: 1, + accent: accent, + onChanged: (v) => update(value.copyWith(brightness: v)), + ), + SheetSlider( + icon: Icons.tonality_rounded, + label: t('Contrast'), + valueText: '${(value.contrast * 100).round()} %', + value: value.contrast, + min: 0.5, + max: 2, + accent: accent, + onChanged: (v) => update(value.copyWith(contrast: v)), + ), + const SizedBox(height: 8), + SheetToggle( + icon: Icons.rotate_90_degrees_cw_rounded, + label: '${t('Rotate')} · ${value.quarterTurns * 90}°', + active: value.quarterTurns != 0, + accent: accent, + onTap: () => update( + value.copyWith(quarterTurns: (value.quarterTurns + 1) % 4)), + ), + ], + ); + }, + ), + ); +} + +class _FilterTile extends StatelessWidget { + final IconData icon; + final String label; + final bool selected; + final Color accent; + final VoidCallback onTap; + + const _FilterTile({ + required this.icon, + required this.label, + required this.selected, + required this.accent, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return Material( + color: selected + ? accent.withValues(alpha: 0.18) + : Colors.white.withValues(alpha: 0.06), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + side: + BorderSide(color: selected ? accent : Colors.transparent, width: 2), + ), + child: InkWell( + borderRadius: BorderRadius.circular(14), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4), + child: Column( + children: [ + Icon(icon, color: selected ? accent : Colors.white70, size: 26), + const SizedBox(height: 4), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: selected ? Colors.white : Colors.white70, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/input_field.dart b/lib/widgets/input_field.dart deleted file mode 100644 index e93bea5..0000000 --- a/lib/widgets/input_field.dart +++ /dev/null @@ -1,36 +0,0 @@ -import 'package:flutter/material.dart'; - -class InputField extends StatelessWidget { - final String hintText; - final IconData icon; - final bool obscureText; - final TextEditingController controller; - - const InputField({ - super.key, - required this.hintText, - required this.icon, - this.obscureText = false, - required this.controller, - }); - - @override - Widget build(BuildContext context) { - return TextField( - controller: controller, - obscureText: obscureText, - style: const TextStyle(color: Colors.grey), // Text inside input field is gray - decoration: InputDecoration( - prefixIcon: Icon(icon, color: Colors.grey), // Icons inside input field are gray - hintText: hintText, - hintStyle: const TextStyle(color: Colors.grey), // Placeholder text is gray - filled: true, - fillColor: Colors.grey[300], // Light gray background for inputs - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(12), - borderSide: BorderSide.none, // No border - ), - ), - ); - } -} diff --git a/lib/widgets/progress_chart.dart b/lib/widgets/progress_chart.dart new file mode 100644 index 0000000..6015e46 --- /dev/null +++ b/lib/widgets/progress_chart.dart @@ -0,0 +1,174 @@ +import 'package:flutter/material.dart'; + +class ChartPoint { + final String label; // shown in the tooltip and under the first/last point + final double value; + + const ChartPoint(this.label, this.value); +} + +/// Single-series line chart: 2px line, 8px points, three faint gridlines. +/// Tap (or drag) to show the nearest point's label and value. +class ProgressChart extends StatefulWidget { + final List points; + final Color color; + final Color textColor; + final Color gridColor; + + const ProgressChart({ + super.key, + required this.points, + required this.color, + required this.textColor, + required this.gridColor, + }); + + @override + State createState() => _ProgressChartState(); +} + +class _ProgressChartState extends State { + int? _selected; + + void _select(Offset position, Size size) { + final n = widget.points.length; + if (n == 0) return; + final plotWidth = size.width - _ChartPainter.leftAxis - _ChartPainter.pad * 2; + final x = (position.dx - _ChartPainter.leftAxis - _ChartPainter.pad) / plotWidth; + setState(() => _selected = (x * (n - 1)).round().clamp(0, n - 1)); + } + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + final size = Size(constraints.maxWidth, 170); + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (d) => _select(d.localPosition, size), + onHorizontalDragUpdate: (d) => _select(d.localPosition, size), + child: CustomPaint( + size: size, + painter: _ChartPainter( + points: widget.points, + color: widget.color, + textColor: widget.textColor, + gridColor: widget.gridColor, + selected: _selected, + ), + ), + ); + }, + ); + } +} + +class _ChartPainter extends CustomPainter { + static const double leftAxis = 32; // room for y labels + static const double pad = 10; // keeps end points inside the plot + static const double top = 34; // room for the tooltip + static const double bottom = 20; // room for x labels + + final List points; + final Color color; + final Color textColor; + final Color gridColor; + final int? selected; + + _ChartPainter({ + required this.points, + required this.color, + required this.textColor, + required this.gridColor, + required this.selected, + }); + + @override + void paint(Canvas canvas, Size size) { + if (points.isEmpty) return; + final values = points.map((p) => p.value); + var minV = values.reduce((a, b) => a < b ? a : b); + var maxV = values.reduce((a, b) => a > b ? a : b); + if (maxV - minV < 1) { + minV -= 0.5; + maxV += 0.5; + } + final plot = Rect.fromLTRB(leftAxis + pad, top, size.width - pad, size.height - bottom); + + Offset at(int i) => Offset( + points.length == 1 ? plot.center.dx : plot.left + plot.width * i / (points.length - 1), + plot.bottom - plot.height * (points[i].value - minV) / (maxV - minV), + ); + + // Gridlines + y labels (min, mid, max) + final grid = Paint() + ..color = gridColor + ..strokeWidth = 1; + for (final f in [0.0, 0.5, 1.0]) { + final y = plot.bottom - plot.height * f; + canvas.drawLine(Offset(leftAxis, y), Offset(size.width, y), grid); + _text(canvas, (minV + (maxV - minV) * f).toStringAsFixed(1), Offset(0, y - 7), 11, textColor); + } + + // x labels: first and last only + _text(canvas, points.first.label, Offset(plot.left - pad, plot.bottom + 5), 11, textColor); + if (points.length > 1) { + _text(canvas, points.last.label, Offset(plot.right, plot.bottom + 5), 11, textColor, alignRight: true); + } + + // Line + final path = Path()..moveTo(at(0).dx, at(0).dy); + for (int i = 1; i < points.length; i++) { + path.lineTo(at(i).dx, at(i).dy); + } + canvas.drawPath( + path, + Paint() + ..color = color + ..strokeWidth = 2 + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + ); + + // Points with a surface ring so they read on top of the line + for (int i = 0; i < points.length; i++) { + final isSel = i == selected; + canvas.drawCircle(at(i), isSel ? 7 : 5, Paint()..color = Colors.white); + canvas.drawCircle(at(i), isSel ? 5.5 : 4, Paint()..color = color); + } + + // Tooltip for the selected point + if (selected != null) { + final p = at(selected!); + canvas.drawLine(Offset(p.dx, plot.top), Offset(p.dx, plot.bottom), grid); + final label = '${points[selected!].label} ${points[selected!].value.toStringAsFixed(2)}'; + final tp = _layout(label, 12, Colors.white, bold: true); + final w = tp.width + 16; + final left = (p.dx - w / 2).clamp(0.0, size.width - w); + canvas.drawRRect( + RRect.fromRectAndRadius(Rect.fromLTWH(left, 2, w, 24), const Radius.circular(6)), + Paint()..color = Colors.grey[900]!, + ); + tp.paint(canvas, Offset(left + 8, 2 + (24 - tp.height) / 2)); + } + } + + TextPainter _layout(String text, double size, Color color, {bool bold = false}) { + return TextPainter( + text: TextSpan( + text: text, + style: TextStyle(fontSize: size, color: color, fontWeight: bold ? FontWeight.w600 : FontWeight.normal), + ), + textDirection: TextDirection.ltr, + )..layout(); + } + + void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) { + final tp = _layout(text, size, color); + tp.paint(canvas, alignRight ? at.translate(-tp.width, 0) : at); + } + + @override + bool shouldRepaint(_ChartPainter old) => + old.points != points || old.selected != selected || old.color != color || old.textColor != textColor; +} diff --git a/lib/widgets/section.dart b/lib/widgets/section.dart new file mode 100644 index 0000000..ac2d0af --- /dev/null +++ b/lib/widgets/section.dart @@ -0,0 +1,248 @@ +import 'package:flutter/material.dart'; +import '../theme/app_theme.dart'; + +/// Small uppercase label above a group, e.g. "OBVESTILA". +class SectionHeader extends StatelessWidget { + final String label; + + const SectionHeader(this.label, {super.key}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(4, 20, 4, 8), + child: Text( + label.toUpperCase(), + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + letterSpacing: 1.4, + color: Surfaces.current.textSecondary, + ), + ), + ); + } +} + +/// Rounded group of rows with thin dividers between them. +class GroupCard extends StatelessWidget { + final List children; + + const GroupCard({super.key, required this.children}); + + @override + Widget build(BuildContext context) { + final s = Surfaces.current; + return ClipRRect( + borderRadius: BorderRadius.circular(14), + child: Material( + color: s.card, + child: Column( + children: [ + for (int i = 0; i < children.length; i++) ...[ + if (i > 0) Divider(height: 1, thickness: 1, indent: 16, color: s.divider), + children[i], + ], + ], + ), + ), + ); + } +} + +/// One settings row: title (+ optional subtitle) on the left, current value and +/// a chevron on the right. Pass [trailing] to replace value + chevron (e.g. a Switch). +class SettingsTile extends StatelessWidget { + final String title; + final String? subtitle; + final Widget? leading; + final String? value; + final Widget? valueLeading; + final Widget? trailing; + final VoidCallback? onTap; + + const SettingsTile({ + super.key, + required this.title, + this.subtitle, + this.leading, + this.value, + this.valueLeading, + this.trailing, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + final s = Surfaces.current; + return InkWell( + onTap: onTap, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + child: Row( + children: [ + if (leading != null) ...[leading!, const SizedBox(width: 12)], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(title, style: TextStyle(fontSize: 15, color: s.textPrimary)), + if (subtitle != null) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text(subtitle!, style: TextStyle(fontSize: 12, color: s.textSecondary)), + ), + ], + ), + ), + if (trailing != null) + trailing! + else ...[ + if (valueLeading != null) ...[valueLeading!, const SizedBox(width: 8)], + if (value != null) + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 170), + child: Text( + value!, + style: TextStyle(fontSize: 14, color: s.textSecondary), + overflow: TextOverflow.ellipsis, + ), + ), + if (onTap != null) Icon(Icons.chevron_right, color: s.textSecondary), + ], + ], + ), + ), + ), + ); + } +} + +/// Settings row with a switch on the right; tapping the row toggles it. +class SettingsSwitchTile extends StatelessWidget { + final String title; + final bool value; + final ValueChanged onChanged; + final Color activeColor; + + const SettingsSwitchTile({ + super.key, + required this.title, + required this.value, + required this.onChanged, + required this.activeColor, + }); + + @override + Widget build(BuildContext context) { + return SettingsTile( + title: title, + onTap: () => onChanged(!value), + trailing: SizedBox( + height: 32, + child: FittedBox( + child: Switch( + value: value, + onChanged: onChanged, + activeTrackColor: activeColor, + activeThumbColor: Colors.white, + ), + ), + ), + ); + } +} + +/// Row used inside dark bottom-sheet pickers, with a check on the selected one. +class SheetOption extends StatelessWidget { + final String label; + final Widget? leading; + final bool selected; + final Color selectedColor; + final VoidCallback onTap; + + const SheetOption({ + super.key, + required this.label, + this.leading, + required this.selected, + required this.selectedColor, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + onTap: onTap, + leading: leading, + title: Text( + label, + style: TextStyle( + color: Colors.white, + fontWeight: selected ? FontWeight.bold : FontWeight.normal, + ), + ), + trailing: selected ? Icon(Icons.check_rounded, color: selectedColor) : null, + ); + } +} + +/// Headline number with a small label above and an optional caption below. +class StatTile extends StatelessWidget { + final String label; + final String value; + final String? caption; + + const StatTile({super.key, required this.label, required this.value, this.caption}); + + @override + Widget build(BuildContext context) { + final s = Surfaces.current; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: TextStyle(fontSize: 12, color: s.textSecondary)), + const SizedBox(height: 2), + Text(value, style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold, color: s.textPrimary)), + if (caption != null) + Text(caption!, style: TextStyle(fontSize: 11, color: s.textSecondary), maxLines: 1, overflow: TextOverflow.ellipsis), + ], + ), + ); + } +} + +/// Grid of [StatTile]s, two per row, on one card. +class StatGrid extends StatelessWidget { + final List tiles; + + const StatGrid({super.key, required this.tiles}); + + @override + Widget build(BuildContext context) { + final s = Surfaces.current; + final rows = []; + for (int i = 0; i < tiles.length; i += 2) { + if (i > 0) rows.add(Divider(height: 1, thickness: 1, color: s.divider)); + rows.add(IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(child: tiles[i]), + VerticalDivider(width: 1, thickness: 1, color: s.divider), + Expanded(child: i + 1 < tiles.length ? tiles[i + 1] : const SizedBox()), + ], + ), + )); + } + return ClipRRect( + borderRadius: BorderRadius.circular(14), + child: ColoredBox(color: s.card, child: Column(children: rows)), + ); + } +} diff --git a/lib/widgets/text_prompt.dart b/lib/widgets/text_prompt.dart new file mode 100644 index 0000000..5a0fbf1 --- /dev/null +++ b/lib/widgets/text_prompt.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import '../services/app_settings.dart'; + +/// Dark dialog with one text field. Returns the trimmed text, or null if cancelled. +/// [onReset] adds a secondary button ([resetLabel], default "Reset to Default") that closes the dialog. +Future showTextPrompt( + BuildContext context, { + required String title, + String? message, + String initial = '', + String? hint, + TextInputType keyboardType = TextInputType.text, + String? confirmLabel, + String? resetLabel, + VoidCallback? onReset, +}) { + final s = AppSettings.instance; + final controller = TextEditingController(text: initial); + + return showDialog( + context: context, + builder: (dialog) => AlertDialog( + title: Text(title), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (message != null) ...[ + Text(message), + const SizedBox(height: 16), + ], + TextField( + controller: controller, + autofocus: true, + keyboardType: keyboardType, + autocorrect: false, + style: const TextStyle(color: Colors.white), + cursorColor: s.bulletColor, + decoration: InputDecoration( + hintText: hint, + hintStyle: const TextStyle(color: Colors.white38), + filled: true, + fillColor: Colors.white10, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: s.bulletColor), + ), + ), + onSubmitted: (v) => Navigator.pop(dialog, v.trim()), + ), + ], + ), + actions: [ + if (onReset != null) + TextButton( + onPressed: () { + onReset(); + Navigator.pop(dialog); + }, + child: Text(resetLabel ?? s.t('Reset to Default'), style: const TextStyle(color: Colors.white54)), + ), + TextButton( + onPressed: () => Navigator.pop(dialog), + child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)), + ), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: s.bulletColor), + onPressed: () => Navigator.pop(dialog, controller.text.trim()), + child: Text(confirmLabel ?? s.t('Save')), + ), + ], + ), + ); +} diff --git a/pubspec.lock b/pubspec.lock index 892f3e9..004e102 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1,14 +1,6 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: - _discoveryapis_commons: - dependency: transitive - description: - name: _discoveryapis_commons - sha256: "113c4100b90a5b70a983541782431b82168b3cae166ab130649c36eb3559d498" - url: "https://pub.dev" - source: hosted - version: "1.0.7" archive: dependency: transitive description: @@ -137,6 +129,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.6" + cryptography: + dependency: "direct main" + description: + name: cryptography + sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" + url: "https://pub.dev" + source: hosted + version: "2.9.0" cupertino_icons: dependency: "direct main" description: @@ -312,70 +312,6 @@ packages: description: flutter source: sdk version: "0.0.0" - google_identity_services_web: - dependency: transitive - description: - name: google_identity_services_web - sha256: "55580f436822d64c8ff9a77e37d61f5fb1e6c7ec9d632a43ee324e2a05c3c6c9" - url: "https://pub.dev" - source: hosted - version: "0.3.3" - google_sign_in: - dependency: "direct main" - description: - name: google_sign_in - sha256: d0a2c3bcb06e607bb11e4daca48bd4b6120f0bbc4015ccebbe757d24ea60ed2a - url: "https://pub.dev" - source: hosted - version: "6.3.0" - google_sign_in_android: - dependency: transitive - description: - name: google_sign_in_android - sha256: "4e52c64366bdb3fe758f683b088ee514cc7a95e69c52b5ee9fc5919e1683d21b" - url: "https://pub.dev" - source: hosted - version: "6.2.0" - google_sign_in_ios: - dependency: transitive - description: - name: google_sign_in_ios - sha256: "29cd125f58f50ceb40e8253d3c0209e321eee3e5df16cd6d262495f7cad6a2bd" - url: "https://pub.dev" - source: hosted - version: "5.8.1" - google_sign_in_platform_interface: - dependency: transitive - description: - name: google_sign_in_platform_interface - sha256: "5f6f79cf139c197261adb6ac024577518ae48fdff8e53205c5373b5f6430a8aa" - url: "https://pub.dev" - source: hosted - version: "2.5.0" - google_sign_in_web: - dependency: transitive - description: - name: google_sign_in_web - sha256: "460547beb4962b7623ac0fb8122d6b8268c951cf0b646dd150d60498430e4ded" - url: "https://pub.dev" - source: hosted - version: "0.12.4+4" - googleapis: - dependency: "direct main" - description: - name: googleapis - sha256: "864f222aed3f2ff00b816c675edf00a39e2aaf373d728d8abec30b37bee1a81c" - url: "https://pub.dev" - source: hosted - version: "13.2.0" - googleapis_auth: - dependency: "direct main" - description: - name: googleapis_auth - sha256: befd71383a955535060acde8792e7efc11d2fccd03dd1d3ec434e85b68775938 - url: "https://pub.dev" - source: hosted - version: "1.6.0" http: dependency: "direct overridden" description: @@ -545,7 +481,7 @@ packages: source: hosted version: "2.0.0" package_info_plus: - dependency: transitive + dependency: "direct main" description: name: package_info_plus sha256: "7976bfe4c583170d6cdc7077e3237560b364149fcd268b5f53d95a991963b191" diff --git a/pubspec.yaml b/pubspec.yaml index cca3bd4..d1832b7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: test1 description: A new Flutter project. publish_to: 'none' # This prevents publishing to pub.dev -version: 1.1.0+4 +version: 1.2.0+5 environment: sdk: '>=3.3.0 <4.0.0' @@ -11,9 +11,6 @@ dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.8 - google_sign_in: ^6.1.5 - googleapis: ^13.2.0 - googleapis_auth: ^1.6.0 shared_preferences: ^2.2.2 photo_view: ^0.15.0 screenshot: ^3.0.0 @@ -38,6 +35,8 @@ dependencies: flutter_local_notifications: ^18.0.1 timezone: ^0.9.4 flutter_timezone: ^3.0.0 + package_info_plus: ^8.3.0 + cryptography: ^2.9.0 dependency_overrides: http: ^0.13.6 @@ -57,6 +56,7 @@ flutter_icons: flutter: uses-material-design: true assets: + - assets/club.enc - assets/logo.png - assets/logo.svg - assets/target.png diff --git a/tool/encrypt_club_data.dart b/tool/encrypt_club_data.dart new file mode 100644 index 0000000..cd6bbde --- /dev/null +++ b/tool/encrypt_club_data.dart @@ -0,0 +1,51 @@ +// Encrypts tool/club_data.json into assets/club.enc using the club code. +// +// dart run tool/encrypt_club_data.dart +// +// The code is asked interactively (not echoed, not saved in shell history). +// tool/club_data.json holds the plain contacts and is gitignored — keep it private. +// Re-run after editing contacts or to change the club code, then rebuild the app. +import 'dart:convert'; +import 'dart:io'; +import 'package:test1/services/club_crypto.dart'; + +const _input = 'tool/club_data.json'; +const _output = 'assets/club.enc'; + +Future main() async { + final source = File(_input); + if (!source.existsSync()) { + stderr.writeln('Missing $_input'); + exit(1); + } + final plaintext = source.readAsStringSync(); + final contacts = (jsonDecode(plaintext) as Map)['contacts'] as List; + + final code = _ask('Club code: '); + if (ClubCrypto.normalize(code).length < 8) { + stderr.writeln('Use at least 8 characters — short codes can be guessed by brute force.'); + exit(1); + } + if (_ask('Repeat club code: ') != code) { + stderr.writeln('Codes do not match.'); + exit(1); + } + + final encrypted = await ClubCrypto.encrypt(plaintext, code); + if (await ClubCrypto.decrypt(encrypted, code) != plaintext) { + stderr.writeln('Self-check failed, nothing written.'); + exit(1); + } + File(_output).writeAsStringSync(encrypted); + stdout.writeln('Wrote $_output with ${contacts.length} contacts.'); +} + +String _ask(String prompt) { + stdout.write(prompt); + final terminal = stdin.hasTerminal; + if (terminal) stdin.echoMode = false; + final value = stdin.readLineSync() ?? ''; + if (terminal) stdin.echoMode = true; + stdout.writeln(); + return value; +}