import 'package:flutter/material.dart';
import '../../core/localization/app_localizations.dart';
import '../../core/theme/app_colors.dart';
import '../../data/app_data_scope.dart';
import '../../models/navigation_snapshot.dart';
import '../../models/poi.dart';
import '../../models/tour.dart';
import '../../services/guide_audio_service.dart';
import '../../services/analytics_service.dart';
import '../../services/partner_recommendation_service.dart';
import '../../widgets/affiliate_ticket_button.dart';
import '../../widgets/partner_recommendations.dart';
import '../../widgets/tour_map.dart';
import '../../widgets/remote_image.dart';
import '../../widgets/media_gallery.dart';
import '../../widgets/image_caption.dart';
import 'tour_completion_page.dart';
class GuidePage extends StatefulWidget {
const GuidePage({super.key, required this.tour});
final Tour tour;
@override
State<GuidePage> createState() => _GuidePageState();
}
class _GuidePageState extends State<GuidePage> {
final GuideAudioService _audio = GuideAudioService();
final PartnerRecommendationService _partnerRecommendations =
const PartnerRecommendationService();
int _index = 0;
bool _speaking = false;
NavigationSnapshot? _navigation;
Poi? _detailedPoi;
TourStop get _stop => widget.tour.stops[_index];
@override
void initState() {
super.initState();
AnalyticsService.instance.track('tour_stop_view', properties: {
'tour_id': widget.tour.id,
'poi_id': _stop.poiId,
'stop_index': 0,
'stop_count': widget.tour.stops.length
});
WidgetsBinding.instance.addPostFrameCallback((_) => _loadPoiDetail());
}
Future<void> _loadPoiDetail() async {
final id = _stop.poiId;
try {
final detail = await AppDataScope.read(context).poiDetail(id);
if (!mounted || _stop.poiId != id) return;
setState(() => _detailedPoi = detail);
_prewarmCurrentAudio();
} catch (_) {
// The active tour still works with the already loaded POI list data.
}
}
Future<void> _prewarmCurrentAudio() async {
if (!mounted) return;
final lang = Localizations.localeOf(context).languageCode;
final resolved = _stop.guideText.resolve(lang);
final url = _stop.audioUrls[resolved.languageCode] ?? _stop.audioUrls[lang];
await _audio.prewarm(
text: resolved.text,
languageCode: resolved.languageCode,
prerecordedUrl: url,
);
}
@override
void dispose() {
_audio.dispose();
super.dispose();
}
Future<void> _toggleAudio(String lang) async {
if (_speaking) {
await _audio.stop();
if (mounted) setState(() => _speaking = false);
return;
}
final resolved = _stop.guideText.resolve(lang);
final url = _stop.audioUrls[resolved.languageCode] ?? _stop.audioUrls[lang];
await AnalyticsService.instance.audioStart(
poiId: _stop.poiId,
source: url?.trim().isNotEmpty == true ? 'prerecorded' : 'tts',
);
await _audio.speak(
text: resolved.text,
languageCode: resolved.languageCode,
prerecordedUrl: url,
);
if (mounted) setState(() => _speaking = true);
}
Future<void> _next() async {
if (_index < widget.tour.stops.length - 1) {
await _selectStop(_index + 1);
}
}
Future<void> _selectStop(int index) async {
if (index < 0 || index >= widget.tour.stops.length || index == _index) {
return;
}
await _audio.stop();
if (!mounted) return;
setState(() {
_index = index;
_speaking = false;
_navigation = null;
_detailedPoi = null;
});
await AnalyticsService.instance.track('tour_stop_view', properties: {
'tour_id': widget.tour.id,
'poi_id': _stop.poiId,
'stop_index': _index,
'stop_count': widget.tour.stops.length
});
WidgetsBinding.instance.addPostFrameCallback((_) => _loadPoiDetail());
}
void _onNavigationChanged(NavigationSnapshot snapshot) {
final previous = _navigation;
final changed = previous == null ||
previous.arrived != snapshot.arrived ||
previous.locationAvailable != snapshot.locationAvailable ||
((previous.distanceMeters ?? 0) - (snapshot.distanceMeters ?? 0))
.abs() >=
5 ||
previous.durationMinutes != snapshot.durationMinutes ||
previous.instruction != snapshot.instruction;
if (!changed || !mounted) return;
if (snapshot.arrived && previous?.arrived != true) {
AnalyticsService.instance.track('tour_stop_arrived', properties: {
'tour_id': widget.tour.id,
'poi_id': _stop.poiId,
'stop_index': _index
});
}
setState(() => _navigation = snapshot);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final lang = Localizations.localeOf(context).languageCode;
final store = AppDataScope.of(context);
final basePoi = store.poiById(_stop.poiId);
final poi = _detailedPoi?.id == _stop.poiId ? _detailedPoi! : basePoi;
final progress = (_index + 1) / widget.tour.stops.length;
final isLastStop = _index == widget.tour.stops.length - 1;
final recommendations = _partnerRecommendations.recommend(
partners: store.partners,
tour: widget.tour,
targetPoi: poi,
isTourEnd: isLastStop,
languageCode: lang,
);
return Scaffold(
appBar: AppBar(
title: Text(l10n.tf('guideStopProgress',
{'current': _index + 1, 'total': widget.tour.stops.length})),
),
body: ListView(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 28),
children: [
ClipRRect(
borderRadius: BorderRadius.circular(999),
child: LinearProgressIndicator(
value: progress,
minHeight: 7,
backgroundColor: AppColors.line,
),
),
const SizedBox(height: 10),
Row(
children: [
Text(
l10n.tf('guideStopsRemaining',
{'n': widget.tour.stops.length - _index - 1}),
style: const TextStyle(
color: AppColors.mutedInk,
fontSize: 12,
fontWeight: FontWeight.w700)),
const Spacer(),
Text('${(progress * 100).round()} %',
style: const TextStyle(
color: AppColors.heartRed,
fontSize: 12,
fontWeight: FontWeight.w900)),
],
),
const SizedBox(height: 14),
_NavigationSummary(
stopNumber: _index + 1,
totalStops: widget.tour.stops.length,
stopTitle: poi.title.get(lang),
snapshot: _navigation,
),
const SizedBox(height: 14),
TourMap(
tour: widget.tour,
activeStopIndex: _index,
height: 330,
liveLocation: true,
showNavigationCard: true,
onNavigationChanged: _onNavigationChanged,
onStopSelected: (index) => _selectStop(index),
),
const SizedBox(height: 24),
RemoteImage(
url: poi.imageUrl,
height: 250,
width: double.infinity,
fit: BoxFit.cover,
borderRadius: BorderRadius.circular(26),
fallbackIcon: Icons.location_city_rounded,
fallbackIconSize: 66,
semanticLabel: poi.title.get(lang),
),
if (poi.imageUrl?.trim().isNotEmpty == true)
ImageCaption(text: poi.imageCaption),
if (poi.galleryUrls.isNotEmpty) ...[
const SizedBox(height: 26),
MediaGallery(
urls: poi.galleryUrls,
title: l10n.t('moreImages'),
height: 210,
),
],
const SizedBox(height: 24),
Text(
poi.title.get(lang),
style: const TextStyle(
color: AppColors.heartRed,
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 7),
Text(
_stop.title.get(lang),
style: Theme.of(context)
.textTheme
.headlineMedium
?.copyWith(fontWeight: FontWeight.w900),
),
if (poi.hasAffiliateTicket) ...[
const SizedBox(height: 16),
AffiliateTicketButton(poi: poi),
],
const SizedBox(height: 18),
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: AppColors.ink,
borderRadius: BorderRadius.circular(22),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.headphones, color: Colors.white),
const SizedBox(width: 8),
Text(
l10n.t('audio'),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w800,
),
),
const Spacer(),
IconButton(
onPressed: () => _toggleAudio(lang),
icon: Icon(
_speaking
? Icons.stop_circle_outlined
: Icons.play_circle_fill,
color: Colors.white,
size: 36,
),
),
],
),
const SizedBox(height: 4),
Text(
l10n.t('audioTtsNote'),
style: TextStyle(
color: Colors.white.withValues(alpha: .7),
fontSize: 12,
),
),
],
),
),
const SizedBox(height: 24),
Text(
l10n.t('text'),
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.w800),
),
const SizedBox(height: 10),
SelectableText(
_stop.guideText.get(lang),
style:
Theme.of(context).textTheme.bodyLarge?.copyWith(height: 1.65),
),
const SizedBox(height: 26),
if (poi.address != null)
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.place_outlined, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
poi.address!,
style: const TextStyle(color: AppColors.mutedInk),
),
),
],
),
if (recommendations.isNotEmpty) ...[
const SizedBox(height: 30),
PartnerRecommendations(items: recommendations),
],
const SizedBox(height: 28),
if (!isLastStop)
FilledButton.icon(
onPressed: _next,
icon: Icon(
_navigation?.arrived == true
? Icons.check_circle_rounded
: Icons.directions_walk,
),
label: Text(
_navigation?.arrived == true
? l10n
.tf('stationReachedNext', {'next': l10n.t('nextStop')})
: l10n.t('nextStop'),
),
)
else
FilledButton.icon(
onPressed: () async {
await AnalyticsService.instance.tourComplete(
tourId: widget.tour.id,
stopCount: widget.tour.stops.length,
);
if (!context.mounted) return;
await Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => TourCompletionPage(tour: widget.tour)),
);
},
icon: const Icon(Icons.celebration_rounded),
label: Text(l10n.t('endTour')),
),
],
),
);
}
}
class _NavigationSummary extends StatelessWidget {
const _NavigationSummary({
required this.stopNumber,
required this.totalStops,
required this.stopTitle,
required this.snapshot,
});
final int stopNumber;
final int totalStops;
final String stopTitle;
final NavigationSnapshot? snapshot;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final s = snapshot;
final distance = s?.distanceMeters;
final duration = s?.durationMinutes;
String subtitle;
IconData icon;
if (s == null || !s.locationAvailable) {
subtitle = l10n.t('liveLocationLoading');
icon = Icons.gps_fixed_rounded;
} else if (s.arrived) {
subtitle = l10n.t('arrivedAtStop');
icon = Icons.flag_rounded;
} else {
final parts = <String>[
if (distance != null) _distance(distance),
if (duration != null) l10n.tf('approxWalkMinutes', {'n': duration}),
];
subtitle =
parts.isEmpty ? l10n.t('walkingRouteCalculating') : parts.join(' · ');
icon = Icons.directions_walk_rounded;
}
return Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: s?.arrived == true ? AppColors.softPink : Colors.white,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: s?.arrived == true ? AppColors.heartRed : AppColors.line,
),
),
child: Row(
children: [
CircleAvatar(
backgroundColor: AppColors.ink,
foregroundColor: Colors.white,
child: Icon(icon),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${l10n.t('nextStationLabel')} $stopNumber/$totalStops',
style: const TextStyle(
color: AppColors.heartRed,
fontWeight: FontWeight.w800,
fontSize: 12,
),
),
const SizedBox(height: 2),
Text(
stopTitle,
style: const TextStyle(
fontWeight: FontWeight.w900,
fontSize: 16,
),
),
const SizedBox(height: 3),
Text(
subtitle,
style: const TextStyle(color: AppColors.mutedInk),
),
if (s?.instruction?.trim().isNotEmpty == true &&
s?.arrived != true) ...[
const SizedBox(height: 3),
Text(
s!.instruction!,
style: const TextStyle(fontWeight: FontWeight.w700),
),
],
],
),
),
],
),
);
}
static String _distance(int meters) {
if (meters < 1000) return '$meters m';
return '${(meters / 1000).toStringAsFixed(1)} km';
}
}

