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/bar_tabs.dart'; import '../widgets/help_sheet.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}); @override State createState() => _BookScreenState(); } class _BookScreenState extends State with WidgetsBindingObserver { 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); _load(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { 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; }); } } 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: 18, fontWeight: FontWeight.bold), ), ), 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]!)); } // The full session, not the copy limited to one format Session _full(Session session) => _sessions! .firstWhere((s) => s.name == session.name, orElse: () => session); Future _openDetails(Session session) async { await Navigator.push( context, MaterialPageRoute( builder: (_) => SessionScreen(session: _full(session)))); _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: [ if (stats.targets == 0) _buildEmpty() else ...[ _buildSummary(sessions, stats), ..._buildHistory(sessions), ], ], ), ), ), ], ); }, ); } // Filters continue the dark app bar, like Koledar/Stiki 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; }), ); } // Second dark row under the tabs: shots-per-target pills left, year right // Always 1โ€“5 (the capture limit); older saves above 5 keep their own pill. // Formats with no targets yet are dimmed and can't be picked. Widget _buildFilterBar(List formats, int? selected) { final sorted = { for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n, ...formats, }.toList() ..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: [ Text(AppSettings.instance.t('Shots'), style: const TextStyle(fontSize: 12, color: Colors.white60)), const SizedBox(width: 8), for (final n in sorted) ...[ _BarPill( label: '$n', selected: n == selected, empty: !formats.contains(n), onTap: formats.contains(n) ? () => setState(() => _shots = n) : null), const SizedBox(width: 6), ], ], ), ), ), 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), ], ), ), ], ), ); } // 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 const divider = VerticalDivider(width: 1, color: Colors.white24); return ClipRRect( borderRadius: BorderRadius.circular(20), child: ColoredBox( color: surf.card, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Dark header: all four numbers in equal columns Container( color: AppTheme.bar, padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 14), child: IntrinsicHeight( child: Row( children: [ Expanded( child: _MiniStat( label: s.t('Average per shot'), value: stats.averagePerShot?.toStringAsFixed(2) ?? 'โ€“', ), ), divider, Expanded( child: _MiniStat( label: s.t('Best target'), value: '${stats.best!.score}', ), ), divider, Expanded( child: _MiniStat( label: s.t('Average target'), value: stats.averageTarget!.toStringAsFixed(1), ), ), divider, Expanded( child: _MiniStat( label: s.t(_filter == _Filter.tournament ? 'Tournaments' : 'Trainings'), value: '${stats.sessions}', ), ), ], ), ), ), if (chartSessions.length > 1) Padding( padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), child: ProgressChart( points: _chartPoints(chartSessions), color: s.bulletColor, textColor: surf.textSecondary, gridColor: surf.divider, ), ), ], ), ), ); } List _buildHistory(List sessions) { final s = AppSettings.instance; final surf = Surfaces.current; final widgets = []; String monthOf(Session x) => DateFormat('LLLL yyyy', _locale).format(x.date).toUpperCase(); if (_sortByScore) { // Average per shot, so sessions with more targets don't win by volume final ranked = [...sessions]..sort( (a, b) => (b.averagePerShot ?? 0).compareTo(a.averagePerShot ?? 0)); widgets.add(_sortBar(s.t('Best results').toUpperCase())); widgets.addAll(ranked.map(_sessionCard)); return widgets; } String? month; for (final session in sessions) { final m = monthOf(session); if (m != month) { // The first month header shares its row with the sort toggle widgets.add(month == null ? _sortBar(m) : _monthHeader(m)); month = m; } widgets.add(_sessionCard(session)); } if (sessions.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; } // Sort choice sits right above the list it sorts Widget _sortBar(String title) { final s = AppSettings.instance; final surf = Surfaces.current; return Padding( padding: const EdgeInsets.fromLTRB(4, 16, 0, 4), child: Row( children: [ Expanded( child: Text( title, style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, letterSpacing: 1.4, color: surf.textSecondary, ), ), ), SegmentedButton( showSelectedIcon: false, style: SegmentedButton.styleFrom( visualDensity: VisualDensity.compact, selectedBackgroundColor: s.bulletColor, selectedForegroundColor: Colors.white, foregroundColor: surf.textSecondary, textStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600), ), segments: [ ButtonSegment( value: false, icon: const Icon(Icons.event_rounded, size: 16), label: Text(s.t('Sort by Date'))), ButtonSegment( value: true, icon: const Icon(Icons.leaderboard_rounded, size: 16), label: Text(s.t('Sort by Score'))), ], selected: {_sortByScore}, onSelectionChanged: (v) => setState(() => _sortByScore = v.first), ), ], ), ); } 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, ), ), ); } // Date block on the left like the calendar cards. Tap shows this session's // targets of the selected format on one target; the menu opens details/edit. Widget _sessionCard(Session session) { final s = AppSettings.instance; final surf = Surfaces.current; final avg = session.averagePerShot; 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: [ _DateBlock( date: session.date, color: s.bulletColor, locale: _locale), Expanded( child: Material( color: Colors.transparent, child: InkWell( onTap: () => _openTargets(session), onLongPress: () => _openDetails(session), child: Padding( padding: const EdgeInsets.fromLTRB(14, 12, 4, 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), ), ], ), ), Text( '${session.totalScore}', style: TextStyle( fontSize: 22, fontWeight: FontWeight.w800, color: surf.textPrimary), ), ], ), ), ), ), ), IconButton( tooltip: s.t('Details'), icon: Icon(Icons.more_vert_rounded, color: surf.textSecondary), onPressed: () => _openDetails(session), ), ], ), ), ), ); } Future _openTargets(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), ), ], ), ); } } /// What Knjiga shows and where to tap; opened from the info button in the app bar. void showBookHelp(BuildContext context) { final s = AppSettings.instance; showHelpSheet(context, accent: s.bulletColor, t: s.t, items: const [ ( Icons.emoji_events_rounded, 'Trainings / Tournaments: choose which sessions the statistics count.' ), ( Icons.filter_5_rounded, 'Shots 1โ€“5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.' ), ( Icons.calendar_month_rounded, 'Year (top right): choose which year to show.' ), ( Icons.show_chart_rounded, 'Graph: average per shot over time. Tap or drag on it to see each value.' ), ( Icons.leaderboard_rounded, 'By date / By score: sort the list by date or by best average per shot.' ), ( Icons.touch_app_rounded, 'Tap a session to see all its targets with the selected number of shots on one target.' ), ( Icons.more_vert_rounded, 'Three dots on the right or long press: session details, single targets, rename and delete.' ), ]); } class _MiniStat extends StatelessWidget { final String label; final String value; const _MiniStat({required this.label, required this.value}); // White on the dark header; labels get two lines since four share the width @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: Column( children: [ Text(value, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.w800, color: Colors.white)), const SizedBox(height: 2), Text(label, textAlign: TextAlign.center, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 11, color: Colors.white60, height: 1.2)), ], ), ); } } /// 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 bool empty; // no targets with this many shots final VoidCallback? onTap; // null = not selectable const _BarPill( {required this.label, required this.selected, this.empty = false, 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: 14, vertical: 6), child: Text( label, style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: selected ? Colors.black : (empty ? Colors.white30 : Colors.white70), ), ), ), ), ); } }