Files
SDKmuta/lib/screens/book_screen.dart
T
2026-10-26 20:48:16 +01:00

729 lines
23 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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/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<BookScreen> createState() => _BookScreenState();
}
class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
static const int _chartSessions = 12;
List<Session>? _sessions; // selected year only; null while loading
List<int> _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<void> _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<Session> get _filtered => [
for (final s in _sessions ?? <Session>[])
if (s.isTournament == (_filter == _Filter.tournament)) s,
];
// Shots-per-target formats in the current tab, most used first
List<int> _formats(List<Session> sessions) {
final counts = <int, int>{};
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<void> _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: [
if (stats.targets == 0)
_buildEmpty()
else ...[
_buildSummary(sessions, stats),
..._buildHistory(sessions),
],
],
),
),
),
],
);
},
);
}
// 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<int> 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),
],
],
),
),
),
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<ChartPoint> _chartPoints(List<Session> chronological) {
if (chronological.length <= _chartSessions) {
return [
for (final x in chronological)
ChartPoint(DateFormat('d. M.').format(x.date), x.averagePerShot!),
];
}
final byMonth = <int, List<Session>>{};
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<Session> 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<Widget> _buildHistory(List<Session> sessions) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final widgets = <Widget>[];
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: [
_DateBlock(
date: session.date, color: s.bulletColor, locale: _locale),
Expanded(
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),
),
],
),
),
Text(
'${session.totalScore}',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w800,
color: surf.textPrimary),
),
],
),
),
),
),
),
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<void> _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,
),
),
),
),
);
}
}