Files
plezy/lib/screens/discover_screen.dart
T
2025-12-12 15:57:22 +01:00

1574 lines
57 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../services/plex_client.dart';
import '../utils/plex_image_helper.dart';
import '../models/plex_metadata.dart';
import '../models/plex_hub.dart';
import '../providers/multi_server_provider.dart';
import '../providers/server_state_provider.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/playback_state_provider.dart';
import '../widgets/desktop_app_bar.dart';
import 'profile/user_avatar_widget.dart';
import '../widgets/hub_section.dart';
import 'profile/profile_switch_screen.dart';
import '../providers/user_profile_provider.dart';
import '../providers/settings_provider.dart';
import '../mixins/refreshable.dart';
import '../i18n/strings.g.dart';
import '../mixins/item_updatable.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import '../focus/dpad_navigator.dart';
import 'auth_screen.dart';
class DiscoverScreen extends StatefulWidget {
final VoidCallback? onBecameVisible;
const DiscoverScreen({super.key, this.onBecameVisible});
@override
State<DiscoverScreen> createState() => _DiscoverScreenState();
}
class _DiscoverScreenState extends State<DiscoverScreen>
with Refreshable, ItemUpdatable, SingleTickerProviderStateMixin {
static const Duration _heroAutoScrollDuration = Duration(seconds: 8);
@override
PlexClient get client {
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
if (!multiServerProvider.hasConnectedServers) {
throw Exception('No servers available');
}
return context.getClientForServer(
multiServerProvider.onlineServerIds.first,
);
}
List<PlexMetadata> _onDeck = [];
List<PlexHub> _hubs = [];
bool _isLoading = true;
bool _areHubsLoading = true;
String? _errorMessage;
final PageController _heroController = PageController();
final ScrollController _scrollController = ScrollController();
int _currentHeroIndex = 0;
Timer? _autoScrollTimer;
late AnimationController _indicatorAnimationController;
bool _isAutoScrollPaused = false;
// Hub navigation keys
GlobalKey<HubSectionState>? _continueWatchingHubKey;
final List<GlobalKey<HubSectionState>> _hubKeys = [];
// Hero and app bar focus
late FocusNode _heroFocusNode;
late FocusNode _refreshButtonFocusNode;
late FocusNode _userButtonFocusNode;
bool _isRefreshFocused = false;
bool _isUserFocused = false;
/// Get the correct PlexClient for an item's server
PlexClient _getClientForItem(PlexMetadata? item) {
// Items should always have a serverId, but if not, fall back to first available server
final serverId = item?.serverId;
if (serverId == null) {
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
if (!multiServerProvider.hasConnectedServers) {
throw Exception('No servers available');
}
return context.getClientForServer(
multiServerProvider.onlineServerIds.first,
);
}
return context.getClientForServer(serverId);
}
/// Update hub keys when hubs list changes
void _updateHubKeys() {
_hubKeys.clear();
for (int i = 0; i < _hubs.length; i++) {
_hubKeys.add(GlobalKey<HubSectionState>());
}
// Create continue watching hub key if needed
if (_onDeck.isNotEmpty) {
_continueWatchingHubKey ??= GlobalKey<HubSectionState>();
}
}
/// Get all hub states (continue watching + other hubs)
List<GlobalKey<HubSectionState>> get _allHubKeys {
final keys = <GlobalKey<HubSectionState>>[];
if (_continueWatchingHubKey != null && _onDeck.isNotEmpty) {
keys.add(_continueWatchingHubKey!);
}
keys.addAll(_hubKeys);
return keys;
}
/// Handle vertical navigation between hubs
/// Returns true if the navigation was handled
bool _handleVerticalNavigation(int hubIndex, bool isUp) {
final keys = _allHubKeys;
if (keys.isEmpty) return false;
// UP from first hub: Navigate to hero section
if (isUp && hubIndex == 0) {
_heroFocusNode.requestFocus();
// Scroll to top to show hero fully
_scrollController.animateTo(
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
return true;
}
int targetIndex;
if (isUp) {
targetIndex = hubIndex - 1;
} else {
targetIndex = hubIndex + 1;
}
// Check if target is valid
if (targetIndex < 0 || targetIndex >= keys.length) {
// At boundary, block navigation (return true to consume the event)
return true;
}
// Navigate to target hub, clamping to available items
final targetState = keys[targetIndex].currentState;
if (targetState != null) {
targetState.requestFocusFromMemory();
return true;
}
return false;
}
@override
void initState() {
super.initState();
_indicatorAnimationController = AnimationController(
vsync: this,
duration: _heroAutoScrollDuration,
);
_heroFocusNode = FocusNode(debugLabel: 'hero_section');
_refreshButtonFocusNode = FocusNode(debugLabel: 'refresh_button');
_userButtonFocusNode = FocusNode(debugLabel: 'user_button');
_refreshButtonFocusNode.addListener(_onRefreshFocusChange);
_userButtonFocusNode.addListener(_onUserFocusChange);
_loadContent();
_startAutoScroll();
}
void _onRefreshFocusChange() {
if (mounted) {
setState(() {
_isRefreshFocused = _refreshButtonFocusNode.hasFocus;
});
}
}
void _onUserFocusChange() {
if (mounted) {
setState(() {
_isUserFocused = _userButtonFocusNode.hasFocus;
});
}
}
/// Handle key events for the hero section
KeyEventResult _handleHeroKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// DOWN: Move to first hub
if (key.isDownKey) {
final keys = _allHubKeys;
if (keys.isNotEmpty) {
keys.first.currentState?.requestFocusFromMemory();
}
return KeyEventResult.handled;
}
// UP: Move to app bar (refresh button)
if (key.isUpKey) {
_refreshButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// LEFT: Navigate hero carousel to previous
if (key.isLeftKey) {
if (_currentHeroIndex > 0) {
_heroController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
return KeyEventResult.handled;
}
// RIGHT: Navigate hero carousel to next
if (key.isRightKey) {
if (_currentHeroIndex < _onDeck.length - 1) {
_heroController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
return KeyEventResult.handled;
}
// SELECT: Play current hero item
if (key.isSelectKey) {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length) {
navigateToVideoPlayer(context, metadata: _onDeck[_currentHeroIndex]);
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Handle key events for the refresh button in app bar
KeyEventResult _handleRefreshKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// DOWN: Return to hero
if (key.isDownKey) {
_heroFocusNode.requestFocus();
return KeyEventResult.handled;
}
// RIGHT: Move to user button
if (key.isRightKey) {
_userButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// LEFT/UP: Block at boundary
if (key.isLeftKey || key.isUpKey) {
return KeyEventResult.handled;
}
// SELECT: Trigger refresh
if (key.isSelectKey) {
_loadContent();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Handle key events for the user button in app bar
KeyEventResult _handleUserKeyEvent(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
// DOWN: Return to hero
if (key.isDownKey) {
_heroFocusNode.requestFocus();
return KeyEventResult.handled;
}
// LEFT: Move to refresh button
if (key.isLeftKey) {
_refreshButtonFocusNode.requestFocus();
return KeyEventResult.handled;
}
// RIGHT/UP: Block at boundary
if (key.isRightKey || key.isUpKey) {
return KeyEventResult.handled;
}
// SELECT: Show user menu
if (key.isSelectKey) {
final userProvider = context.read<UserProfileProvider>();
_showUserMenu(context, userProvider);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
void dispose() {
_autoScrollTimer?.cancel();
_heroController.dispose();
_scrollController.dispose();
_indicatorAnimationController.dispose();
_heroFocusNode.dispose();
_refreshButtonFocusNode.removeListener(_onRefreshFocusChange);
_refreshButtonFocusNode.dispose();
_userButtonFocusNode.removeListener(_onUserFocusChange);
_userButtonFocusNode.dispose();
super.dispose();
}
void _startAutoScroll() {
if (_isAutoScrollPaused) return;
_indicatorAnimationController.forward(from: 0.0);
_autoScrollTimer = Timer.periodic(_heroAutoScrollDuration, (timer) {
if (_onDeck.isEmpty ||
!_heroController.hasClients ||
_isAutoScrollPaused) {
return;
}
// Validate current index is within bounds before calculating next page
if (_currentHeroIndex >= _onDeck.length) {
_currentHeroIndex = 0;
}
final nextPage = (_currentHeroIndex + 1) % _onDeck.length;
_heroController.animateToPage(
nextPage,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
// Wait for page transition to complete before resetting progress
Future.delayed(const Duration(milliseconds: 500), () {
if (!_isAutoScrollPaused) {
_indicatorAnimationController.forward(from: 0.0);
}
});
});
}
void _resetAutoScrollTimer() {
_autoScrollTimer?.cancel();
_startAutoScroll();
}
void _pauseAutoScroll() {
setState(() {
_isAutoScrollPaused = true;
});
_autoScrollTimer?.cancel();
_indicatorAnimationController.stop();
}
void _resumeAutoScroll() {
setState(() {
_isAutoScrollPaused = false;
});
_startAutoScroll();
}
// Helper method to calculate visible dot range (max 5 dots)
({int start, int end}) _getVisibleDotRange() {
final totalDots = _onDeck.length;
if (totalDots <= 5) {
return (start: 0, end: totalDots - 1);
}
// Center the active dot when possible
final center = _currentHeroIndex;
int start = (center - 2).clamp(0, totalDots - 5);
int end = start + 4; // 5 dots total (0-4 inclusive)
return (start: start, end: end);
}
// Helper method to determine dot size based on position
double _getDotSize(int dotIndex, int start, int end) {
final totalDots = _onDeck.length;
// If we have 5 or fewer dots, all are full size (8px)
if (totalDots <= 5) {
return 8.0;
}
// First and last visible dots are smaller if there are more items beyond them
final isFirstVisible = dotIndex == start && start > 0;
final isLastVisible = dotIndex == end && end < totalDots - 1;
if (isFirstVisible || isLastVisible) {
return 5.0; // Smaller edge dots
}
return 8.0; // Normal size
}
Future<void> _loadContent() async {
appLogger.d('Loading discover content from all servers');
setState(() {
_isLoading = true;
_areHubsLoading = true;
_errorMessage = null;
});
try {
appLogger.d('Fetching onDeck and hubs from all Plex servers');
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
if (!multiServerProvider.hasConnectedServers) {
throw Exception('No servers available');
}
// Start OnDeck and libraries fetch in parallel
final onDeckFuture = multiServerProvider.aggregationService
.getOnDeckFromAllServers(limit: 20);
final librariesFuture = multiServerProvider.aggregationService
.getLibrariesFromAllServersGrouped();
// Wait for OnDeck to complete and show it immediately
final onDeck = await onDeckFuture;
setState(() {
_onDeck = onDeck;
_isLoading = false; // Show content, but hubs still loading
// Reset hero index to avoid sync issues
_currentHeroIndex = 0;
// Create continue watching hub key if needed
if (_onDeck.isNotEmpty) {
_continueWatchingHubKey ??= GlobalKey<HubSectionState>();
}
});
// Sync PageController to first page after OnDeck loads
if (_heroController.hasClients && onDeck.isNotEmpty) {
_heroController.jumpToPage(0);
}
// Wait for libraries and then fetch hubs
final librariesByServer = await librariesFuture;
// Get hidden libraries to filter from hubs
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
context,
listen: false,
);
// Fetch hubs using the pre-fetched libraries and hidden keys
final allHubs = await multiServerProvider.aggregationService
.getHubsFromAllServers(
librariesByServer: librariesByServer,
hiddenLibraryKeys: hiddenLibrariesProvider.hiddenLibraryKeys,
);
// Filter out duplicate hubs that we already fetch separately
final filteredHubs = allHubs.where((hub) {
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
final title = hub.title.toLowerCase();
// Skip "Continue Watching" and "On Deck" hubs (we handle these separately)
return !hubId.contains('ondeck') &&
!hubId.contains('continue') &&
!title.contains('continue watching') &&
!title.contains('on deck');
}).toList();
appLogger.d(
'Received ${onDeck.length} on deck items and ${filteredHubs.length} hubs from all servers',
);
setState(() {
_hubs = filteredHubs;
_areHubsLoading = false;
_updateHubKeys();
});
appLogger.d('Discover content loaded successfully');
} catch (e) {
appLogger.e('Failed to load discover content', error: e);
setState(() {
_errorMessage = 'Failed to load content: $e';
_isLoading = false;
_areHubsLoading = false;
});
}
}
/// Refresh only the Continue Watching section in the background
/// This is called when returning to the home screen to avoid blocking UI
Future<void> _refreshContinueWatching() async {
appLogger.d('Refreshing Continue Watching in background from all servers');
try {
final multiServerProvider = context.read<MultiServerProvider>();
if (!multiServerProvider.hasConnectedServers) {
appLogger.w('No servers available for background refresh');
return;
}
final onDeck = await multiServerProvider.aggregationService
.getOnDeckFromAllServers(limit: 20);
if (mounted) {
setState(() {
_onDeck = onDeck;
// Reset hero index if needed
if (_currentHeroIndex >= onDeck.length) {
_currentHeroIndex = 0;
if (_heroController.hasClients && onDeck.isNotEmpty) {
_heroController.jumpToPage(0);
}
}
});
appLogger.d('Continue Watching refreshed successfully');
}
} catch (e) {
appLogger.w('Failed to refresh Continue Watching', error: e);
// Silently fail - don't show error to user for background refresh
}
}
// Public method to refresh content (for normal navigation)
@override
void refresh() {
appLogger.d('DiscoverScreen.refresh() called');
// Only refresh Continue Watching in background, not full screen reload
_refreshContinueWatching();
}
// Public method to fully reload all content (for profile switches)
void fullRefresh() {
appLogger.d('DiscoverScreen.fullRefresh() called - reloading all content');
// Reload all content including On Deck and content hubs
_loadContent();
}
/// Get icon for hub based on its title
IconData _getHubIcon(String title) {
final lowerTitle = title.toLowerCase();
// Trending/Popular content
if (lowerTitle.contains('trending')) {
return Symbols.trending_up_rounded;
}
if (lowerTitle.contains('popular') || lowerTitle.contains('imdb')) {
return Symbols.whatshot_rounded;
}
// Seasonal/Time-based
if (lowerTitle.contains('seasonal')) {
return Symbols.calendar_month_rounded;
}
if (lowerTitle.contains('newly') || lowerTitle.contains('new release')) {
return Symbols.new_releases_rounded;
}
if (lowerTitle.contains('recently released') ||
lowerTitle.contains('recent')) {
return Symbols.schedule_rounded;
}
// Top/Rated content
if (lowerTitle.contains('top rated') ||
lowerTitle.contains('highest rated')) {
return Symbols.star_rounded;
}
if (lowerTitle.contains('top ')) {
return Symbols.military_tech_rounded;
}
// Genre-specific
if (lowerTitle.contains('thriller')) {
return Symbols.warning_amber_rounded;
}
if (lowerTitle.contains('comedy') || lowerTitle.contains('comedier')) {
return Symbols.mood_rounded;
}
if (lowerTitle.contains('action')) {
return Symbols.flash_on_rounded;
}
if (lowerTitle.contains('drama')) {
return Symbols.theater_comedy_rounded;
}
if (lowerTitle.contains('fantasy')) {
return Symbols.auto_fix_high_rounded;
}
if (lowerTitle.contains('science') || lowerTitle.contains('sci-fi')) {
return Symbols.rocket_launch_rounded;
}
if (lowerTitle.contains('horror') || lowerTitle.contains('skräck')) {
return Symbols.nights_stay_rounded;
}
if (lowerTitle.contains('romance') || lowerTitle.contains('romantic')) {
return Symbols.favorite_border_rounded;
}
if (lowerTitle.contains('adventure') || lowerTitle.contains('äventyr')) {
return Symbols.explore_rounded;
}
// Watchlist/Playlists
if (lowerTitle.contains('playlist') || lowerTitle.contains('watchlist')) {
return Symbols.playlist_play_rounded;
}
if (lowerTitle.contains('unwatched') || lowerTitle.contains('unplayed')) {
return Symbols.visibility_off_rounded;
}
if (lowerTitle.contains('watched') || lowerTitle.contains('played')) {
return Symbols.visibility_rounded;
}
// Network/Studio
if (lowerTitle.contains('network') || lowerTitle.contains('more from')) {
return Symbols.tv_rounded;
}
// Actor/Director
if (lowerTitle.contains('actor') || lowerTitle.contains('director')) {
return Symbols.person_rounded;
}
// Year-based (80s, 90s, etc.)
if (lowerTitle.contains('80') ||
lowerTitle.contains('90') ||
lowerTitle.contains('00')) {
return Symbols.history_rounded;
}
// Rediscover/Start Watching
if (lowerTitle.contains('rediscover') ||
lowerTitle.contains('start watching')) {
return Symbols.play_arrow_rounded;
}
// Default icon for other hubs
return Symbols.auto_awesome_rounded;
}
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
// Check and update in _onDeck list
final onDeckIndex = _onDeck.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (onDeckIndex != -1) {
_onDeck[onDeckIndex] = updatedMetadata;
}
// Check and update in hub items
for (final hub in _hubs) {
final itemIndex = hub.items.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (itemIndex != -1) {
hub.items[itemIndex] = updatedMetadata;
}
}
}
Future<void> _handleLogout() async {
final confirm = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(t.common.logout),
content: Text(t.messages.logoutConfirm),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(t.common.cancel),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: Text(t.common.logout),
),
],
),
);
if (confirm == true && mounted) {
// Use comprehensive logout through UserProfileProvider
final userProfileProvider = Provider.of<UserProfileProvider>(
context,
listen: false,
);
final plexClientProvider = context.plexClient;
final multiServerProvider = context.read<MultiServerProvider>();
final serverStateProvider = context.read<ServerStateProvider>();
final hiddenLibrariesProvider = context.read<HiddenLibrariesProvider>();
final playbackStateProvider = context.read<PlaybackStateProvider>();
// Clear all user data and provider states
await userProfileProvider.logout();
plexClientProvider.clearClient();
multiServerProvider.clearAllConnections();
serverStateProvider.reset();
await hiddenLibrariesProvider.refresh();
playbackStateProvider.clearShuffle();
if (mounted) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => const AuthScreen()),
(route) => false,
);
}
}
}
void _handleSwitchProfile(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()),
);
}
/// Show user menu programmatically (for D-pad select)
void _showUserMenu(BuildContext context, UserProfileProvider userProvider) {
final RenderBox? button =
_userButtonFocusNode.context?.findRenderObject() as RenderBox?;
if (button == null) return;
final RenderBox overlay =
Navigator.of(context).overlay!.context.findRenderObject() as RenderBox;
final position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset.zero, ancestor: overlay),
button.localToGlobal(
button.size.bottomRight(Offset.zero),
ancestor: overlay,
),
),
Offset.zero & overlay.size,
);
showMenu<String>(
context: context,
position: position,
items: [
if (userProvider.hasMultipleUsers)
PopupMenuItem(
value: 'switch_profile',
child: Row(
children: [
AppIcon(Symbols.people_rounded, fill: 1),
SizedBox(width: 8),
Text(t.discover.switchProfile),
],
),
),
PopupMenuItem(
value: 'logout',
child: Row(
children: [
AppIcon(Symbols.logout_rounded, fill: 1),
SizedBox(width: 8),
Text(t.discover.logout),
],
),
),
],
).then((value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'logout') {
_handleLogout();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: CustomScrollView(
controller: _scrollController,
slivers: [
DesktopSliverAppBar(
title: Text(t.discover.title),
floating: true,
pinned: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
surfaceTintColor: Colors.transparent,
shadowColor: Colors.transparent,
scrolledUnderElevation: 0,
actions: [
Focus(
focusNode: _refreshButtonFocusNode,
onKeyEvent: _handleRefreshKeyEvent,
child: Container(
decoration: BoxDecoration(
color: _isRefreshFocused
? Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.08)
: Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: IconButton(
icon: const AppIcon(Symbols.refresh_rounded, fill: 1),
onPressed: _loadContent,
),
),
),
Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
return Focus(
focusNode: _userButtonFocusNode,
onKeyEvent: _handleUserKeyEvent,
child: DecoratedBox(
decoration: BoxDecoration(
color: _isUserFocused
? Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.08)
: Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: PopupMenuButton<String>(
icon: userProvider.currentUser?.thumb != null
? UserAvatarWidget(
user: userProvider.currentUser!,
size: 32,
showIndicators: false,
)
: const AppIcon(Symbols.account_circle_rounded, fill: 1, size: 32),
onSelected: (value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'logout') {
_handleLogout();
}
},
itemBuilder: (context) => [
// Only show Switch Profile if multiple users available
if (userProvider.hasMultipleUsers)
PopupMenuItem(
value: 'switch_profile',
child: Row(
children: [
AppIcon(Symbols.people_rounded, fill: 1),
SizedBox(width: 8),
Text(t.discover.switchProfile),
],
),
),
PopupMenuItem(
value: 'logout',
child: Row(
children: [
AppIcon(Symbols.logout_rounded, fill: 1),
SizedBox(width: 8),
Text(t.discover.logout),
],
),
),
],
),
),
);
},
),
],
),
if (_isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const AppIcon(Symbols.error_outline_rounded, fill: 1, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadContent,
child: Text(t.common.retry),
),
],
),
),
),
if (!_isLoading && _errorMessage == null) ...[
// Hero Section (Continue Watching)
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (_onDeck.isNotEmpty && settingsProvider.showHeroSection) {
return _buildHeroSection();
}
return const SliverToBoxAdapter(child: SizedBox.shrink());
},
),
// On Deck / Continue Watching
if (_onDeck.isNotEmpty)
SliverToBoxAdapter(
child: HubSection(
key: _continueWatchingHubKey,
hub: PlexHub(
hubKey: 'continue_watching',
title: t.discover.continueWatching,
type: 'mixed',
hubIdentifier: '_continue_watching_',
size: _onDeck.length,
more: false,
items: _onDeck,
),
icon: Symbols.play_circle_rounded,
onRefresh: updateItem,
onRemoveFromContinueWatching: _refreshContinueWatching,
isInContinueWatching: true,
onVerticalNavigation: (isUp) =>
_handleVerticalNavigation(0, isUp),
),
),
// Recommendation Hubs (Trending, Top in Genre, etc.)
for (int i = 0; i < _hubs.length; i++)
SliverToBoxAdapter(
child: HubSection(
key: i < _hubKeys.length ? _hubKeys[i] : null,
hub: _hubs[i],
icon: _getHubIcon(_hubs[i].title),
onRefresh: updateItem,
// Hub index is i + 1 if continue watching exists, otherwise i
onVerticalNavigation: (isUp) => _handleVerticalNavigation(
_onDeck.isNotEmpty ? i + 1 : i,
isUp,
),
),
),
// Show loading skeleton for hubs while they're loading
if (_areHubsLoading && _hubs.isEmpty)
for (int i = 0; i < 3; i++)
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Hub title skeleton
Container(
width: 200,
height: 24,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(height: 16),
// Hub items skeleton
SizedBox(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.only(right: 12),
width: 140,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
);
},
),
),
],
),
),
),
if (_onDeck.isEmpty && _hubs.isEmpty && !_areHubsLoading)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AppIcon(Symbols.movie_rounded, fill: 1, size: 64, color: Colors.grey),
SizedBox(height: 16),
Text(t.discover.noContentAvailable),
SizedBox(height: 8),
Text(
t.discover.addMediaToLibraries,
style: TextStyle(color: Colors.grey),
),
],
),
),
),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
],
),
),
);
}
Widget _buildHeroSection() {
return SliverToBoxAdapter(
child: Focus(
focusNode: _heroFocusNode,
autofocus: true,
onKeyEvent: _handleHeroKeyEvent,
child: SizedBox(
height: 500,
child: Stack(
children: [
PageView.builder(
controller: _heroController,
itemCount: _onDeck.length,
onPageChanged: (index) {
// Validate index is within bounds before updating
if (index >= 0 && index < _onDeck.length) {
setState(() {
_currentHeroIndex = index;
});
_resetAutoScrollTimer();
}
},
itemBuilder: (context, index) {
return _buildHeroItem(_onDeck[index]);
},
),
// Page indicators with animated progress and pause/play button
Positioned(
bottom: 16,
left: -26,
right: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Pause/Play button
GestureDetector(
onTap: () {
if (_isAutoScrollPaused) {
_resumeAutoScroll();
} else {
_pauseAutoScroll();
}
},
child: AppIcon(_isAutoScrollPaused ? Symbols.play_arrow_rounded : Symbols.pause_rounded, fill: 1, color: Colors.white, size: 18, semanticLabel: '${_isAutoScrollPaused ? t.discover.play : t.discover.pause} auto-scroll'),
),
// Spacer to separate indicators from button
const SizedBox(width: 8),
// Page indicators (limited to 5 dots)
...() {
final range = _getVisibleDotRange();
return List.generate(range.end - range.start + 1, (i) {
final index = range.start + i;
final isActive = _currentHeroIndex == index;
final dotSize = _getDotSize(
index,
range.start,
range.end,
);
if (isActive) {
// Animated progress indicator for active page
return AnimatedBuilder(
animation: _indicatorAnimationController,
builder: (context, child) {
// Fill width animates based on dot size
final maxWidth =
dotSize *
3; // 24px for normal, 15px for small
final fillWidth =
dotSize +
((maxWidth - dotSize) *
_indicatorAnimationController.value);
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
margin: const EdgeInsets.symmetric(
horizontal: 4,
),
width: maxWidth,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(
dotSize / 2,
),
),
child: Align(
alignment: Alignment.centerLeft,
child: Container(
width: fillWidth,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(
dotSize / 2,
),
),
),
),
);
},
);
} else {
// Static indicator for inactive pages
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
margin: const EdgeInsets.symmetric(horizontal: 4),
width: dotSize,
height: dotSize,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(dotSize / 2),
),
);
}
});
}(),
],
),
),
],
),
),
),
);
}
Widget _buildHeroItem(PlexMetadata heroItem) {
final isEpisode = heroItem.type.toLowerCase() == 'episode';
final showName = heroItem.grandparentTitle ?? heroItem.title;
final screenWidth = MediaQuery.of(context).size.width;
final isLargeScreen = screenWidth > 800;
// Determine content type label for chip
final contentTypeLabel = heroItem.type.toLowerCase() == 'movie'
? t.discover.movie
: t.discover.tvShow;
// Build semantic label for hero item
final heroLabel = isEpisode
? "${heroItem.grandparentTitle}, ${heroItem.title}"
: heroItem.title;
return Semantics(
label: heroLabel,
button: true,
hint: t.accessibility.tapToPlay,
child: GestureDetector(
onTap: () {
appLogger.d('Navigating to VideoPlayerScreen for: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
},
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.3),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Stack(
fit: StackFit.expand,
children: [
// Background Image with fade/zoom animation and parallax
if (heroItem.art != null || heroItem.grandparentArt != null)
AnimatedBuilder(
animation: _scrollController,
builder: (context, child) {
final scrollOffset = _scrollController.hasClients
? _scrollController.offset
: 0.0;
return Transform.translate(
offset: Offset(0, scrollOffset * 0.3),
child: child,
);
},
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0.0, end: 1.0),
duration: const Duration(milliseconds: 800),
curve: Curves.easeOut,
builder: (context, value, child) {
return Transform.scale(
scale: 1.0 + (0.1 * (1 - value)),
child: Opacity(opacity: value, child: child),
);
},
child: Builder(
builder: (context) {
final client = _getClientForItem(heroItem);
final mediaQuery = MediaQuery.of(context);
final imageUrl = PlexImageHelper.getOptimizedImageUrl(
client: client,
thumbPath: heroItem.art ?? heroItem.grandparentArt,
maxWidth: mediaQuery.size.width,
maxHeight: mediaQuery.size.height * 0.7,
devicePixelRatio: mediaQuery.devicePixelRatio,
imageType: ImageType.art,
);
return CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
);
},
),
),
)
else
Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
// Gradient Overlay
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withValues(alpha: 0.7),
Colors.black.withValues(alpha: 0.9),
],
stops: const [0.0, 0.5, 1.0],
),
),
),
// Content with responsive alignment
Positioned(
bottom: isLargeScreen ? 80 : 50,
left: 0,
right: isLargeScreen ? 200 : 0,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: isLargeScreen ? 40 : 16,
),
child: Column(
crossAxisAlignment: isLargeScreen
? CrossAxisAlignment.start
: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
// Show logo or name/title
if (heroItem.clearLogo != null)
SizedBox(
height: 120,
width: 400,
child: Builder(
builder: (context) {
final client = _getClientForItem(heroItem);
final dpr = MediaQuery.of(
context,
).devicePixelRatio;
final logoUrl =
PlexImageHelper.getOptimizedImageUrl(
client: client,
thumbPath: heroItem.clearLogo,
maxWidth: 400,
maxHeight: 120,
devicePixelRatio: dpr,
imageType: ImageType.logo,
);
return CachedNetworkImage(
imageUrl: logoUrl,
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
memCacheWidth: (400 * dpr)
.clamp(200, 800)
.round(),
alignment: isLargeScreen
? Alignment.bottomLeft
: Alignment.bottomCenter,
placeholder: (context, url) => Align(
alignment: isLargeScreen
? Alignment.centerLeft
: Alignment.center,
child: Text(
showName,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
),
errorWidget: (context, url, error) {
// Fallback to text if logo fails to load
return Align(
alignment: isLargeScreen
? Alignment.centerLeft
: Alignment.center,
child: Text(
showName,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
);
},
);
},
),
)
else
Text(
showName,
style: Theme.of(context).textTheme.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
// Metadata as dot-separated text with content type
if (heroItem.year != null ||
heroItem.contentRating != null ||
heroItem.rating != null) ...[
const SizedBox(height: 16),
Text(
[
contentTypeLabel,
if (heroItem.rating != null)
'★ ${heroItem.rating!.toStringAsFixed(1)}',
if (heroItem.contentRating != null)
formatContentRating(heroItem.contentRating!),
if (heroItem.year != null)
heroItem.year.toString(),
].join(' • '),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w500,
),
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
],
// On small screens: show button before summary
if (!isLargeScreen) ...[
const SizedBox(height: 20),
_buildSmartPlayButton(heroItem),
],
// Summary with episode info (Apple TV style)
if (heroItem.summary != null) ...[
const SizedBox(height: 12),
RichText(
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
text: TextSpan(
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
height: 1.4,
),
children: [
if (isEpisode &&
heroItem.parentIndex != null &&
heroItem.index != null)
TextSpan(
text:
'S${heroItem.parentIndex}, E${heroItem.index}: ',
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
TextSpan(
text: heroItem.summary?.isNotEmpty == true
? heroItem.summary!
: 'No description available',
),
],
),
),
],
// On large screens: show button after summary
if (isLargeScreen) ...[
const SizedBox(height: 20),
_buildSmartPlayButton(heroItem),
],
],
),
),
),
],
),
),
),
),
);
}
Widget _buildSmartPlayButton(PlexMetadata heroItem) {
final hasProgress =
heroItem.viewOffset != null &&
heroItem.duration != null &&
heroItem.viewOffset! > 0 &&
heroItem.duration! > 0;
final minutesLeft = hasProgress
? ((heroItem.duration! - heroItem.viewOffset!) / 60000).round()
: 0;
final progress = hasProgress
? heroItem.viewOffset! / heroItem.duration!
: 0.0;
return InkWell(
onTap: () {
appLogger.d('Playing: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
},
borderRadius: BorderRadius.circular(24),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const AppIcon(Symbols.play_arrow_rounded, fill: 1, size: 20, color: Colors.black),
const SizedBox(width: 8),
if (hasProgress) ...[
// Progress bar
Container(
width: 40,
height: 6,
decoration: BoxDecoration(
color: Colors.black26,
borderRadius: BorderRadius.circular(3),
),
child: FractionallySizedBox(
alignment: Alignment.centerLeft,
widthFactor: progress,
child: Container(
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(2),
),
),
),
),
const SizedBox(width: 8),
Text(
t.discover.minutesLeft(minutes: minutesLeft),
style: const TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
] else
Text(
t.discover.play,
style: TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
],
),
),
);
}
}