A cross platform Audiobookshelf client for Android and iOS
Dart
Bring the desktop web UI up to date with main and add server tools
Barnabas0972e0294889
diff --cc lib/providers/_lp_core.dartindex b77a8167,9065681b..3e73ef47--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@@ -2134,8 -2339,21 +2363,21 @@@ mixin _CoreMixin on ChangeNotifier, _St}}- Future<void> _downloadSubscribedEpisodes(String podcastId) async {- if (AppPlatform.isWeb || _api == null || isOffline) return;+ /// Downloads a subscribed show's episodes. [keys] names the exact episodes+ /// (with [meta] carrying their details); without it the absorbing queue is+ /// scanned instead, which is what the catch-up pass does. A queue-less show+ /// must pass [keys] - its episodes never enter the queue, so a scan would+ /// come back empty and silently download nothing.+ ///+ /// Returns false when it bailed before enqueueing anything (offline, or+ /// holding out for WiFi), so a caller that can't rely on the catch-up pass+ /// knows the episodes still need retrying.+ Future<bool> _downloadSubscribedEpisodes(+ String podcastId, {+ List<String>? keys,+ Map<String, Map<String, dynamic>>? meta,+ }) async {- if (_api == null || isOffline) return false;++ if (AppPlatform.isWeb || _api == null || isOffline) return false;final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();if (wifiOnly) {final connectivity = await Connectivity().checkConnectivity();@@@ -2374,8 -2768,10 +2803,11 @@@return seriesId;}+ // Alpha [QueueDL]: every exit from this function used to be silent, so a+ // queue auto-download that never fired looked identical to one that never+ // ran. Each return now names the gate that stopped it. Strip before beta.Future<void> _checkQueueAutoDownloads(String playingKey) async {+ if (AppPlatform.isWeb) return;try {final self = this as LibraryProvider;final planGeneration = ++_queueDownloadPlanGeneration;@@@ -2601,9 -3081,10 +3117,11 @@@}Future<void> _catchUpQueueAutoDownloads() async {+ if (AppPlatform.isWeb) return;final itemId = AudioPlayerService().currentItemId;if (itemId == null) {+ debugPrint(+ '[QueueDL] stop: nothing is playing, so there is no queue position to download from');_queueDownloadPlanGeneration++;return;}diff --cc lib/screens/absorbing_screen.dartindex 833e7545,255aef72..f042a439--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@@ -11,9 -10,8 +11,10 @@@ import '../services/download_service.daimport '../services/queue_download_policy.dart';import '../services/scoped_prefs.dart';import '../widgets/absorb_page_header.dart';--import '../main.dart' show flatNotifier, gradientIntensityNotifier, rootNavigatorKey;++import '../main.dart'++ show flatNotifier, gradientIntensityNotifier, rootNavigatorKey;import '../widgets/absorbing_card.dart';+import '../widgets/card_chapters_sheet.dart';import '../widgets/offline_status_icon.dart';import '../widgets/overlay_toast.dart';import '../widgets/series_books_sheet.dart';@@@ -64,9 -36,9 +65,11 @@@ class AbsorbingScreen extends StatefulWstatic void scrollToFirst() {final state = globalKey.currentState;if (state != null && state._pageController.hasClients) {-- state._pageController.animateToPage(0,-- duration: const Duration(milliseconds: 350),-- curve: Curves.easeOutCubic);++ state._pageController.animateToPage(++ 0,++ duration: const Duration(milliseconds: 350),++ curve: Curves.easeOutCubic,++ );}}@@@ -83,10 -55,10 +86,12 @@@ class _AbsorbingScreenState extends Stafinal _cardKeys = <String, GlobalKey<AbsorbingCardState>>{};GlobalKey<AbsorbingCardState> _cardKey(String absorbingKey) {-- return _cardKeys.putIfAbsent(absorbingKey, () => GlobalKey<AbsorbingCardState>());++ return _cardKeys.putIfAbsent(++ absorbingKey,++ () => GlobalKey<AbsorbingCardState>(),++ );}--final _cast = ChromecastService();String _queueMode = 'off';// Raw per-type modes behind the derived _queueMode. peekUpNext keys off these@@@ -126,9 -98,9 +131,10 @@@String _activePlaylistChipLabel(LibraryProvider lib, AppLocalizations l) {final id = _queuePlaylistId;if (id == null) return l.queueModePlaylist;-- final match = lib.playlists.cast<Map<String, dynamic>>().where(-- (p) => p['id'] == id,-- ).firstOrNull;++ final match = lib.playlists++ .cast<Map<String, dynamic>>()++ .where((p) => p['id'] == id)++ .firstOrNull;final n = match?['name'] as String?;if (n == null || n.isEmpty) return l.queueModePlaylist;return n.length > 24 ? '${n.substring(0, 23)}…' : n;@@@ -190,7 -162,7 +196,8 @@@// walks the queue from the current item forward, so reordering items after// the front changes what's up next without changing the first key.final queueOrder = lib.absorbingBookIds.join(',');-- final stamp = '$_queueMode|$_bookQueueMode|$_podcastQueueMode|$_mergeLibraries'++ final stamp =++ '$_queueMode|$_bookQueueMode|$_podcastQueueMode|$_mergeLibraries''|$_queuePlaylistId|$_queueCollectionName|$currentId|$queueOrder';if (stamp == _upNextComputedFor) return;_upNextComputedFor = stamp;@@@ -250,7 -210,7 +257,8 @@@_lastSeenHasBook = _player.hasBook;_lastSeenIsPlaying = _player.isPlaying;_lastSeenActiveSession = _player.hasActiveSession;-- var shouldRebuild = hasBookChanged || isPlayingChanged || activeSessionChanged;++ var shouldRebuild =++ hasBookChanged || isPlayingChanged || activeSessionChanged;// Detect item or episode change (same show, different episode counts as a change)final itemChanged = _player.currentItemId != _lastPlayingId;@@@ -268,9 -228,9 +276,12 @@@final playingKey = _player.currentEpisodeId != null? '${_player.currentItemId!}-${_player.currentEpisodeId!}': _player.currentItemId!;-- lib.unblockFromAbsorbing(playingKey,++ lib.unblockFromAbsorbing(++ playingKey,episodeTitle: _player.currentEpisodeTitle,-- episodeDuration: _player.currentEpisodeId != null ? _player.totalDuration : null,++ episodeDuration: _player.currentEpisodeId != null++ ? _player.totalDuration++ : null,);// Persist so this item stays at front even if the app is killed_lastFinishedId = playingKey;@@@ -285,7 -245,7 +296,9 @@@// No animation needed — persist the move-to-front immediately.lib.moveAbsorbingToFront(playingKey);}-- WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToActiveCard());++ WidgetsBinding.instance.addPostFrameCallback(++ (_) => _scrollToActiveCard(),++ );} else if (wasPlayingId != null && !_isSyncing) {// Playback stopped — keep this item at the front of the list.// Don't call markFinishedLocally here: actual completion is handled@@@ -315,12 -275,12 +328,15 @@@_lastFinishedId = castKey;ScopedPrefs.setString('absorbing_last_finished', castKey);final currentPage = _pageController.hasClients-- ? (_pageController.page ?? 0).round() : 0;++ ? (_pageController.page ?? 0).round()++ : 0;_suppressReorder = currentPage > 0;if (!_suppressReorder) {lib.moveAbsorbingToFront(castKey);}-- WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToActiveCard());++ WidgetsBinding.instance.addPostFrameCallback(++ (_) => _scrollToActiveCard(),++ );} else if (nowCasting) {_lastCastItemId = _cast.castingItemId;_lastCastEpisodeId = _cast.castingEpisodeId;@@@ -366,23 -326,23 +382,29 @@@// After the animation lands at 0, release suppression so the list properly// reorders with the playing item at index 0._pageController-- .animateToPage(0,-- duration: const Duration(milliseconds: 400),-- curve: Curves.easeInOutCubic)++ .animateToPage(++ 0,++ duration: const Duration(milliseconds: 400),++ curve: Curves.easeInOutCubic,++ ).then((_) {-- if (!mounted) return;-- _suppressReorder = false;-- // Persist the played item at front so subsequent plays-- // maintain the correct order instead of reverting.-- if (playingKey != null) {-- context.read<LibraryProvider>().moveAbsorbingToFront(playingKey);-- }-- setState(() {});-- });++ if (!mounted) return;++ _suppressReorder = false;++ // Persist the played item at front so subsequent plays++ // maintain the correct order instead of reverting.++ if (playingKey != null) {++ context.read<LibraryProvider>().moveAbsorbingToFront(++ playingKey,++ );++ }++ setState(() {});++ });} else {-- _pageController.animateToPage(idx,-- duration: const Duration(milliseconds: 350),-- curve: Curves.easeOutCubic);++ _pageController.animateToPage(++ idx,++ duration: const Duration(milliseconds: 350),++ curve: Curves.easeOutCubic,++ );}} else if (retries > 0) {// Book might not be in the list yet — retry after a rebuild@@@ -423,7 -383,7 +445,6 @@@await lib.refresh();}--/// Derive the absorbing key for an item map: compound "itemId-episodeId" for/// podcast episodes, plain "itemId" for books.String _absorbingKey(Map<String, dynamic> item) {@@@ -443,7 -403,7 +464,11 @@@// Quick lookup of fresh data — only from the in-progress sections.// For podcast episodes, key by compound "itemId-episodeId".-- const allowedSections = {'continue-listening', 'continue-series', 'downloaded-books'};++ const allowedSections = {++ 'continue-listening',++ 'continue-series',++ 'downloaded-books',++ };final sectionLookup = <String, Map<String, dynamic>>{};for (final section in lib.personalizedSections) {final sectionId = section['id'] as String? ?? '';@@@ -467,7 -427,7 +492,10 @@@final items = <Map<String, dynamic>>[];final skippedKeys = <String, String>{};for (final key in lib.absorbingBookIds) {-- if (removes.contains(key)) { skippedKeys[key] = 'removed'; continue; }++ if (removes.contains(key)) {++ skippedKeys[key] = 'removed';++ continue;++ }// Prefer fresh data from current library's sectionsfinal fromSection = sectionLookup[key];if (fromSection != null) {@@@ -480,11 -440,11 +508,15 @@@final itemLibId = cached['libraryId'] as String?;final mediaType = cached['mediaType'] as String?;final isPodItem = mediaType == 'podcast' || key.length > 36;-- if (_mergeLibraries || selectedLibraryId == null ||-- (itemLibId != null ? itemLibId == selectedLibraryId : isPodItem == lib.isPodcastLibrary)) {++ if (_mergeLibraries ||++ selectedLibraryId == null ||++ (itemLibId != null++ ? itemLibId == selectedLibraryId++ : isPodItem == lib.isPodcastLibrary)) {items.add(cached);} else {-- skippedKeys[key] = 'wrong library (item=$itemLibId, selected=$selectedLibraryId)';++ skippedKeys[key] =++ 'wrong library (item=$itemLibId, selected=$selectedLibraryId)';}} else {skippedKeys[key] = 'not in section or cache';@@@ -547,13 -507,13 +579,19 @@@final activeIsPodcast = activeEpId != null;// Only show if the active item matches the current library type (or merge is on)if (_mergeLibraries || activeIsPodcast == isPod) {-- final activeKey = activeEpId != null ? '$activeId-$activeEpId' : activeId;++ final activeKey = activeEpId != null++ ? '$activeId-$activeEpId'++ : activeId;-- final existingIdx = items.indexWhere((b) => _absorbingKey(b) == activeKey);++ final existingIdx = items.indexWhere(++ (b) => _absorbingKey(b) == activeKey,++ );// Only pull the active item to the top while it's actually playing.// When paused, leave the queue order alone so a freshly-queued// "beginning" episode stays first instead of being bumped to 2nd.-- final activePlaying = _player.hasBook ? _player.isPlaying : _cast.isCasting;++ final activePlaying = _player.hasBook++ ? _player.isPlaying++ : _cast.isCasting;if (!_suppressReorder && existingIdx > 0 && activePlaying) {final item = items.removeAt(existingIdx);items.insert(0, item);@@@ -562,10 -522,10 +600,7 @@@final entry = <String, dynamic>{'id': activeId,'media': {-- 'metadata': {-- 'title': activeTitle,-- 'authorName': activeAuthor,-- },++ 'metadata': {'title': activeTitle, 'authorName': activeAuthor},'duration': activeDuration,'chapters': activeChapters,},@@@ -585,14 -545,14 +620,20 @@@// When nothing is playing, keep the last-finished item at the front// Only if it matches the current library type-- if (!_player.hasBook && !_cast.isCasting && _lastFinishedId != null && !removes.contains(_lastFinishedId)) {++ if (!_player.hasBook &&++ !_cast.isCasting &&++ _lastFinishedId != null &&++ !removes.contains(_lastFinishedId)) {// Compound podcast keys are "uuid-uuid" (>36 chars); plain book UUIDs are 36.final finishedIsPodcast = _lastFinishedId!.length > 36;if (_mergeLibraries || finishedIsPodcast == isPod) {-- final finishedIdx = items.indexWhere((b) => _absorbingKey(b) == _lastFinishedId);++ final finishedIdx = items.indexWhere(++ (b) => _absorbingKey(b) == _lastFinishedId,++ );// Don't pull the last-finished item over a brand-new "beginning"// episode that's deliberately sitting at the top.-- final freshOnTop = items.isNotEmpty &&++ final freshOnTop =++ items.isNotEmpty &&_absorbingKey(items[0]) == lib.freshQueuedFrontKey;if (finishedIdx > 0 && !freshOnTop) {final item = items.removeAt(finishedIdx);@@@ -617,25 -577,25 +658,30 @@@final lib = context.watch<LibraryProvider>();final mq = MediaQuery.of(context);final isTablet = mq.size.shortestSide >= 600;-- final isPhoneLandscape = !isTablet && mq.orientation == Orientation.landscape;++ final isPhoneLandscape =++ !isTablet && mq.orientation == Orientation.landscape;// Swap the PageController when orientation changes so we can go nearly// edge-to-edge on phone landscape while keeping the side peek in portrait.if (_lastOrientation != null && _lastOrientation != mq.orientation) {final currentPage = _pageController.hasClients-- ? (_pageController.page ?? _pageController.initialPage.toDouble()).round()++ ? (_pageController.page ?? _pageController.initialPage.toDouble())++ .round(): 0;final oldController = _pageController;_pageController = PageController(initialPage: currentPage,viewportFraction: isPhoneLandscape ? 0.95 : 0.92,);-- WidgetsBinding.instance.addPostFrameCallback((_) => oldController.dispose());++ WidgetsBinding.instance.addPostFrameCallback(++ (_) => oldController.dispose(),++ );}_lastOrientation = mq.orientation;// Reset carousel to first card when library changes-- if (lib.selectedLibraryId != _lastSeenLibraryId && _lastSeenLibraryId != null) {++ if (lib.selectedLibraryId != _lastSeenLibraryId &&++ _lastSeenLibraryId != null) {if (_pageController.hasClients) {_pageController.jumpToPage(0);}@@@ -643,7 -603,7 +689,7 @@@_lastSeenLibraryId = lib.selectedLibraryId;final dl = DownloadService();var books = _getAbsorbingBooks(lib);--++// When offline, only show downloaded books — but always keep the// currently playing/casting item visible so controls remain accessible.final effectiveOffline = lib.isOffline;@@@ -665,7 -625,7 +711,8 @@@}).toList();}-- final showBlockingLoader = lib.isLoading &&++ final showBlockingLoader =++ lib.isLoading &&books.isEmpty &&!_player.hasBook &&!_cast.isCasting &&@@@ -699,580 -694,251 +746,774 @@@),),),- )- else if (!effectiveOffline)- GestureDetector(- onTap: _isSyncing ? null : () async {- setState(() => _isSyncing = true);- await _pullRefresh();- if (mounted) setState(() => _isSyncing = false);- },- child: Container(- padding: const EdgeInsets.all(6),- decoration: BoxDecoration(- color: subtleBg,- shape: BoxShape.circle,- border: Border.all(color: subtleBorder),- ),- child: _isSyncing- ? SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: muted))- : Icon(Icons.refresh_rounded, size: 18, color: muted),- ),),- if (books.isNotEmpty) ...[- const SizedBox(width: 8),- GestureDetector(- onTap: () => _showReorderSheet(context, lib, books),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),- decoration: BoxDecoration(- color: subtleBg,- borderRadius: BorderRadius.circular(20),- border: Border.all(color: subtleBorder),- ),- child: SizedBox(- height: 20,- child: Row(mainAxisSize: MainAxisSize.min, children: [- Icon(Icons.reorder_rounded, size: 18, color: muted),- if (_queueMode != 'off') ...[- const SizedBox(width: 4),- Text(- _queueMode == 'playlist'- ? _activePlaylistChipLabel(lib, l)- : _queueMode == 'collection'- ? _activeCollectionChipLabel(l)- : _queueMode == 'auto_next'- ? (_mergeLibraries ? l.queueModeAuto : lib.isPodcastLibrary ? l.queueModeShowLabel : l.queueModeSeriesLabel)+ ),+ SafeArea(- child: Builder(builder: (context) {- final desktopWorkspace = isDesktopWorkspace(context);- final offlineIcon = OfflineStatusIcon(- onTapWhenOnline: () {- lib.setManualOffline(true);- final dl = DownloadService();- final itemId = _player.currentItemId;- final epId = _player.currentEpisodeId;- final dlKey = epId != null && itemId != null- ? '$itemId-$epId'- : itemId;- if (dlKey == null || !dl.isDownloaded(dlKey)) {- _stopAndRefresh(lib);- }- },- );-- final headerActions = <Widget>[- if (_player.hasBook)- GestureDetector(- onTap: _isSyncing ? null : () => _stopAndRefresh(lib),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),- decoration: BoxDecoration(- color: subtleBg,- borderRadius: BorderRadius.circular(20),- border: Border.all(color: subtleBorder),- ),- child: SizedBox(- height: 20,- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (_isSyncing)- SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: muted))- else- Icon(Icons.stop_rounded, size: 18, color: muted),- const SizedBox(width: 4),- Text(l.absorbingStop, style: TextStyle(color: muted, fontSize: 13, fontWeight: FontWeight.w500)),- ],- ),- ),- ),- )- else if (!effectiveOffline)- GestureDetector(- onTap: _isSyncing ? null : () async {- setState(() => _isSyncing = true);- await _pullRefresh();- if (mounted) setState(() => _isSyncing = false);- },- child: Container(- padding: const EdgeInsets.all(6),- decoration: BoxDecoration(- color: subtleBg,- shape: BoxShape.circle,- border: Border.all(color: subtleBorder),- ),- child: _isSyncing- ? SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: muted))- : Icon(Icons.refresh_rounded, size: 18, color: muted),- ),- ),- if (!desktopWorkspace && books.isNotEmpty) ...[- const SizedBox(width: 8),- GestureDetector(- onTap: () => _showReorderSheet(context, lib, books),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),- decoration: BoxDecoration(- color: subtleBg,- borderRadius: BorderRadius.circular(20),- border: Border.all(color: subtleBorder),- ),- child: SizedBox(- height: 20,- child: Row(mainAxisSize: MainAxisSize.min, children: [- Icon(Icons.reorder_rounded, size: 18, color: muted),- if (_queueMode != 'off') ...[- const SizedBox(width: 4),- Text(- _queueMode == 'playlist'- ? _activePlaylistChipLabel(lib, l)- : _queueMode == 'collection'- ? _activeCollectionChipLabel(l)- : _queueMode == 'auto_next'- ? (_mergeLibraries ? l.queueModeAuto : lib.isPodcastLibrary ? l.queueModeShowLabel : l.queueModeSeriesLabel)- : l.queueModeManual,- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: cs.primary),++ child: Builder(++ builder: (context) {++ final desktopWorkspace = isDesktopWorkspace(context);++ final offlineIcon = OfflineStatusIcon(++ onTapWhenOnline: () {++ lib.setManualOffline(true);++ final dl = DownloadService();++ final itemId = _player.currentItemId;++ final epId = _player.currentEpisodeId;++ final dlKey = epId != null && itemId != null++ ? '$itemId-$epId'++ : itemId;++ if (dlKey == null || !dl.isDownloaded(dlKey)) {++ _stopAndRefresh(lib);++ }++ },++ );++++ final headerActions = <Widget>[++ if (_player.hasBook)++ GestureDetector(++ onTap: _isSyncing ? null : () => _stopAndRefresh(lib),++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 10,++ vertical: 5,+ ),- ],- ]),- ),- ),- ),- ],- ];-- final pageDots = books.length > 1- ? _PageDots(count: books.length, controller: _pageController)- : null;-- // Compact landscape header: one row containing the ABSORB branding,- // offline icon, page dots, and actions. Skips the large "Absorbing"- // title row to give the card more vertical breathing room.- final landscapeHeader = Padding(- padding: const EdgeInsets.fromLTRB(20, 6, 20, 2),- child: Row(- children: [- Text(- l.appTitle,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant,- letterSpacing: 4,- fontWeight: FontWeight.w300,- ),- ),- const SizedBox(width: 8),- offlineIcon,- if (pageDots != null) ...[- const SizedBox(width: 12),- Expanded(child: pageDots),- const SizedBox(width: 12),- ] else- const Spacer(),- ...headerActions,- ],- ),- );-- final portraitHeader = AbsorbPageHeader(- title: Wording.of(context).absorbingTitle,- showBranding: !desktopWorkspace,- padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),- trailing: offlineIcon,- actions: headerActions,- );-- if (desktopWorkspace) {- return Column(- children: [- portraitHeader,- Expanded(- child: showBlockingLoader- ? Center(- child: CircularProgressIndicator(- strokeWidth: 2,- color: cs.onSurface.withValues(alpha: 0.24)))- : LayoutBuilder(builder: (context, constraints) {- if (books.isEmpty) {- _desktopVisibleItemKey = null;- return _emptyState(cs, tt, effectiveOffline, l);- }-- final currentKey = _absorbingKey(books[0]);- _desktopVisibleItemKey = currentKey;- final panelOpen = _desktopPanelOpen ??=- shouldOpenAbsorbingSidePanelByDefault(constraints.maxWidth);- final panelWidth = absorbingQueuePaneWidth(constraints.maxWidth);- final playerLayoutWidth =- absorbingDesktopPlayerLayoutWidth(constraints.maxWidth);- final overlayPanel = shouldOverlayAbsorbingSidePanel(- constraints.maxWidth,- );- final chapterData = _desktopChapterData?.itemKey == currentKey- ? _desktopChapterData- : null;- final playerPane = Expanded(- child: Padding(- padding: const EdgeInsets.fromLTRB(- _kAbsorbingDesktopPlayerHorizontalPadding / 2,- 8,- _kAbsorbingDesktopPlayerHorizontalPadding / 2,- 16,- ),- child: AbsorbingCard(- key: _cardKey(currentKey),- item: books[0],- player: _player,- presentation: AbsorbingCardPresentation.desktop,- spaciousDesktopLayout: playerLayoutWidth >=- kAbsorbingSpaciousDesktopLayoutWidth,- onChapterDataChanged: _handleDesktopChapterData,- ),- ),- );- final panelRail = SizedBox(- width: _kAbsorbingDesktopPanelRailWidth,- child: Align(- alignment: Alignment.topCenter,- child: Padding(- padding: const EdgeInsets.only(top: 8),- child: IconButton(- key: const ValueKey(- 'desktop-absorbing-panel-toggle',- ),- tooltip: panelOpen- ? MaterialLocalizations.of(context)- .closeButtonTooltip- : l.absorbingManageQueue,- onPressed: () => setState(- () => _desktopPanelOpen = !panelOpen,- ),- icon: Icon(- panelOpen- ? Icons.chevron_right_rounded- : Icons.chevron_left_rounded,++ decoration: BoxDecoration(++ color: subtleBg,++ borderRadius: BorderRadius.circular(20),++ border: Border.all(color: subtleBorder),++ ),++ child: SizedBox(++ height: 20,++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ if (_isSyncing)++ SizedBox(++ width: 18,++ height: 18,++ child: CircularProgressIndicator(++ strokeWidth: 1.5,++ color: muted,+ ),++ )++ else++ Icon(++ Icons.stop_rounded,++ size: 18,++ color: muted,++ ),++ const SizedBox(width: 4),++ Text(++ l.absorbingStop,++ style: TextStyle(++ color: muted,++ fontSize: 13,++ fontWeight: FontWeight.w500,+ ),+ ),- ),- );- return TweenAnimationBuilder<double>(- tween: Tween(end: panelOpen ? panelWidth : 0),- duration: const Duration(milliseconds: 220),- curve: Curves.easeOutCubic,- builder: (context, animatedWidth, child) {- final devicePixelRatio =- MediaQuery.devicePixelRatioOf(context);- final visibleWidth =- (animatedWidth * devicePixelRatio).round() /- devicePixelRatio;- final playerRow = Row(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- playerPane,- if (!overlayPanel)- SizedBox(width: visibleWidth),- VerticalDivider(- width:- _kAbsorbingDesktopPanelDividerWidth,- thickness: 1,- color: cs.outlineVariant- .withValues(alpha: 0.45),++ ],++ ),++ ),++ ),++ )++ else if (!effectiveOffline)++ GestureDetector(++ onTap: _isSyncing++ ? null++ : () async {++ setState(() => _isSyncing = true);++ await _pullRefresh();++ if (mounted) setState(() => _isSyncing = false);++ },++ child: Container(++ padding: const EdgeInsets.all(6),++ decoration: BoxDecoration(++ color: subtleBg,++ shape: BoxShape.circle,++ border: Border.all(color: subtleBorder),++ ),++ child: _isSyncing++ ? SizedBox(++ width: 18,++ height: 18,++ child: CircularProgressIndicator(++ strokeWidth: 1.5,++ color: muted,++ ),++ )++ : Icon(++ Icons.refresh_rounded,++ size: 18,++ color: muted,++ ),++ ),++ ),++ if (!desktopWorkspace && books.isNotEmpty) ...[++ const SizedBox(width: 8),++ GestureDetector(++ onTap: () => _showReorderSheet(context, lib, books),++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 8,++ vertical: 5,++ ),++ decoration: BoxDecoration(++ color: subtleBg,++ borderRadius: BorderRadius.circular(20),++ border: Border.all(color: subtleBorder),++ ),++ child: SizedBox(++ height: 20,++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(++ Icons.reorder_rounded,++ size: 18,++ color: muted,++ ),++ if (_queueMode != 'off') ...[++ const SizedBox(width: 4),++ Text(++ _queueMode == 'playlist'++ ? _activePlaylistChipLabel(lib, l)++ : _queueMode == 'collection'++ ? _activeCollectionChipLabel(l)++ : _queueMode == 'auto_next'++ ? (_mergeLibraries++ ? l.queueModeAuto++ : lib.isPodcastLibrary++ ? l.queueModeShowLabel++ : l.queueModeSeriesLabel)+ : l.queueModeManual,- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: cs.primary),++ style: TextStyle(++ fontSize: 10,++ fontWeight: FontWeight.w600,++ color: cs.primary,+ ),- panelRail,- ],- );- return Stack(- fit: StackFit.expand,- children: [- playerRow,- Positioned(- top: 0,- bottom: 0,- right: _kAbsorbingDesktopPanelRailWidth +- _kAbsorbingDesktopPanelDividerWidth,- child: Offstage(- offstage: visibleWidth == 0,- child: SizedBox(- width: visibleWidth,- child: ClipRect(- child: OverflowBox(- minWidth: panelWidth,- maxWidth: panelWidth,- alignment: Alignment.centerRight,- child: child,++ ),++ ],++ ],++ ),+ ),- ],- ]),- ),- ),- ),- ],- ];-- final pageDots = books.length > 1- ? _PageDots(count: books.length, controller: _pageController)- : null;-- // Compact landscape header: one row containing the ABSORB branding,- // offline icon, page dots, and actions. Skips the large "Absorbing"- // title row to give the card more vertical breathing room.- final landscapeHeader = Padding(- padding: const EdgeInsets.fromLTRB(20, 6, 20, 2),- child: Row(- children: [- Text(- l.appTitle,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant,- letterSpacing: 4,- fontWeight: FontWeight.w300,++ ),++ ),++ ],++ ];++++ final pageDots = books.length > 1++ ? _PageDots(++ count: books.length,++ controller: _pageController,++ )++ : null;++++ // Compact landscape header: one row containing the ABSORB branding,++ // offline icon, page dots, and actions. Skips the large "Absorbing"++ // title row to give the card more vertical breathing room.++ final landscapeHeader = Padding(++ padding: const EdgeInsets.fromLTRB(20, 6, 20, 2),++ child: Row(++ children: [++ Text(++ l.appTitle,++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant,++ letterSpacing: 4,++ fontWeight: FontWeight.w300,++ ),++ ),++ const SizedBox(width: 8),++ offlineIcon,++ if (pageDots != null) ...[++ const SizedBox(width: 12),++ Expanded(child: pageDots),++ const SizedBox(width: 12),++ ] else++ const Spacer(),++ ...headerActions,++ ],+ ),- ),- const SizedBox(width: 8),- offlineIcon,- if (pageDots != null) ...[- const SizedBox(width: 12),- Expanded(child: pageDots),- const SizedBox(width: 12),- ] else- const Spacer(),- ...headerActions,- ],- ),- );++ );++++ final portraitHeader = AbsorbPageHeader(++ title: Wording.of(context).absorbingTitle,++ showBranding: !desktopWorkspace,++ padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),++ trailing: offlineIcon,++ actions: headerActions,++ );++++ if (desktopWorkspace) {++ return Column(++ children: [++ portraitHeader,++ Expanded(++ child: showBlockingLoader++ ? Center(++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: cs.onSurface.withValues(alpha: 0.24),++ ),++ )++ : LayoutBuilder(++ builder: (context, constraints) {++ if (books.isEmpty) {++ _desktopVisibleItemKey = null;++ return _emptyState(++ cs,++ tt,++ effectiveOffline,++ l,++ );++ }+- final portraitHeader = AbsorbPageHeader(- title: Wording.of(context).absorbingTitle,- padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),- trailing: offlineIcon,- actions: headerActions,- );++ final currentKey = _absorbingKey(books[0]);++ _desktopVisibleItemKey = currentKey;++ final panelOpen = _desktopPanelOpen ??=++ shouldOpenAbsorbingSidePanelByDefault(++ constraints.maxWidth,++ );++ final panelWidth = absorbingQueuePaneWidth(++ constraints.maxWidth,++ );++ final playerLayoutWidth =++ absorbingDesktopPlayerLayoutWidth(++ constraints.maxWidth,++ );++ final overlayPanel =++ shouldOverlayAbsorbingSidePanel(++ constraints.maxWidth,++ );++ final chapterData =++ _desktopChapterData?.itemKey == currentKey++ ? _desktopChapterData++ : null;++ final playerPane = Expanded(++ child: Padding(++ padding: const EdgeInsets.fromLTRB(++ _kAbsorbingDesktopPlayerHorizontalPadding /++ 2,++ 8,++ _kAbsorbingDesktopPlayerHorizontalPadding /++ 2,++ 16,++ ),++ child: AbsorbingCard(++ key: _cardKey(currentKey),++ item: books[0],++ player: _player,++ presentation:++ AbsorbingCardPresentation.desktop,++ spaciousDesktopLayout:++ playerLayoutWidth >=++ kAbsorbingSpaciousDesktopLayoutWidth,++ onChapterDataChanged:++ _handleDesktopChapterData,++ ),++ ),++ );++ final panelRail = SizedBox(++ width: _kAbsorbingDesktopPanelRailWidth,++ child: Align(++ alignment: Alignment.topCenter,++ child: Padding(++ padding: const EdgeInsets.only(top: 20),++ child: IconButton(++ key: const ValueKey(++ 'desktop-absorbing-panel-toggle',++ ),++ tooltip: panelOpen++ ? MaterialLocalizations.of(++ context,++ ).closeButtonTooltip++ : l.absorbingManageQueue,++ onPressed: () => setState(++ () =>++ _desktopPanelOpen = !panelOpen,++ ),++ icon: Icon(++ panelOpen++ ? Icons.chevron_right_rounded++ : Icons.chevron_left_rounded,+ ),+ ),+ ),+ ),- ),- ],- );- },- child: _buildDesktopSidePanel(- context,- opaque: overlayPanel,- chapterData: chapterData,- queuePanel: _AbsorbingQueuePanel(- embedded: true,- showHeader: false,- keys: books.map(_absorbingKey).toList(),- books: books,- lib: lib,- scrollController: _desktopQueueScrollController,- absorbingKeyFn: _absorbingKey,- queueMode: _queueMode,- isMerged: _mergeLibraries,- isPodcast: lib.isPodcastLibrary,- currentItemId: _currentPlayerKey,- onQueueModeChanged: (mode) =>- _handleQueueModeChanged(lib, mode),++ );++ return TweenAnimationBuilder<double>(++ tween: Tween(++ end: panelOpen ? panelWidth : 0,++ ),++ duration: const Duration(milliseconds: 220),++ curve: Curves.easeOutCubic,++ builder: (context, animatedWidth, child) {++ final devicePixelRatio =++ MediaQuery.devicePixelRatioOf(++ context,++ );++ final visibleWidth =++ (animatedWidth * devicePixelRatio)++ .round() /++ devicePixelRatio;++ final playerRow = Row(++ crossAxisAlignment:++ CrossAxisAlignment.stretch,++ children: [++ playerPane,++ if (!overlayPanel)++ SizedBox(width: visibleWidth),++ const SizedBox(++ width:++ _kAbsorbingDesktopPanelDividerWidth,++ ),++ panelRail,++ ],++ );++ return Stack(++ fit: StackFit.expand,++ children: [++ playerRow,++ Positioned(++ top: 12,++ bottom: 16,++ right:++ _kAbsorbingDesktopPanelRailWidth +++ _kAbsorbingDesktopPanelDividerWidth,++ child: Offstage(++ offstage: visibleWidth == 0,++ child: SizedBox(++ width: visibleWidth,++ child: ClipRect(++ child: OverflowBox(++ minWidth: panelWidth,++ maxWidth: panelWidth,++ alignment:++ Alignment.centerRight,++ child: child,++ ),++ ),++ ),++ ),++ ),++ ],++ );++ },++ child: _buildDesktopSidePanel(++ context,++ opaque: overlayPanel,++ chapterData: chapterData,++ queuePanel: _AbsorbingQueuePanel(++ embedded: true,++ showHeader: false,++ keys: books.map(_absorbingKey).toList(),++ books: books,++ lib: lib,++ scrollController:++ _desktopQueueScrollController,++ absorbingKeyFn: _absorbingKey,++ queueMode: _queueMode,++ isMerged: _mergeLibraries,++ isPodcast: lib.isPodcastLibrary,++ currentItemId: _currentPlayerKey,++ onQueueModeChanged: (mode) =>++ _handleQueueModeChanged(lib, mode),++ ),++ ),++ );++ },+ ),- ),- );- }),- ),- ],- );- }++ ),++ ],++ );++ }-- return Column(-- children: [-- // ── Header ──-- // Phone landscape uses the compact single-row header; everything-- // else (portrait, tablets in any orientation) keeps the full header.-- if (isPhoneLandscape) landscapeHeader else portraitHeader,-- // Hide Up Next when the session is stopped (not merely paused) --- // hasActiveSession stays true while paused but goes false once the-- // engine is stopped, so a stopped session with items still in the-- // queue won't show a confusing "Nothing is up next".-- if (_player.hasActiveSession && _showUpNextLabel && _queueMode != 'off' && books.isNotEmpty)-- Padding(-- padding: const EdgeInsets.fromLTRB(20, 0, 20, 2),-- child: Align(-- alignment: Alignment.centerRight,-- child: Builder(builder: (context) {-- final isDark = Theme.of(context).brightness == Brightness.dark;-- final greenColor = isDark ? Colors.greenAccent[400] : Colors.green.shade700;-- final redColor = isDark ? Colors.redAccent[200] : Colors.red.shade700;-- final hasNext = _upNextLabel != null;-- return Text(-- hasNext ? l.upNext(_upNextLabel!) : l.nothingUpNext,-- style: TextStyle(-- fontSize: 10,-- fontWeight: FontWeight.w600,-- color: hasNext ? greenColor : redColor,++ return Column(++ children: [++ // ── Header ──++ // Phone landscape uses the compact single-row header; everything++ // else (portrait, tablets in any orientation) keeps the full header.++ if (isPhoneLandscape) landscapeHeader else portraitHeader,++ // Hide Up Next when the session is stopped (not merely paused) -++ // hasActiveSession stays true while paused but goes false once the++ // engine is stopped, so a stopped session with items still in the++ // queue won't show a confusing "Nothing is up next".++ if (_player.hasActiveSession &&++ _showUpNextLabel &&++ _queueMode != 'off' &&++ books.isNotEmpty)++ Padding(++ padding: const EdgeInsets.fromLTRB(20, 0, 20, 2),++ child: Align(++ alignment: Alignment.centerRight,++ child: Builder(++ builder: (context) {++ final isDark =++ Theme.of(context).brightness ==++ Brightness.dark;++ final greenColor = isDark++ ? Colors.greenAccent[400]++ : Colors.green.shade700;++ final redColor = isDark++ ? Colors.redAccent[200]++ : Colors.red.shade700;++ final hasNext = _upNextLabel != null;++ return Text(++ hasNext++ ? l.upNext(_upNextLabel!)++ : l.nothingUpNext,++ style: TextStyle(++ fontSize: 10,++ fontWeight: FontWeight.w600,++ color: hasNext ? greenColor : redColor,++ ),++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ );++ },++ ),++ ),),-- maxLines: 1,-- overflow: TextOverflow.ellipsis,-- );-- }),-- ),-- ),-- // ── Page Dots (compact header inlines them in phone landscape) ──-- if (!isPhoneLandscape && pageDots != null)-- Padding(-- padding: const EdgeInsets.only(top: 4, bottom: 2),-- child: pageDots,-- ),-- // ── Cards (refreshable) ──-- Expanded(-- child: showBlockingLoader-- ? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))-- : books.isEmpty-- ? _emptyState(cs, tt, effectiveOffline, l)-- : books.length == 1++ // ── Page Dots (compact header inlines them in phone landscape) ──++ if (!isPhoneLandscape && pageDots != null)++ Padding(++ padding: const EdgeInsets.only(top: 4, bottom: 2),++ child: pageDots,++ ),++ // ── Cards (refreshable) ──++ Expanded(++ child: showBlockingLoader++ ? Center(++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: cs.onSurface.withValues(alpha: 0.24),++ ),++ )++ : books.isEmpty++ ? _emptyState(cs, tt, effectiveOffline, l)++ : books.length == 1? LayoutBuilder(builder: (context, constraints) {final vPad = isPhoneLandscape? 0.0-- : (constraints.maxHeight * 0.01).clamp(2.0, 16.0);++ : (constraints.maxHeight * 0.01).clamp(++ 2.0,++ 16.0,++ );final hPad = isPhoneLandscape ? 0.0 : 4.0;return Padding(-- padding: EdgeInsets.symmetric(horizontal: hPad, vertical: vPad),-- child: RepaintBoundary(child: AbsorbingCard(key: _cardKey(_absorbingKey(books[0])), item: books[0], player: _player)),++ padding: EdgeInsets.symmetric(++ horizontal: hPad,++ vertical: vPad,++ ),++ child: RepaintBoundary(++ child: AbsorbingCard(++ key: _cardKey(_absorbingKey(books[0])),++ item: books[0],++ player: _player,++ ),++ ),);},): PageView.builder(-- controller: _pageController,-- scrollDirection: Axis.horizontal,-- clipBehavior: Clip.none,-- physics: const PageScrollPhysics(parent: ClampingScrollPhysics()),-- itemCount: books.length,-- itemBuilder: (_, i) => LayoutBuilder(-- builder: (context, constraints) {-- final cardWidth = constraints.maxWidth;-- final vPad = isPhoneLandscape-- ? 0.0-- : (constraints.maxHeight * 0.01).clamp(2.0, 16.0);-- final hPad = isPhoneLandscape ? 0.0 : 4.0;-- return AnimatedBuilder(-- animation: _pageController,-- builder: (context, child) {-- double distFromCenter = 0.0;-- double rawDist = 0.0;-- if (_pageController.hasClients && _pageController.positions.length == 1 && _pageController.position.haveDimensions) {-- final page = _pageController.page ?? _pageController.initialPage.toDouble();-- rawDist = page - i; // negative = card is to the right-- distFromCenter = rawDist.abs();-- }-- final double scaleX;-- if (distFromCenter >= 1.0) {-- scaleX = 0.85;-- } else {-- // Use easeOut curve for smoother transition-- final t = Curves.easeOut.transform(1.0 - distFromCenter);-- scaleX = 0.85 + (t * 0.15); // 0.85 → 1.0-- }-- // Calculate how much space the squeeze frees up, then translate toward center-- final squeezedWidth = cardWidth * scaleX;-- final freedSpace = cardWidth - squeezedWidth;-- // Pull card toward center by half the freed space-- final direction = rawDist > 0 ? 1.0 : (rawDist < 0 ? -1.0 : 0.0);-- final translateX = direction * freedSpace * 0.45;---- return Transform(-- alignment: Alignment.center,-- transform: Matrix4.identity()-- ..translate(translateX, 0.0, 0.0)-- ..scale(scaleX, 1.0, 1.0),-- child: Padding(-- padding: EdgeInsets.symmetric(horizontal: hPad, vertical: vPad),-- child: child,++ controller: _pageController,++ scrollDirection: Axis.horizontal,++ clipBehavior: Clip.none,++ physics: const PageScrollPhysics(++ parent: ClampingScrollPhysics(),++ ),++ itemCount: books.length,++ itemBuilder: (_, i) => LayoutBuilder(++ builder: (context, constraints) {++ final cardWidth = constraints.maxWidth;++ final vPad = isPhoneLandscape++ ? 0.0++ : (constraints.maxHeight * 0.01).clamp(++ 2.0,++ 16.0,++ );++ final hPad = isPhoneLandscape ? 0.0 : 4.0;++ return AnimatedBuilder(++ animation: _pageController,++ builder: (context, child) {++ double distFromCenter = 0.0;++ double rawDist = 0.0;++ if (_pageController.hasClients &&++ _pageController.positions.length ==++ 1 &&++ _pageController++ .position++ .haveDimensions) {++ final page =++ _pageController.page ??++ _pageController.initialPage++ .toDouble();++ rawDist =++ page -++ i; // negative = card is to the right++ distFromCenter = rawDist.abs();++ }++ final double scaleX;++ if (distFromCenter >= 1.0) {++ scaleX = 0.85;++ } else {++ // Use easeOut curve for smoother transition++ final t = Curves.easeOut.transform(++ 1.0 - distFromCenter,++ );++ scaleX =++ 0.85 + (t * 0.15); // 0.85 → 1.0++ }++ // Calculate how much space the squeeze frees up, then translate toward center++ final squeezedWidth = cardWidth * scaleX;++ final freedSpace =++ cardWidth - squeezedWidth;++ // Pull card toward center by half the freed space++ final direction = rawDist > 0++ ? 1.0++ : (rawDist < 0 ? -1.0 : 0.0);++ final translateX =++ direction * freedSpace * 0.45;++++ return Transform(++ alignment: Alignment.center,++ transform: Matrix4.identity()++ ..translate(translateX, 0.0, 0.0)++ ..scale(scaleX, 1.0, 1.0),++ child: Padding(++ padding: EdgeInsets.symmetric(++ horizontal: hPad,++ vertical: vPad,++ ),++ child: child,++ ),++ );++ },++ child: RepaintBoundary(++ child: AbsorbingCard(++ key: _cardKey(_absorbingKey(books[i])),++ item: books[i],++ player: _player,++ ),),);},-- child: RepaintBoundary(child: AbsorbingCard(key: _cardKey(_absorbingKey(books[i])), item: books[i], player: _player)),-- );-- },-- ),-- ),++ ),++ ),++ ),++ ],++ );++ },),-- ],-- );- }),- }),- ),+ ),+ ],),);}-- Widget _emptyState(ColorScheme cs, TextTheme tt, bool isOffline, AppLocalizations l) {++ Widget _emptyState(++ ColorScheme cs,++ TextTheme tt,++ bool isOffline,++ AppLocalizations l,++ ) {final lib = context.read<LibraryProvider>();final isPod = lib.isPodcastLibrary;return Center(child: Column(mainAxisSize: MainAxisSize.min,children: [-- Icon(isOffline ? Icons.cloud_off_rounded-- : isPod ? Icons.podcasts_rounded : Icons.headphones_rounded,-- size: 64, color: cs.onSurface.withValues(alpha: 0.15)),++ Icon(++ isOffline++ ? Icons.cloud_off_rounded++ : isPod++ ? Icons.podcasts_rounded++ : Icons.headphones_rounded,++ size: 64,++ color: cs.onSurface.withValues(alpha: 0.15),++ ),const SizedBox(height: 16),-- Text(isOffline-- ? (isPod ? l.absorbingNoDownloadedEpisodes : l.absorbingNoDownloadedBooks)-- : (isPod ? l.absorbingNothingPlayingYet : Wording.of(context).absorbingNothingAbsorbingYet),-- style: tt.titleMedium?.copyWith(color: cs.onSurfaceVariant)),++ Text(++ isOffline++ ? (isPod++ ? l.absorbingNoDownloadedEpisodes++ : l.absorbingNoDownloadedBooks)++ : (isPod++ ? l.absorbingNothingPlayingYet++ : Wording.of(context).absorbingNothingAbsorbingYet),++ style: tt.titleMedium?.copyWith(color: cs.onSurfaceVariant),++ ),const SizedBox(height: 8),-- Text(isOffline-- ? (isPod ? l.absorbingDownloadEpisodesToListen : l.absorbingDownloadBooksToListen)-- : (isPod ? l.absorbingStartEpisodeFromShows : l.absorbingStartBookFromLibrary),-- style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.24))),++ Text(++ isOffline++ ? (isPod++ ? l.absorbingDownloadEpisodesToListen++ : l.absorbingDownloadBooksToListen)++ : (isPod++ ? l.absorbingStartEpisodeFromShows++ : l.absorbingStartBookFromLibrary),++ style: tt.bodySmall?.copyWith(++ color: cs.onSurface.withValues(alpha: 0.24),++ ),++ ),],),);}- void _showReorderSheet(BuildContext context, LibraryProvider lib, List<Map<String, dynamic>> books) {+ Future<void> _handleQueueModeChanged(LibraryProvider lib, String mode) async {+ if (mode == 'playlist') {+ final pid = await PlayerSettings.getQueuePlaylistId();+ if (pid == null) {+ if (mounted) {+ final hint = AppLocalizations.of(context)!.queueModePlaylistHint;+ showOverlayToast(context, hint, icon: Icons.playlist_play_rounded);+ }+ return;+ }+ await PlayerSettings.setQueueModePlaylist(pid);+ unawaited(lib.syncQueueAutoDownloads());+ return;+ }+ if (_mergeLibraries || _queueMode == 'playlist') {+ await PlayerSettings.setBookQueueMode(mode);+ await PlayerSettings.setPodcastQueueMode(mode);+ } else {+ final isPod = _player.currentItemId == null+ ? lib.isPodcastLibrary+ : _player.currentEpisodeId != null;+ if (isPod) {+ await PlayerSettings.setPodcastQueueMode(mode);+ } else {+ await PlayerSettings.setBookQueueMode(mode);+ }+ }+ PlayerSettings.notifySettingsChanged();+ unawaited(lib.syncQueueAutoDownloads());+ }++ String? get _currentPlayerKey => _player.currentEpisodeId != null+ ? '${_player.currentItemId}-${_player.currentEpisodeId}'+ : _player.currentItemId;++ Widget _buildDesktopSidePanel(+ BuildContext context, {+ required bool opaque,+ required AbsorbingChapterData? chapterData,+ required Widget queuePanel,+ }) {+ final cs = Theme.of(context).colorScheme;+ final l = AppLocalizations.of(context)!;+ final chaptersPanel = chapterData == null- ? Center(child: CircularProgressIndicator(- strokeWidth: 2,- color: cs.onSurface.withValues(alpha: 0.24),- ))++ ? Center(++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: cs.onSurface.withValues(alpha: 0.24),++ ),++ )+ : chapterData.chapters.isEmpty- ? Center(child: Padding(- padding: const EdgeInsets.all(24),- child: Text(- chapterData.episodeId == null ? l.noChaptersBook : l.noChaptersPodcast,- textAlign: TextAlign.center,- style: Theme.of(context).textTheme.bodyMedium?.copyWith(- color: cs.onSurfaceVariant,++ ? Center(++ child: Padding(++ padding: const EdgeInsets.all(24),++ child: Text(++ chapterData.episodeId == null++ ? l.noChaptersBook++ : l.noChaptersPodcast,++ textAlign: TextAlign.center,++ style: Theme.of(++ context,++ ).textTheme.bodyMedium?.copyWith(color: cs.onSurfaceVariant),++ ),++ ),++ )++ : CardChaptersList(++ accent: cs.primary,++ chapters: chapterData.chapters,++ totalDuration: chapterData.totalDuration,++ currentPosition: chapterData.currentPosition,++ isPlaybackActive: chapterData.isPlaybackActive,++ isCastingThis: chapterData.isCastingThis,++ displaySpeed: chapterData.displaySpeed,++ player: _player,++ itemId: chapterData.itemId,++ );++++ return Material(++ color: opaque++ ? cs.surface.withValues(alpha: 0.98)++ : cs.surfaceContainerLow.withValues(alpha: 0.88),++ elevation: opaque ? 10 : 2,++ shadowColor: Colors.black.withValues(alpha: 0.35),++ shape: RoundedRectangleBorder(++ borderRadius: BorderRadius.circular(20),++ side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.42)),++ ),++ clipBehavior: Clip.antiAlias,++ child: Column(++ children: [++ Padding(++ padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),++ child: SizedBox(++ width: double.infinity,++ child: SegmentedButton<DesktopAbsorbingPanelTab>(++ key: const ValueKey('desktop-absorbing-panel-tabs'),++ segments: [++ ButtonSegment(++ value: DesktopAbsorbingPanelTab.chapters,++ icon: const Icon(Icons.format_list_numbered_rounded),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(l.chapters, maxLines: 1),++ ),+ ),- ),- ))- : CardChaptersList(- accent: cs.primary,- chapters: chapterData.chapters,- totalDuration: chapterData.totalDuration,- currentPosition: chapterData.currentPosition,- isPlaybackActive: chapterData.isPlaybackActive,- isCastingThis: chapterData.isCastingThis,- displaySpeed: chapterData.displaySpeed,- player: _player,- itemId: chapterData.itemId,- );-- return ColoredBox(- color: opaque ? cs.surface : cs.surface.withValues(alpha: 0.72),- child: Column(children: [- Padding(- padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),- child: SizedBox(- width: double.infinity,- child: SegmentedButton<DesktopAbsorbingPanelTab>(- key: const ValueKey('desktop-absorbing-panel-tabs'),- segments: [- ButtonSegment(- value: DesktopAbsorbingPanelTab.chapters,- icon: const Icon(Icons.format_list_numbered_rounded),- label: FittedBox(- fit: BoxFit.scaleDown,- child: Text(l.chapters, maxLines: 1),++ ButtonSegment(++ value: DesktopAbsorbingPanelTab.queue,++ icon: const Icon(Icons.queue_music_rounded),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(l.absorbingManageQueue, maxLines: 1),++ ),+ ),++ ],++ selected: {_desktopPanelTab},++ showSelectedIcon: false,++ onSelectionChanged: (selection) {++ if (selection.isEmpty) return;++ setState(() => _desktopPanelTab = selection.first);++ },++ ),++ ),++ ),++ Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.45)),++ Expanded(++ child: IndexedStack(++ index: _desktopPanelTab.index,++ children: [++ KeyedSubtree(++ key: const ValueKey('desktop-absorbing-chapters-panel'),++ child: chaptersPanel,+ ),- ButtonSegment(- value: DesktopAbsorbingPanelTab.queue,- icon: const Icon(Icons.queue_music_rounded),- label: FittedBox(- fit: BoxFit.scaleDown,- child: Text(l.absorbingManageQueue, maxLines: 1),- ),++ KeyedSubtree(++ key: const ValueKey('desktop-absorbing-queue-panel'),++ child: queuePanel,+ ),+ ],- selected: {_desktopPanelTab},- showSelectedIcon: false,- onSelectionChanged: (selection) {- if (selection.isEmpty) return;- setState(() => _desktopPanelTab = selection.first);- },+ ),+ ),- ),- Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.45)),- Expanded(- child: IndexedStack(- index: _desktopPanelTab.index,- children: [- KeyedSubtree(- key: const ValueKey('desktop-absorbing-chapters-panel'),- child: chaptersPanel,- ),- KeyedSubtree(- key: const ValueKey('desktop-absorbing-queue-panel'),- child: queuePanel,- ),- ],- ),- ),- ]),++ ],++ ),+ );+ }+- void _showReorderSheet(BuildContext context, LibraryProvider lib, List<Map<String, dynamic>> books) {++ void _showReorderSheet(++ BuildContext context,++ LibraryProvider lib,++ List<Map<String, dynamic>> books,++ ) {final keys = books.map((b) => _absorbingKey(b)).toList();final media = MediaQuery.of(context);-- final needsMoreRoom = media.size.height < 600 ||-- media.textScaler.scale(1) > 1.2;++ final needsMoreRoom =++ media.size.height < 600 || media.textScaler.scale(1) > 1.2;showModalBottomSheet(context: context,isScrollControlled: true,@@@ -1310,49 -1008,49 +1551,61 @@@ class _PageDots extends StatelessWidge@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;-- return LayoutBuilder(builder: (context, constraints) {-- // Active dot is 20 wide, inactive is 6, each has horizontal padding on both sides.-- // Solve for padding: count * (6 + 2*pad) + (20 - 6) <= maxWidth-- // pad = (maxWidth - 14 - count * 6) / (count * 2)-- const double dotSize = 6;-- const double activeDotWidth = 20;-- final maxWidth = constraints.maxWidth;-- final extraActive = activeDotWidth - dotSize;-- final available = maxWidth - extraActive - count * dotSize;-- final hPad = (available / (count * 2)).clamp(1.5, 8.0);---- return ListenableBuilder(-- listenable: controller,-- builder: (_, __) {-- final page = controller.hasClients && controller.positions.length == 1 ? (controller.page ?? 0).round() : 0;-- return Row(-- mainAxisAlignment: MainAxisAlignment.center,-- children: List.generate(count, (i) {-- final active = i == page;-- return GestureDetector(-- behavior: HitTestBehavior.opaque,-- onTap: () => controller.animateToPage(i,-- duration: const Duration(milliseconds: 400),-- curve: Curves.easeOutCubic),-- child: Padding(-- padding: EdgeInsets.symmetric(horizontal: hPad, vertical: 12),-- child: AnimatedContainer(-- duration: const Duration(milliseconds: 300),++ return LayoutBuilder(++ builder: (context, constraints) {++ // Active dot is 20 wide, inactive is 6, each has horizontal padding on both sides.++ // Solve for padding: count * (6 + 2*pad) + (20 - 6) <= maxWidth++ // pad = (maxWidth - 14 - count * 6) / (count * 2)++ const double dotSize = 6;++ const double activeDotWidth = 20;++ final maxWidth = constraints.maxWidth;++ final extraActive = activeDotWidth - dotSize;++ final available = maxWidth - extraActive - count * dotSize;++ final hPad = (available / (count * 2)).clamp(1.5, 8.0);++++ return ListenableBuilder(++ listenable: controller,++ builder: (_, __) {++ final page =++ controller.hasClients && controller.positions.length == 1++ ? (controller.page ?? 0).round()++ : 0;++ return Row(++ mainAxisAlignment: MainAxisAlignment.center,++ children: List.generate(count, (i) {++ final active = i == page;++ return GestureDetector(++ behavior: HitTestBehavior.opaque,++ onTap: () => controller.animateToPage(++ i,++ duration: const Duration(milliseconds: 400),curve: Curves.easeOutCubic,-- width: active ? activeDotWidth : dotSize,-- height: dotSize,-- decoration: BoxDecoration(-- color: active ? cs.onSurface.withValues(alpha: 0.54) : cs.onSurface.withValues(alpha: 0.15),-- borderRadius: BorderRadius.circular(3),++ ),++ child: Padding(++ padding: EdgeInsets.symmetric(++ horizontal: hPad,++ vertical: 12,++ ),++ child: AnimatedContainer(++ duration: const Duration(milliseconds: 300),++ curve: Curves.easeOutCubic,++ width: active ? activeDotWidth : dotSize,++ height: dotSize,++ decoration: BoxDecoration(++ color: active++ ? cs.onSurface.withValues(alpha: 0.54)++ : cs.onSurface.withValues(alpha: 0.15),++ borderRadius: BorderRadius.circular(3),++ ),),),-- ),-- );-- }),-- );-- },-- );-- });++ );++ }),++ );++ },++ );++ },++ );}}@@@ -1406,9 -1097,9 +1659,7 @@@ class _AbsorbingQueuePanelState extendvoid initState() {super.initState();_order = List.from(widget.keys);-- _booksByKey = {-- for (final b in widget.books) widget.absorbingKeyFn(b): b,-- };++ _booksByKey = {for (final b in widget.books) widget.absorbingKeyFn(b): b};_queueMode = widget.queueMode;_currentItemId = widget.currentItemId;_downloads = DownloadService()..addListener(_onDownloadsChanged);@@@ -1435,19 -1126,6 +1686,17 @@@int _rollingDownloadCount = 3;String _podcastAdvanceDir = 'oldest_first';+ @override+ void didUpdateWidget(_AbsorbingQueuePanel oldWidget) {+ super.didUpdateWidget(oldWidget);+ // The embedded panel is long-lived; pick up queue changes from the+ // parent (playback advancing, items added or removed elsewhere).+ if (widget.embedded && !listEquals(widget.keys, oldWidget.keys)) {+ _order = List.from(widget.keys);- _booksByKey = {- for (final b in widget.books) widget.absorbingKeyFn(b): b,- };++ _booksByKey = {for (final b in widget.books) widget.absorbingKeyFn(b): b};+ }+ }+void _onDownloadsChanged() {if (mounted) setState(() {});}@@@ -1458,8 -1136,8 +1707,8 @@@final nextKey = itemId == null? null: episodeId == null-- ? itemId-- : '$itemId-$episodeId';++ ? itemId++ : '$itemId-$episodeId';if (!mounted || nextKey == _currentItemId) return;setState(() {_currentItemId = nextKey;@@@ -1508,7 -1192,7 +1763,8 @@@final count = await PlayerSettings.getRollingDownloadCount();if (!mounted ||queueMode != _queueMode ||-- sourceId != _activeAutoDownloadSourceId) return;++ sourceId != _activeAutoDownloadSourceId)++ return;setState(() {_queueAutoDownload = resolveQueueAutoDownloadEnabled(queueMode: queueMode,@@@ -1525,9 -1226,16 +1798,16 @@@Future<void> _setQueueAutoDownload(bool value) async {final sourceId = _activeAutoDownloadSourceId;setState(() => _queueAutoDownload = value);- if (_queueMode == 'auto_next' && sourceId != null) {+ if (sourceId != null) {if (value) {- await widget.lib.enableRollingDownload(sourceId);+ final kind = _queueMode == 'playlist'+ ? 'playlist'+ : _queueMode == 'collection'- ? 'collection'- : _currentPodcastShowId != null- ? 'podcast'- : 'series';++ ? 'collection'++ : _currentPodcastShowId != null++ ? 'podcast'++ : 'series';+ await widget.lib.enableRollingDownload(sourceId, kind: kind);} else {await widget.lib.disableRollingDownload(sourceId);}@@@ -1616,7 -1324,7 +1896,8 @@@if (data == null) return;final (sid, _) = widget.lib.extractSeries(data);if (sid == null) return;-- final libraryId = data['libraryId'] as String? ?? widget.lib.selectedLibraryId;++ final libraryId =++ data['libraryId'] as String? ?? widget.lib.selectedLibraryId;if (libraryId == null) return;final books = await auth.fetchBooksBySeries(libraryId, sid);if (!mounted ||@@@ -1722,8 -1430,8 +2003,8 @@@final sourceId = mode == 'playlist'? await PlayerSettings.getQueuePlaylistId(): mode == 'collection'-- ? await PlayerSettings.getQueueCollectionId()-- : null;++ ? await PlayerSettings.getQueueCollectionId()++ : null;if (!mounted) return;final modeChanged = mode != _queueMode;final sourceChanged = sourceId != _activeQueueSourceId;@@@ -1755,239 -1463,219 +2036,346 @@@final bottomInset = MediaQuery.of(context).viewPadding.bottom;return Container(- decoration: BoxDecoration(- color: cs.surface,- borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),- ),- child: Column(children: [- // Handle- Center(child: Container(- margin: const EdgeInsets.only(top: 8),- width: 32, height: 4,- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.2),- borderRadius: BorderRadius.circular(2),- ),- )),- // Header- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 8, 4),- child: Row(children: [- Expanded(child: Text(l.absorbingManageQueue,- style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600))),- TextButton(- onPressed: () {- widget.lib.reorderAbsorbing(_order);- Navigator.pop(context);- },- child: Text(l.absorbingDone),+ decoration: widget.embedded+ ? null+ : BoxDecoration(+ color: cs.surface,- borderRadius:- const BorderRadius.vertical(top: Radius.circular(20)),++ borderRadius: const BorderRadius.vertical(++ top: Radius.circular(20),++ ),),- child: Column(children: [- // Handle- if (!widget.embedded)- Center(child: Container(- margin: const EdgeInsets.only(top: 8),- width: 32, height: 4,- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.2),- borderRadius: BorderRadius.circular(2),- ]),- ),- // Queue mode toggle- Padding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),- child: SegmentedButton<String>(- segments: [- ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff, maxLines: 1))),- ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual, maxLines: 1))),- ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 16),- label: FittedBox(fit: BoxFit.scaleDown, child: Text(widget.isMerged ? l.queueModeAuto : _currentIsPodcast ? l.queueModeShowLabel : l.queueModeSeriesLabel, maxLines: 1))),- ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist, maxLines: 1))),- // Collection mode is entered via a collection's Play button, not- // picked here - shown only while active so the selection is valid.- if (_queueMode == 'collection')- ButtonSegment(value: 'collection', icon: const Icon(Icons.collections_bookmark_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeCollection, maxLines: 1))),- ],- selected: {_queueMode},- onSelectionChanged: (v) {- if (v.isNotEmpty) widget.onQueueModeChanged(v.first);- },- style: ButtonStyle(- visualDensity: VisualDensity.compact,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,++ child: Column(++ children: [++ // Handle++ if (!widget.embedded)++ Center(++ child: Container(++ margin: const EdgeInsets.only(top: 8),++ width: 32,++ height: 4,++ decoration: BoxDecoration(++ color: cs.onSurface.withValues(alpha: 0.2),++ borderRadius: BorderRadius.circular(2),++ ),++ ),),- )),- // Header- if (widget.showHeader)- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 8, 4),- child: Row(children: [- Expanded(child: Text(l.absorbingManageQueue,- style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600))),- if (!widget.embedded)- TextButton(- onPressed: () {- widget.lib.reorderAbsorbing(_order);- Navigator.pop(context);- },- child: Text(l.absorbingDone),- ),- ),- if (_queueMode != 'off')- Padding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),- child: Column(children: [- Row(children: [- Expanded(child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(_autoDownloadLabel(l),- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- Text(- _queueAutoDownload- ? l.autoDownloadQueueOnSubtitle(_rollingDownloadCount)- : l.autoDownloadQueueOffSubtitle,- style: tt.bodySmall?.copyWith(- color: cs.onSurfaceVariant, fontSize: 11.5),- ),- ],- )),- if (_queueAutoDownload)- Tooltip(- message: l.keepNext,- child: DropdownButtonHideUnderline(- child: DropdownButton<int>(- value: _rollingDownloadCount,- isDense: true,- items: const [2, 3, 4, 5]- .map((count) => DropdownMenuItem(- value: count,- child: Text('$count'),- ))- .toList(),- onChanged: _queueDownloadSettingsLoaded- ? (value) async {- if (value == null) return;- setState(() => _rollingDownloadCount = value);- await PlayerSettings.setRollingDownloadCount(value);- unawaited(widget.lib.syncQueueAutoDownloads());- }- : null,++ // Header++ if (widget.showHeader)++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 8, 8, 4),++ child: Row(++ children: [++ Expanded(++ child: Text(++ l.absorbingManageQueue,++ style: tt.titleMedium?.copyWith(++ fontWeight: FontWeight.w600,+ ),+ ),+ ),- const SizedBox(width: 4),- Switch(- value: _queueAutoDownload,- onChanged: _queueDownloadSettingsLoaded- ? _setQueueAutoDownload- : null,- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- ]),- ]),- ),- if (_queueMode != 'off')++ if (!widget.embedded)++ TextButton(++ onPressed: () {++ widget.lib.reorderAbsorbing(_order);++ Navigator.pop(context);++ },++ child: Text(l.absorbingDone),++ ),++ ],+ ),- ]),- ),- // Queue mode toggle- Padding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),- child: SegmentedButton<String>(- segments: [- ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff, maxLines: 1))),- ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual, maxLines: 1))),- ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 16),- label: FittedBox(fit: BoxFit.scaleDown, child: Text(widget.isMerged ? l.queueModeAuto : _currentIsPodcast ? l.queueModeShowLabel : l.queueModeSeriesLabel, maxLines: 1))),- ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist, maxLines: 1))),- // Collection mode is entered via a collection's Play button, not- // picked here - shown only while active so the selection is valid.- if (_queueMode == 'collection')- ButtonSegment(value: 'collection', icon: const Icon(Icons.collections_bookmark_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeCollection, maxLines: 1))),- ],- selected: {_queueMode},- onSelectionChanged: (v) {- if (v.isNotEmpty) widget.onQueueModeChanged(v.first);- },- style: ButtonStyle(- visualDensity: VisualDensity.compact,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),- ),- ),- if (widget.embedded && _queueMode == 'manual')++ // Queue mode togglePadding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- Wording.of(context).desktopManualQueueHint,- style: tt.bodySmall?.copyWith(- color: cs.onSurfaceVariant,- height: 1.3,- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),- child: Row(children: [- Expanded(child: Text(l.showUpNextLabel,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant))),- Switch(- value: _showUpNext,- onChanged: (v) {- setState(() => _showUpNext = v);- PlayerSettings.setShowUpNextLabel(v);- },- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,++ padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),++ child: SegmentedButton<String>(++ segments: [++ ButtonSegment(++ value: 'off',++ icon: const Icon(Icons.stop_rounded, size: 16),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(l.queueModeOff, maxLines: 1),++ ),+ ),++ ButtonSegment(++ value: 'manual',++ icon: const Icon(Icons.queue_music_rounded, size: 16),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(l.queueModeManual, maxLines: 1),++ ),++ ),++ ButtonSegment(++ value: 'auto_next',++ icon: const Icon(Icons.skip_next_rounded, size: 16),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(++ widget.isMerged++ ? l.queueModeAuto++ : _currentIsPodcast++ ? l.queueModeShowLabel++ : l.queueModeSeriesLabel,++ maxLines: 1,++ ),++ ),++ ),++ ButtonSegment(++ value: 'playlist',++ icon: const Icon(Icons.playlist_play_rounded, size: 16),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(l.queueModePlaylist, maxLines: 1),++ ),++ ),++ // Collection mode is entered via a collection's Play button, not++ // picked here - shown only while active so the selection is valid.++ if (_queueMode == 'collection')++ ButtonSegment(++ value: 'collection',++ icon: const Icon(++ Icons.collections_bookmark_rounded,++ size: 16,++ ),++ label: FittedBox(++ fit: BoxFit.scaleDown,++ child: Text(l.queueModeCollection, maxLines: 1),++ ),++ ),++ ],++ selected: {_queueMode},++ onSelectionChanged: (v) {++ if (v.isNotEmpty) widget.onQueueModeChanged(v.first);++ },++ style: ButtonStyle(++ visualDensity: VisualDensity.compact,++ tapTargetSize: MaterialTapTargetSize.shrinkWrap,),- ]),+ ),),- if (_queueMode != 'off')- if (_queueMode == 'auto_next' && _currentPodcastShowId != null)-- Padding(-- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),- child: Column(children: [- Row(children: [- Expanded(child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(l.autoDownloadQueue,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- Text(- _queueAutoDownload- ? l.autoDownloadQueueOnSubtitle(_rollingDownloadCount)- : l.autoDownloadQueueOffSubtitle,- style: tt.bodySmall?.copyWith(- color: cs.onSurfaceVariant, fontSize: 11.5),- ),- ],- )),- if (_queueAutoDownload)- Tooltip(- message: l.keepNext,- child: DropdownButtonHideUnderline(- child: DropdownButton<int>(- value: _rollingDownloadCount,- isDense: true,- items: const [2, 3, 4, 5]- .map((count) => DropdownMenuItem(- value: count,- child: Text('$count'),- ))- .toList(),- child: Row(children: [- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(l.reversePlayOrder,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- Text(- _podcastAdvanceDir == 'newest_first'- ? l.episodeListPlaysNewerToOlder- : l.episodeListPlaysOlderToNewer,++ if (widget.embedded && _queueMode == 'manual')++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),++ child: Align(++ alignment: Alignment.centerLeft,++ child: Text(++ Wording.of(context).desktopManualQueueHint,+ style: tt.bodySmall?.copyWith(- color: cs.onSurfaceVariant, fontSize: 11.5),++ color: cs.onSurfaceVariant,++ height: 1.3,++ ),+ ),- ])),- Switch(- value: _podcastAdvanceDir == 'newest_first',- onChanged: (v) async {- final dir = v ? 'newest_first' : 'oldest_first';- setState(() => _podcastAdvanceDir = dir);- await PlayerSettings.setPodcastAdvanceDir(- _currentPodcastShowId!, dir);- unawaited(widget.lib.syncQueueAutoDownloads());- },- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),- ]),- ),- if (_queueMode == 'auto_next' && !_currentIsPodcast && _seriesId != null)- _modeHeaderButton(- cs, tt,- label: l.openSeries,- subtitle: _seriesName,- icon: Icons.collections_bookmark_rounded,- onTap: () {- final auth = context.read<AuthProvider>();- final outer = rootNavigatorKey.currentContext ?? context;- Navigator.pop(context);- showSeriesBooksSheet(- outer,- seriesName: _seriesName ?? '',- seriesId: _seriesId,- books: const [],- serverUrl: auth.serverUrl,- token: auth.token,- libraryId: widget.lib.selectedLibraryId,- );- },- ),- if (_queueMode == 'auto_next' && _currentPodcastShowId != null && _showItem != null)- _modeHeaderButton(- cs, tt,- label: l.allEpisodes,- subtitle: _showName,- icon: Icons.podcasts_rounded,- onTap: () {- final outer = rootNavigatorKey.currentContext ?? context;- Navigator.pop(context);- EpisodeListSheet.show(outer, _showItem!);- },- ),- if (_queueMode == 'playlist' && _playlistId != null)- _modeHeaderButton(- cs, tt,- label: l.openPlaylist,- subtitle: _playlistName,- icon: Icons.playlist_play_rounded,- onTap: () {- final outer = rootNavigatorKey.currentContext ?? context;- Navigator.pop(context);- PlaylistDetailSheet.show(outer, _playlistId!);- },- ),- if (_queueMode == 'collection' && _collectionId != null)- _modeHeaderButton(- cs, tt,- label: l.openCollection,- subtitle: _collectionName,- icon: Icons.collections_bookmark_rounded,- onTap: () {- final outer = rootNavigatorKey.currentContext ?? context;- Navigator.pop(context);- CollectionDetailSheet.show(outer, _collectionId!);- },- ),- Expanded(- child: _buildQueueList(cs, tt, l, bottomInset),- ),- ]),++ ),++ if (_queueMode != 'off')++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),++ child: Column(++ children: [++ Row(++ children: [++ Expanded(++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(++ _autoDownloadLabel(l),++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ Text(++ _queueAutoDownload++ ? l.autoDownloadQueueOnSubtitle(++ _rollingDownloadCount,++ )++ : l.autoDownloadQueueOffSubtitle,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ fontSize: 11.5,++ ),++ ),++ ],++ ),++ ),++ if (_queueAutoDownload)++ Tooltip(++ message: l.keepNext,++ child: DropdownButtonHideUnderline(++ child: DropdownButton<int>(++ value: _rollingDownloadCount,++ isDense: true,++ items: const [2, 3, 4, 5]++ .map(++ (count) => DropdownMenuItem(++ value: count,++ child: Text('$count'),++ ),++ )++ .toList(),++ onChanged: _queueDownloadSettingsLoaded++ ? (value) async {++ if (value == null) return;++ setState(++ () => _rollingDownloadCount = value,++ );++ await PlayerSettings.setRollingDownloadCount(++ value,++ );++ unawaited(++ widget.lib.syncQueueAutoDownloads(),++ );++ }++ : null,++ ),++ ),++ ),++ const SizedBox(width: 4),++ Switch(++ value: _queueAutoDownload,+ onChanged: _queueDownloadSettingsLoaded- ? (value) async {- if (value == null) return;- setState(() => _rollingDownloadCount = value);- await PlayerSettings.setRollingDownloadCount(value);- unawaited(widget.lib.syncQueueAutoDownloads());- }++ ? _setQueueAutoDownload+ : null,++ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),++ ],++ ),++ ],++ ),++ ),++ if (_queueMode != 'off')++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),++ child: Row(++ children: [++ Expanded(++ child: Text(++ l.showUpNextLabel,++ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ),- const SizedBox(width: 4),- Switch(- value: _queueAutoDownload,- onChanged: _queueDownloadSettingsLoaded- ? _setQueueAutoDownload- : null,- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- ]),- ]),- ),- if (_queueMode != 'off')- Padding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),- child: Row(children: [- Expanded(child: Text(l.showUpNextLabel,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant))),- Switch(- value: _showUpNext,- onChanged: (v) {- setState(() => _showUpNext = v);- PlayerSettings.setShowUpNextLabel(v);- },- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,++ Switch(++ value: _showUpNext,++ onChanged: (v) {++ setState(() => _showUpNext = v);++ PlayerSettings.setShowUpNextLabel(v);++ },++ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,++ ),++ ],+ ),- ]),- ),- if (_queueMode == 'auto_next' && _currentPodcastShowId != null)- Padding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),- child: Row(children: [- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(l.reversePlayOrder,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- Text(- _podcastAdvanceDir == 'newest_first'- ? l.episodeListPlaysNewerToOlder- : l.episodeListPlaysOlderToNewer,- style: tt.bodySmall?.copyWith(- color: cs.onSurfaceVariant, fontSize: 11.5),- ),- ])),- Switch(- value: _podcastAdvanceDir == 'newest_first',- onChanged: (v) async {- final dir = v ? 'newest_first' : 'oldest_first';- setState(() => _podcastAdvanceDir = dir);- await PlayerSettings.setPodcastAdvanceDir(- _currentPodcastShowId!, dir);- unawaited(widget.lib.syncQueueAutoDownloads());- },- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,++ ),++ if (_queueMode == 'auto_next' && _currentPodcastShowId != null)++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),++ child: Row(++ children: [++ Expanded(++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(++ l.reversePlayOrder,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ Text(++ _podcastAdvanceDir == 'newest_first'++ ? l.episodeListPlaysNewerToOlder++ : l.episodeListPlaysOlderToNewer,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ fontSize: 11.5,++ ),++ ),++ ],++ ),++ ),++ Switch(++ value: _podcastAdvanceDir == 'newest_first',++ onChanged: (v) async {++ final dir = v ? 'newest_first' : 'oldest_first';++ setState(() => _podcastAdvanceDir = dir);++ await PlayerSettings.setPodcastAdvanceDir(++ _currentPodcastShowId!,++ dir,++ );++ unawaited(widget.lib.syncQueueAutoDownloads());++ },++ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,++ ),++ ],+ ),- ]),- ),- if (_queueMode == 'auto_next' && !_currentIsPodcast && _seriesId != null)- _modeHeaderButton(- cs, tt,- label: l.openSeries,- subtitle: _seriesName,- icon: Icons.collections_bookmark_rounded,- onTap: () {- final auth = context.read<AuthProvider>();- final outer = rootNavigatorKey.currentContext ?? context;- if (!widget.embedded) Navigator.pop(context);- showSeriesBooksSheet(- outer,- seriesName: _seriesName ?? '',- seriesId: _seriesId,- books: const [],- serverUrl: auth.serverUrl,- token: auth.token,- libraryId: widget.lib.selectedLibraryId,- );- },- ),- if (_queueMode == 'auto_next' && _currentPodcastShowId != null && _showItem != null)- _modeHeaderButton(- cs, tt,- label: l.allEpisodes,- subtitle: _showName,- icon: Icons.podcasts_rounded,- onTap: () {- final outer = rootNavigatorKey.currentContext ?? context;- if (!widget.embedded) Navigator.pop(context);- EpisodeListSheet.show(outer, _showItem!);- },- ),- if (_queueMode == 'playlist' && _playlistId != null)- _modeHeaderButton(- cs, tt,- label: l.openPlaylist,- subtitle: _playlistName,- icon: Icons.playlist_play_rounded,- onTap: () {- final outer = rootNavigatorKey.currentContext ?? context;- if (!widget.embedded) Navigator.pop(context);- PlaylistDetailSheet.show(outer, _playlistId!);- },- ),- if (_queueMode == 'collection' && _collectionId != null)- _modeHeaderButton(- cs, tt,- label: l.openCollection,- subtitle: _collectionName,- icon: Icons.collections_bookmark_rounded,- onTap: () {- final outer = rootNavigatorKey.currentContext ?? context;- if (!widget.embedded) Navigator.pop(context);- CollectionDetailSheet.show(outer, _collectionId!);- },- ),- Expanded(- child: _buildQueueList(cs, tt, l, bottomInset),- ),- ]),++ ),++ if (_queueMode == 'auto_next' &&++ !_currentIsPodcast &&++ _seriesId != null)++ _modeHeaderButton(++ cs,++ tt,++ label: l.openSeries,++ subtitle: _seriesName,++ icon: Icons.collections_bookmark_rounded,++ onTap: () {++ final auth = context.read<AuthProvider>();++ final outer = rootNavigatorKey.currentContext ?? context;++ if (!widget.embedded) Navigator.pop(context);++ showSeriesBooksSheet(++ outer,++ seriesName: _seriesName ?? '',++ seriesId: _seriesId,++ books: const [],++ serverUrl: auth.serverUrl,++ token: auth.token,++ libraryId: widget.lib.selectedLibraryId,++ );++ },++ ),++ if (_queueMode == 'auto_next' &&++ _currentPodcastShowId != null &&++ _showItem != null)++ _modeHeaderButton(++ cs,++ tt,++ label: l.allEpisodes,++ subtitle: _showName,++ icon: Icons.podcasts_rounded,++ onTap: () {++ final outer = rootNavigatorKey.currentContext ?? context;++ if (!widget.embedded) Navigator.pop(context);++ EpisodeListSheet.show(outer, _showItem!);++ },++ ),++ if (_queueMode == 'playlist' && _playlistId != null)++ _modeHeaderButton(++ cs,++ tt,++ label: l.openPlaylist,++ subtitle: _playlistName,++ icon: Icons.playlist_play_rounded,++ onTap: () {++ final outer = rootNavigatorKey.currentContext ?? context;++ if (!widget.embedded) Navigator.pop(context);++ PlaylistDetailSheet.show(outer, _playlistId!);++ },++ ),++ if (_queueMode == 'collection' && _collectionId != null)++ _modeHeaderButton(++ cs,++ tt,++ label: l.openCollection,++ subtitle: _collectionName,++ icon: Icons.collections_bookmark_rounded,++ onTap: () {++ final outer = rootNavigatorKey.currentContext ?? context;++ if (!widget.embedded) Navigator.pop(context);++ CollectionDetailSheet.show(outer, _collectionId!);++ },++ ),++ Expanded(child: _buildQueueList(cs, tt, l, bottomInset)),++ ],++ ),);}@@@ -2010,32 -1698,32 +2398,51 @@@color: cs.surfaceContainerHighest.withValues(alpha: 0.5),borderRadius: BorderRadius.circular(12),),-- child: Row(children: [-- Icon(icon, size: 18, color: cs.primary),-- const SizedBox(width: 10),-- Expanded(-- child: Column(-- crossAxisAlignment: CrossAxisAlignment.start,-- mainAxisSize: MainAxisSize.min,-- children: [-- Text(label,-- style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600)),-- if (subtitle != null && subtitle.isNotEmpty)-- Text(subtitle,++ child: Row(++ children: [++ Icon(icon, size: 18, color: cs.primary),++ const SizedBox(width: 10),++ Expanded(++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ mainAxisSize: MainAxisSize.min,++ children: [++ Text(++ label,++ style: tt.bodyMedium?.copyWith(++ fontWeight: FontWeight.w600,++ ),++ ),++ if (subtitle != null && subtitle.isNotEmpty)++ Text(++ subtitle,maxLines: 1,overflow: TextOverflow.ellipsis,-- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- ],++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ ],++ ),),-- ),-- Icon(Icons.chevron_right_rounded, size: 18, color: cs.onSurfaceVariant),-- ]),++ Icon(++ Icons.chevron_right_rounded,++ size: 18,++ color: cs.onSurfaceVariant,++ ),++ ],++ ),),),);}-- Widget _buildQueueList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {++ Widget _buildQueueList(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ double bottomInset,++ ) {if (_queueMode == 'auto_next') {if (_currentPodcastShowId != null) {return _buildShowEpisodesList(cs, tt, l, bottomInset);@@@ -2056,7 -1744,7 +2463,12 @@@return _buildManualList(cs, tt, l, bottomInset);}-- Widget _buildCollectionList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {++ Widget _buildCollectionList(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ double bottomInset,++ ) {final books = _collectionBooks;if (books == null) {return const Center(child: CircularProgressIndicator(strokeWidth: 2));@@@ -2065,8 -1753,8 +2477,10 @@@return Center(child: Padding(padding: const EdgeInsets.all(24),-- child: Text(l.absorbingNothingAbsorbingYet,-- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),++ child: Text(++ l.absorbingNothingAbsorbingYet,++ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),++ ),),);}@@@ -2082,7 -1770,7 +2496,12 @@@);}-- Widget _buildShowEpisodesList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {++ Widget _buildShowEpisodesList(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ double bottomInset,++ ) {final eps = _showEpisodes;if (eps == null) {return const Center(child: CircularProgressIndicator(strokeWidth: 2));@@@ -2091,14 -1779,14 +2510,17 @@@return Center(child: Padding(padding: const EdgeInsets.all(24),-- child: Text(l.absorbingNothingAbsorbingYet,-- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),++ child: Text(++ l.absorbingNothingAbsorbingYet,++ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),++ ),),);}final showId = _currentPodcastShowId;final newestFirst = _podcastAdvanceDir == 'newest_first';-- final sorted = [...eps]..sort((a, b) {++ final sorted = [...eps]++ ..sort((a, b) {final at = (a['publishedAt'] as num?)?.toInt() ?? 0;final bt = (b['publishedAt'] as num?)?.toInt() ?? 0;return newestFirst ? bt.compareTo(at) : at.compareTo(bt);@@@ -2111,7 -1799,7 +2533,9 @@@final ep = sorted[i];final epId = ep['id'] as String? ?? '';return _readOnlyQueueItem(-- cs, tt, l,++ cs,++ tt,++ l,key: '$showId-$epId',book: _showItem ?? const {},index: i,@@@ -2121,7 -1809,7 +2545,12 @@@);}-- Widget _buildSeriesList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {++ Widget _buildSeriesList(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ double bottomInset,++ ) {final books = _seriesBooks;if (books == null) {return const Center(child: CircularProgressIndicator(strokeWidth: 2));@@@ -2130,8 -1818,8 +2559,10 @@@return Center(child: Padding(padding: const EdgeInsets.all(24),-- child: Text(l.absorbingNothingAbsorbingYet,-- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),++ child: Text(++ l.absorbingNothingAbsorbingYet,++ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),++ ),),);}@@@ -2141,6 -1829,6 +2572,7 @@@final (_, seq) = widget.lib.extractSeries(book);return seq ?? double.maxFinite;}++return seqOf(a).compareTo(seqOf(b));});return ListView.builder(@@@ -2155,7 -1843,7 +2587,12 @@@);}-- Widget _buildPlaylistList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {++ Widget _buildPlaylistList(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ double bottomInset,++ ) {final items = _playlistItems;if (items == null) {return const Center(child: CircularProgressIndicator(strokeWidth: 2));@@@ -2164,8 -1852,8 +2601,10 @@@return Center(child: Padding(padding: const EdgeInsets.all(24),-- child: Text(l.playlistAllFinished,-- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),++ child: Text(++ l.playlistAllFinished,++ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),++ ),),);}@@@ -2177,10 -1865,10 +2616,14 @@@final item = items[i];final libraryItemId = item['libraryItemId'] as String? ?? '';final episodeId = item['episodeId'] as String?;-- final key = episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;++ final key = episodeId != null++ ? '$libraryItemId-$episodeId'++ : libraryItemId;final book = item['libraryItem'] as Map<String, dynamic>? ?? const {};return _readOnlyQueueItem(-- cs, tt, l,++ cs,++ tt,++ l,key: key,book: book,index: i,@@@ -2253,11 -1941,11 +2696,13 @@@title: epTitle ?? title,author: title,coverUrl: widget.lib.getCoverUrl(showId),-- totalDuration: (episodeOverride?['duration'] as num?)?.toDouble() ?? 0,++ totalDuration:++ (episodeOverride?['duration'] as num?)?.toDouble() ?? 0,chapters: const [],episodeId: epId,episodeTitle: epTitle,-- libraryId: book['libraryId'] as String? ?? widget.lib.selectedLibraryId,++ libraryId:++ book['libraryId'] as String? ?? widget.lib.selectedLibraryId,);} else {playback = AudioPlayerService().playItem(@@@ -2268,206 -1956,204 +2713,283 @@@coverUrl: widget.lib.getCoverUrl(key),totalDuration: (media['duration'] as num?)?.toDouble() ?? 0,chapters: media['chapters'] as List<dynamic>? ?? const [],-- libraryId: book['libraryId'] as String? ?? widget.lib.selectedLibraryId,++ libraryId:++ book['libraryId'] as String? ?? widget.lib.selectedLibraryId,);}-- unawaited(playback.then((error) async {-- if (error == null) {-- await widget.lib.syncQueueAutoDownloads();-- }-- }));++ unawaited(++ playback.then((error) async {++ if (error == null) {++ await widget.lib.syncQueueAutoDownloads();++ }++ }),++ );},child: Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),decoration: BoxDecoration(color: isPlaying? cs.primaryContainer.withValues(alpha: 0.25)-- : (isFinished ? cs.onSurface.withValues(alpha: 0.03) : Colors.transparent),++ : (isFinished++ ? cs.onSurface.withValues(alpha: 0.03)++ : Colors.transparent),borderRadius: BorderRadius.circular(12),),-- child: Row(children: [-- SizedBox(-- width: 24,-- child: Text('${index + 1}',++ child: Row(++ children: [++ SizedBox(++ width: 24,++ child: Text(++ '${index + 1}',style: tt.labelMedium?.copyWith(-- color: isFinished ? cs.onSurface.withValues(alpha: 0.3) : cs.primary,++ color: isFinished++ ? cs.onSurface.withValues(alpha: 0.3)++ : cs.primary,fontWeight: FontWeight.w700,-- )),-- ),-- if (isFinished)-- Icon(Icons.check_circle_rounded,-- size: 16, color: Colors.green.withValues(alpha: 0.5))-- else-- () {-- final progress = widget.lib.getProgress(key);-- return progress > 0-- ? SizedBox(-- width: 16,-- height: 16,-- child: CircularProgressIndicator(-- value: progress,-- strokeWidth: 2.5,-- backgroundColor: cs.surfaceContainerHighest,-- color: cs.primary,-- ),-- )-- : Icon(Icons.circle_outlined,-- size: 16, color: cs.onSurface.withValues(alpha: 0.2));-- }(),-- const SizedBox(width: 8),-- Expanded(-- child: Column(-- crossAxisAlignment: CrossAxisAlignment.start,-- mainAxisSize: MainAxisSize.min,-- children: [-- Text(epTitle ?? title,++ ),++ ),++ ),++ if (isFinished)++ Icon(++ Icons.check_circle_rounded,++ size: 16,++ color: Colors.green.withValues(alpha: 0.5),++ )++ else++ () {++ final progress = widget.lib.getProgress(key);++ return progress > 0++ ? SizedBox(++ width: 16,++ height: 16,++ child: CircularProgressIndicator(++ value: progress,++ strokeWidth: 2.5,++ backgroundColor: cs.surfaceContainerHighest,++ color: cs.primary,++ ),++ )++ : Icon(++ Icons.circle_outlined,++ size: 16,++ color: cs.onSurface.withValues(alpha: 0.2),++ );++ }(),++ const SizedBox(width: 8),++ Expanded(++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ mainAxisSize: MainAxisSize.min,++ children: [++ Text(++ epTitle ?? title,maxLines: 1,overflow: TextOverflow.ellipsis,style: tt.bodyMedium?.copyWith(color: isFinished? cs.onSurface.withValues(alpha: 0.4): null,-- )),-- if (epTitle != null)-- Text(title,++ ),++ ),++ if (epTitle != null)++ Text(++ title,maxLines: 1,overflow: TextOverflow.ellipsis,-- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant))-- else if (author.isNotEmpty)-- Text(author,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ )++ else if (author.isNotEmpty)++ Text(++ author,maxLines: 1,overflow: TextOverflow.ellipsis,-- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- ],++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ ],++ ),),-- ),-- _downloadStatus(key, cs),-- ]),++ _downloadStatus(key, cs),++ ],++ ),),),);}-- Widget _buildManualList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {++ Widget _buildManualList(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ double bottomInset,++ ) {return ReorderableListView.builder(-- scrollController: widget.scrollController,-- buildDefaultDragHandles: false,-- onReorderStart: (_) => HapticFeedback.mediumImpact(),-- padding: EdgeInsets.only(bottom: bottomInset + 16),-- proxyDecorator: (child, index, animation) {-- return AnimatedBuilder(-- animation: animation,-- builder: (context, child) => Material(-- elevation: 4,-- borderRadius: BorderRadius.circular(12),-- color: cs.surfaceContainer,-- child: child,-- ),-- child: child,-- );-- },-- itemCount: _order.length,-- onReorder: (oldIdx, newIdx) {-- setState(() {-- if (newIdx > oldIdx) newIdx--;-- final item = _order.removeAt(oldIdx);-- _order.insert(newIdx, item);-- });- // The sheet commits on Done; the embedded panel has no Done.- if (widget.embedded) widget.lib.reorderAbsorbing(_order);-- },-- itemBuilder: (context, i) {-- final key = _order[i];-- final book = _booksByKey[key];-- if (book == null) return SizedBox.shrink(key: ValueKey(key));---- final media = book['media'] as Map<String, dynamic>? ?? {};-- final metadata = media['metadata'] as Map<String, dynamic>? ?? {};-- final title = metadata['title'] as String? ?? l.unknown;-- final author = metadata['authorName'] as String? ?? '';-- final re = book['recentEpisode'] as Map<String, dynamic>?;-- final epTitle = re?['title'] as String?;-- final isFinished = widget.lib.isItemFinishedByKey(key);---- return Dismissible(-- key: ValueKey(key),-- direction: DismissDirection.endToStart,-- background: Container(-- alignment: Alignment.centerRight,-- padding: const EdgeInsets.only(right: 24),-- margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),-- decoration: BoxDecoration(-- color: cs.error.withValues(alpha: 0.12),-- borderRadius: BorderRadius.circular(12),-- ),-- child: Icon(Icons.remove_circle_outline_rounded, color: cs.error),-- ),-- onDismissed: (_) {-- final removedKey = _order[i];-- setState(() => _order.removeAt(i));-- widget.lib.removeFromAbsorbing(removedKey);-- widget.lib.reorderAbsorbing(_order);-- },-- child: Padding(-- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),-- child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),-- decoration: BoxDecoration(-- color: isFinished ? cs.onSurface.withValues(alpha: 0.03) : Colors.transparent,-- borderRadius: BorderRadius.circular(12),++ scrollController: widget.scrollController,++ buildDefaultDragHandles: false,++ onReorderStart: (_) => HapticFeedback.mediumImpact(),++ padding: EdgeInsets.only(bottom: bottomInset + 16),++ proxyDecorator: (child, index, animation) {++ return AnimatedBuilder(++ animation: animation,++ builder: (context, child) => Material(++ elevation: 4,++ borderRadius: BorderRadius.circular(12),++ color: cs.surfaceContainer,++ child: child,++ ),++ child: child,++ );++ },++ itemCount: _order.length,++ onReorder: (oldIdx, newIdx) {++ setState(() {++ if (newIdx > oldIdx) newIdx--;++ final item = _order.removeAt(oldIdx);++ _order.insert(newIdx, item);++ });++ // The sheet commits on Done; the embedded panel has no Done.++ if (widget.embedded) widget.lib.reorderAbsorbing(_order);++ },++ itemBuilder: (context, i) {++ final key = _order[i];++ final book = _booksByKey[key];++ if (book == null) return SizedBox.shrink(key: ValueKey(key));++++ final media = book['media'] as Map<String, dynamic>? ?? {};++ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};++ final title = metadata['title'] as String? ?? l.unknown;++ final author = metadata['authorName'] as String? ?? '';++ final re = book['recentEpisode'] as Map<String, dynamic>?;++ final epTitle = re?['title'] as String?;++ final isFinished = widget.lib.isItemFinishedByKey(key);++++ return Dismissible(++ key: ValueKey(key),++ direction: DismissDirection.endToStart,++ background: Container(++ alignment: Alignment.centerRight,++ padding: const EdgeInsets.only(right: 24),++ margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),++ decoration: BoxDecoration(++ color: cs.error.withValues(alpha: 0.12),++ borderRadius: BorderRadius.circular(12),++ ),++ child: Icon(Icons.remove_circle_outline_rounded, color: cs.error),++ ),++ onDismissed: (_) {++ final removedKey = _order[i];++ setState(() => _order.removeAt(i));++ widget.lib.removeFromAbsorbing(removedKey);++ widget.lib.reorderAbsorbing(_order);++ },++ child: Padding(++ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),++ child: Container(++ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),++ decoration: BoxDecoration(++ color: isFinished++ ? cs.onSurface.withValues(alpha: 0.03)++ : Colors.transparent,++ borderRadius: BorderRadius.circular(12),++ ),++ child: Row(++ children: [++ // Queue position number++ SizedBox(++ width: 24,++ child: Text(++ '${i + 1}',++ style: tt.labelMedium?.copyWith(++ color: isFinished++ ? cs.onSurface.withValues(alpha: 0.3)++ : cs.primary,++ fontWeight: FontWeight.w700,++ ),),-- child: Row(children: [-- // Queue position number-- SizedBox(width: 24, child: Text('${i + 1}',-- style: tt.labelMedium?.copyWith(-- color: isFinished ? cs.onSurface.withValues(alpha: 0.3) : cs.primary,-- fontWeight: FontWeight.w700,-- ))),-- // Progress indicator-- if (isFinished)-- Icon(Icons.check_circle_rounded, size: 16, color: Colors.green.withValues(alpha: 0.5))-- else ...[-- () {-- final progress = widget.lib.getProgress(key);-- return progress > 0-- ? SizedBox(width: 16, height: 16,-- child: CircularProgressIndicator(-- value: progress,-- strokeWidth: 2.5,-- backgroundColor: cs.surfaceContainerHighest,-- color: cs.primary,-- ))-- : Icon(Icons.circle_outlined, size: 16, color: cs.onSurface.withValues(alpha: 0.2));-- }(),++ ),++ // Progress indicator++ if (isFinished)++ Icon(++ Icons.check_circle_rounded,++ size: 16,++ color: Colors.green.withValues(alpha: 0.5),++ )++ else ...[++ () {++ final progress = widget.lib.getProgress(key);++ return progress > 0++ ? SizedBox(++ width: 16,++ height: 16,++ child: CircularProgressIndicator(++ value: progress,++ strokeWidth: 2.5,++ backgroundColor: cs.surfaceContainerHighest,++ color: cs.primary,++ ),++ )++ : Icon(++ Icons.circle_outlined,++ size: 16,++ color: cs.onSurface.withValues(alpha: 0.2),++ );++ }(),++ ],++ const SizedBox(width: 8),++ // Title + subtitle++ Expanded(++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ mainAxisSize: MainAxisSize.min,++ children: [++ Text(++ epTitle ?? title,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.bodyMedium?.copyWith(++ color: isFinished++ ? cs.onSurface.withValues(alpha: 0.4)++ : null,++ ),++ ),++ if (epTitle != null)++ Text(++ title,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ if (author.isNotEmpty && epTitle == null)++ Text(++ author,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),],-- const SizedBox(width: 8),-- // Title + subtitle-- Expanded(child: Column(-- crossAxisAlignment: CrossAxisAlignment.start,-- mainAxisSize: MainAxisSize.min,-- children: [-- Text(epTitle ?? title,-- maxLines: 1, overflow: TextOverflow.ellipsis,-- style: tt.bodyMedium?.copyWith(-- color: isFinished ? cs.onSurface.withValues(alpha: 0.4) : null,-- )),-- if (epTitle != null)-- Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,-- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- if (author.isNotEmpty && epTitle == null)-- Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,-- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- ],-- )),-- _downloadStatus(key, cs),-- // Drag handle (long-press to avoid conflict with system home gesture)- _DragHandle(index: i, color: cs.onSurface, immediate: widget.embedded),- _DragHandle(index: i, color: cs.onSurface),-- ]),++ ),),-- ),-- );-- },-- );++ _downloadStatus(key, cs),++ // Drag handle (long-press to avoid conflict with system home gesture)++ _DragHandle(++ index: i,++ color: cs.onSurface,++ immediate: widget.embedded,++ ),++ ],++ ),++ ),++ ),++ );++ },++ );}}@@@ -2476,15 -2162,13 +2998,20 @@@class _DragHandle extends StatefulWidget {final int index;final Color color;- const _DragHandle({required this.index, required this.color});+ // Immediate drag for mouse-driven surfaces; long-press hold on touch.+ final bool immediate;- const _DragHandle({required this.index, required this.color, this.immediate = false});++ const _DragHandle({++ required this.index,++ required this.color,++ this.immediate = false,++ });@overrideState<_DragHandle> createState() => _DragHandleState();}--class _DragHandleState extends State<_DragHandle> with SingleTickerProviderStateMixin {++class _DragHandleState extends State<_DragHandle>++ with SingleTickerProviderStateMixin {late final AnimationController _controller;// Match ReorderableDelayedDragStartListener's default delaystatic const _holdDuration = Duration(milliseconds: 500);@@@ -2517,19 -2201,6 +3044,22 @@@@overrideWidget build(BuildContext context) {+ if (widget.immediate) {+ return ReorderableDragStartListener(+ index: widget.index,+ child: MouseRegion(+ cursor: SystemMouseCursors.grab,+ child: Padding(+ padding: const EdgeInsets.all(6),- child: Icon(Icons.drag_handle_rounded, size: 20,- color: widget.color.withValues(alpha: 0.5)),++ child: Icon(++ Icons.drag_handle_rounded,++ size: 20,++ color: widget.color.withValues(alpha: 0.5),++ ),+ ),+ ),+ );+ }return Listener(onPointerDown: _onDown,onPointerUp: _onUp,@@@ -2544,11 -2215,11 +3074,16 @@@duration: const Duration(milliseconds: 150),padding: const EdgeInsets.all(6),decoration: BoxDecoration(-- color: ready ? widget.color.withValues(alpha: 0.1) : Colors.transparent,++ color: ready++ ? widget.color.withValues(alpha: 0.1)++ : Colors.transparent,borderRadius: BorderRadius.circular(8),),-- child: Icon(Icons.drag_handle_rounded, size: 20,-- color: widget.color.withValues(alpha: ready ? 0.7 : 0.3)),++ child: Icon(++ Icons.drag_handle_rounded,++ size: 20,++ color: widget.color.withValues(alpha: ready ? 0.7 : 0.3),++ ),);},),diff --cc lib/screens/admin_library_edit_screen.dartindex a0fbc3c1,a0fbc3c1..3fa0509d--- a/lib/screens/admin_library_edit_screen.dart+++ b/lib/screens/admin_library_edit_screen.dart@@@ -7,11 -7,11 +7,21 @@@ import '../widgets/absorb_page_header.dimport '../widgets/filesystem_picker_screen.dart';import '../widgets/overlay_toast.dart';++enum _LibraryEditorSection { details, settings, scanner, schedule, tools }++++class _MetadataSource {++ final String id;++ bool enabled;++++ _MetadataSource(this.id, {required this.enabled});++}++/// Create or edit a library. Pass [library] (the GET /api/libraries object) to/// edit; omit it to create. Returns true via Navigator.pop when a change was/// saved so the caller can refresh.class AdminLibraryEditScreen extends StatefulWidget {final Map<String, dynamic>? library;++const AdminLibraryEditScreen({super.key, this.library});@override@@@ -19,34 -19,34 +29,72 @@@}class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {-- // The full ABS library icon set (client store globals.js libraryIcons).static const _icons = [-- 'database', 'audiobookshelf', 'books-1', 'books-2', 'book-1', 'microphone-1',-- 'microphone-3', 'radio', 'podcast', 'rss', 'headphones', 'music', 'file-picture',-- 'rocket', 'power', 'star', 'heart',++ 'database',++ 'audiobookshelf',++ 'books-1',++ 'books-2',++ 'book-1',++ 'microphone-1',++ 'microphone-3',++ 'radio',++ 'podcast',++ 'rss',++ 'headphones',++ 'music',++ 'file-picture',++ 'rocket',++ 'power',++ 'star',++ 'heart',++ ];++++ static const _defaultMetadataPrecedence = [++ 'folderStructure',++ 'audioMetatags',++ 'nfoFile',++ 'txtFiles',++ 'opfFile',++ 'absMetadata',];-- // ABS uses its own icon font; map each name to the nearest Material icon for display.static IconData _absIcon(String name) {switch (name) {-- case 'audiobookshelf': return Icons.library_books_rounded;-- case 'books-1': return Icons.menu_book_rounded;-- case 'books-2': return Icons.auto_stories_rounded;-- case 'book-1': return Icons.book_rounded;-- case 'microphone-1': return Icons.mic_rounded;-- case 'microphone-3': return Icons.mic_external_on_rounded;-- case 'radio': return Icons.radio_rounded;-- case 'podcast': return Icons.podcasts_rounded;-- case 'rss': return Icons.rss_feed_rounded;-- case 'headphones': return Icons.headphones_rounded;-- case 'music': return Icons.music_note_rounded;-- case 'file-picture': return Icons.image_rounded;-- case 'rocket': return Icons.rocket_launch_rounded;-- case 'power': return Icons.power_rounded;-- case 'star': return Icons.star_rounded;-- case 'heart': return Icons.favorite_rounded;++ case 'audiobookshelf':++ return Icons.library_books_rounded;++ case 'books-1':++ return Icons.menu_book_rounded;++ case 'books-2':++ return Icons.auto_stories_rounded;++ case 'book-1':++ return Icons.book_rounded;++ case 'microphone-1':++ return Icons.mic_rounded;++ case 'microphone-3':++ return Icons.mic_external_on_rounded;++ case 'radio':++ return Icons.radio_rounded;++ case 'podcast':++ return Icons.podcasts_rounded;++ case 'rss':++ return Icons.rss_feed_rounded;++ case 'headphones':++ return Icons.headphones_rounded;++ case 'music':++ return Icons.music_note_rounded;++ case 'file-picture':++ return Icons.image_rounded;++ case 'rocket':++ return Icons.rocket_launch_rounded;++ case 'power':++ return Icons.power_rounded;++ case 'star':++ return Icons.star_rounded;++ case 'heart':++ return Icons.favorite_rounded;case 'database':-- default: return Icons.storage_rounded;++ default:++ return Icons.storage_rounded;}}@@@ -56,11 -56,11 +104,10 @@@String _mediaType = 'book';String _provider = 'google';String _icon = 'database';-- // Each folder: existing -> {id, fullPath}; new -> {fullPath}.List<Map<String, dynamic>> _folders = [];List<String> _originalFolderIds = [];++ Map<String, dynamic> _originalSettings = {};-- // settingsnum _coverAspectRatio = 1.0;bool _disableWatcher = false;bool _skipAsin = false;@@@ -72,10 -72,10 +119,30 @@@final _podcastRegion = TextEditingController();final _markPercent = TextEditingController();final _markTime = TextEditingController();++ String _finishedMode = 'time';++final _autoScan = TextEditingController();++ final _sectionScrollController = ScrollController();++ bool _scheduleEnabled = false;++ String _scheduleMode = 'weekly';++ int _scheduleMinute = 0;++ TimeOfDay _scheduleTime = const TimeOfDay(hour: 0, minute: 0);++ int _scheduleWeekday = DateTime.monday;-- List<String> _providers = const ['google', 'audible', 'openlibrary', 'itunes', 'audnexus', 'fantlab'];++ List<_MetadataSource> _metadataSources = [];++ _LibraryEditorSection _selectedSection = _LibraryEditorSection.details;++ List<String> _providers = const [++ 'google',++ 'audible',++ 'openlibrary',++ 'itunes',++ 'audnexus',++ 'fantlab',++ ];bool _saving = false;++ String? _removingMetadataExtension;++++ bool get _interactionLocked => _saving || _removingMetadataExtension != null;@overridevoid initState() {@@@ -88,26 -88,26 +155,56 @@@_icon = (lib['icon'] as String?) ?? 'database';_folders = ((lib['folders'] as List?) ?? []).whereType<Map>()-- .map((f) => {'id': f['id'], 'fullPath': f['fullPath']})++ .map(++ (folder) => <String, dynamic>{++ 'id': folder['id'],++ 'fullPath': folder['fullPath'],++ },++ ).toList();-- _originalFolderIds = _folders.map((f) => f['id'].toString()).toList();-- final s = (lib['settings'] as Map?)?.cast<String, dynamic>() ?? {};-- _coverAspectRatio = (s['coverAspectRatio'] as num?) ?? 1;-- _disableWatcher = s['disableWatcher'] as bool? ?? false;-- _skipAsin = s['skipMatchingMediaWithAsin'] as bool? ?? false;-- _skipIsbn = s['skipMatchingMediaWithIsbn'] as bool? ?? false;-- _hideSingleSeries = s['hideSingleBookSeries'] as bool? ?? false;-- _audiobooksOnly = s['audiobooksOnly'] as bool? ?? false;-- _epubScripted = s['epubsAllowScriptedContent'] as bool? ?? false;-- _laterBooksOnly = s['onlyShowLaterBooksInContinueSeries'] as bool? ?? false;-- _podcastRegion.text = (s['podcastSearchRegion'] as String?) ?? 'us';-- final pct = s['markAsFinishedPercentComplete'];-- _markPercent.text = pct == null ? '' : '$pct';-- _markTime.text = '${s['markAsFinishedTimeRemaining'] ?? 10}';-- _autoScan.text = (s['autoScanCronExpression'] as String?) ?? '';++ _originalFolderIds = _folders++ .map((folder) => folder['id'].toString())++ .toList();++ _originalSettings = Map<String, dynamic>.from(++ (lib['settings'] as Map?)?.cast<String, dynamic>() ?? const {},++ );++++ final settings = _originalSettings;++ _coverAspectRatio = (settings['coverAspectRatio'] as num?) ?? 1;++ _disableWatcher = settings['disableWatcher'] as bool? ?? false;++ _skipAsin = settings['skipMatchingMediaWithAsin'] as bool? ?? false;++ _skipIsbn = settings['skipMatchingMediaWithIsbn'] as bool? ?? false;++ _hideSingleSeries = settings['hideSingleBookSeries'] as bool? ?? false;++ _audiobooksOnly = settings['audiobooksOnly'] as bool? ?? false;++ _epubScripted = settings['epubsAllowScriptedContent'] as bool? ?? false;++ _laterBooksOnly =++ settings['onlyShowLaterBooksInContinueSeries'] as bool? ?? false;++ _podcastRegion.text =++ (settings['podcastSearchRegion'] as String?) ?? 'us';++++ final timeRemaining = settings['markAsFinishedTimeRemaining'];++ final percentComplete = settings['markAsFinishedPercentComplete'];++ if (timeRemaining != null) {++ _finishedMode = 'time';++ _markTime.text = '$timeRemaining';++ _markPercent.text = percentComplete == null ? '90' : '$percentComplete';++ } else if (percentComplete != null) {++ _finishedMode = 'percent';++ _markPercent.text = '$percentComplete';++ _markTime.text = '10';++ } else {++ _markTime.text = '10';++ _markPercent.text = '90';++ }++++ _initializeSchedule(settings['autoScanCronExpression']);++ _initializeMetadataSources(settings['metadataPrecedence']);} else {_markTime.text = '10';++ _markPercent.text = '90';_podcastRegion.text = 'us';++ _initializeSchedule(null);++ _resetMetadataSources();}_loadProviders();}@@@ -119,7 -119,7 +216,136 @@@if (!mounted) return;setState(() {_providers = list;-- if (!_providers.contains(_provider)) _providers = [_provider, ..._providers];++ if (!_providers.contains(_provider)) {++ _providers = [_provider, ..._providers];++ }++ });++ }++++ void _initializeMetadataSources(dynamic rawPrecedence) {++ if (rawPrecedence is! List) {++ _resetMetadataSources();++ return;++ }++ final stored = rawPrecedence.map((value) => value.toString()).toList();++ if (stored.isEmpty) {++ _metadataSources = _defaultMetadataPrecedence.reversed++ .map((id) => _MetadataSource(id, enabled: false))++ .toList();++ return;++ }++++ final seen = <String>{};++ final activeDisplayOrder = stored.reversed++ .where((id) => seen.add(id))++ .map((id) => _MetadataSource(id, enabled: true))++ .toList();++ for (final id in _defaultMetadataPrecedence.reversed) {++ if (seen.add(id)) {++ activeDisplayOrder.add(_MetadataSource(id, enabled: false));++ }++ }++ _metadataSources = activeDisplayOrder;++ }++++ void _resetMetadataSources() {++ _metadataSources = _defaultMetadataPrecedence.reversed++ .map((id) => _MetadataSource(id, enabled: true))++ .toList();++ }++++ void _initializeSchedule(dynamic rawCron) {++ final cron = rawCron?.toString().trim() ?? '';++ _autoScan.text = cron;++ _scheduleEnabled = cron.isNotEmpty;++ if (!_scheduleEnabled) return;++++ final parts = cron.split(RegExp(r'\s+'));++ if (parts.length != 5) {++ _scheduleMode = 'advanced';++ return;++ }++++ final minute = int.tryParse(parts[0]);++ final hour = int.tryParse(parts[1]);++ final dayOfWeek = int.tryParse(parts[4]);++ final validMinute = minute != null && minute >= 0 && minute <= 59;++ final validHour = hour != null && hour >= 0 && hour <= 23;++++ if (validMinute &&++ parts[1] == '*' &&++ parts[2] == '*' &&++ parts[3] == '*' &&++ parts[4] == '*') {++ _scheduleMode = 'hourly';++ _scheduleMinute = minute;++ } else if (validMinute &&++ validHour &&++ parts[2] == '*' &&++ parts[3] == '*' &&++ parts[4] == '*') {++ _scheduleMode = 'daily';++ _scheduleTime = TimeOfDay(hour: hour, minute: minute);++ } else if (validMinute &&++ validHour &&++ parts[2] == '*' &&++ parts[3] == '*' &&++ dayOfWeek != null &&++ dayOfWeek >= 0 &&++ dayOfWeek <= 6) {++ _scheduleMode = 'weekly';++ _scheduleTime = TimeOfDay(hour: hour, minute: minute);++ _scheduleWeekday = dayOfWeek == 0 ? DateTime.sunday : dayOfWeek;++ } else {++ _scheduleMode = 'advanced';++ }++ }++++ void _setScheduleEnabled(bool enabled) {++ setState(() {++ _scheduleEnabled = enabled;++ if (enabled && _autoScan.text.trim().isEmpty) {++ _scheduleMode = 'weekly';++ _scheduleTime = const TimeOfDay(hour: 0, minute: 0);++ _scheduleWeekday = DateTime.monday;++ _rebuildCron();++ }++ });++ }++++ void _setScheduleMode(String mode) {++ setState(() {++ _scheduleMode = mode;++ if (mode != 'advanced') _rebuildCron();++ });++ }++++ void _rebuildCron() {++ switch (_scheduleMode) {++ case 'hourly':++ _autoScan.text = '$_scheduleMinute * * * *';++ case 'daily':++ _autoScan.text = '${_scheduleTime.minute} ${_scheduleTime.hour} * * *';++ case 'weekly':++ final cronDay = _scheduleWeekday == DateTime.sunday++ ? 0++ : _scheduleWeekday;++ _autoScan.text =++ '${_scheduleTime.minute} ${_scheduleTime.hour} * * $cronDay';++ case 'advanced':++ break;++ }++ }++++ Future<void> _pickScheduleTime() async {++ final picked = await showTimePicker(++ context: context,++ initialTime: _scheduleTime,++ );++ if (picked == null || !mounted) return;++ setState(() {++ _scheduleTime = picked;++ _rebuildCron();});}@@@ -130,20 -130,20 +356,30 @@@_markPercent.dispose();_markTime.dispose();_autoScan.dispose();++ _sectionScrollController.dispose();super.dispose();}Map<String, dynamic> _settings() {-- final pctText = _markPercent.text.trim();-- final base = <String, dynamic>{++ final base = Map<String, dynamic>.from(_originalSettings);++ final percentText = _markPercent.text.trim();++ final timeText = _markTime.text.trim();++ base.addAll({'coverAspectRatio': _coverAspectRatio,'disableWatcher': _disableWatcher,-- 'markAsFinishedPercentComplete': pctText.isEmpty ? null : num.tryParse(pctText),-- 'markAsFinishedTimeRemaining': num.tryParse(_markTime.text.trim()) ?? 10,-- 'autoScanCronExpression': _autoScan.text.trim().isEmpty ? null : _autoScan.text.trim(),-- };++ 'markAsFinishedPercentComplete': _finishedMode == 'percent'++ ? num.tryParse(percentText)++ : null,++ 'markAsFinishedTimeRemaining': _finishedMode == 'time'++ ? (num.tryParse(timeText) ?? 10)++ : null,++ 'autoScanCronExpression': _scheduleEnabled ? _autoScan.text.trim() : null,++ });++if (_mediaType == 'podcast') {-- base['podcastSearchRegion'] = _podcastRegion.text.trim().isEmpty ? 'us' : _podcastRegion.text.trim();++ base['podcastSearchRegion'] = _podcastRegion.text.trim().isEmpty++ ? 'us'++ : _podcastRegion.text.trim();} else {base.addAll({'skipMatchingMediaWithAsin': _skipAsin,@@@ -152,6 -152,6 +388,12 @@@'audiobooksOnly': _audiobooksOnly,'epubsAllowScriptedContent': _epubScripted,'onlyShowLaterBooksInContinueSeries': _laterBooksOnly,++ 'metadataPrecedence': _metadataSources++ .where((source) => source.enabled)++ .map((source) => source.id)++ .toList()++ .reversed++ .toList(),});}return base;@@@ -163,43 -163,43 +405,100 @@@MaterialPageRoute(builder: (_) => const FilesystemPickerScreen()),);if (path == null || !mounted) return;-- if (_folders.any((f) => f['fullPath'] == path)) return;-- setState(() => _folders = [..._folders, {'fullPath': path}]);++ if (_folders.any((folder) => folder['fullPath'] == path)) return;++ setState(++ () => _folders = [++ ..._folders,++ {'fullPath': path},++ ],++ );++ }++++ bool _hasValidCron() {++ if (!_scheduleEnabled) return true;++ final cron = _autoScan.text.trim();++ return cron.isNotEmpty && cron.split(RegExp(r'\s+')).length == 5;}Future<void> _save() async {final l = AppLocalizations.of(context)!;if (_name.text.trim().isEmpty) {-- showOverlayToast(context, l.libNameRequired, icon: Icons.error_outline_rounded);++ showOverlayToast(++ context,++ l.libNameRequired,++ icon: Icons.error_outline_rounded,++ );++ _selectSection(_LibraryEditorSection.details);return;}if (_folders.isEmpty) {-- showOverlayToast(context, l.libNoFolders, icon: Icons.error_outline_rounded);++ showOverlayToast(++ context,++ l.libNoFolders,++ icon: Icons.error_outline_rounded,++ );++ _selectSection(_LibraryEditorSection.details);++ return;++ }++ if (!_hasValidCron()) {++ showOverlayToast(++ context,++ 'Enter a five-part cron expression before saving.',++ icon: Icons.error_outline_rounded,++ );++ _selectSection(_LibraryEditorSection.schedule);return;}-- // Warn before removing folders on edit (server cascades item deletion).++ final api = context.read<AuthProvider>().apiService;++ if (api == null) return;++ final cron = _autoScan.text.trim();++ final originalCron =++ _originalSettings['autoScanCronExpression']?.toString().trim() ?? '';++ if (_scheduleEnabled &&++ _scheduleMode == 'advanced' &&++ cron != originalCron) {++ setState(() => _saving = true);++ final cronError = await api.validateCronExpression(cron);++ if (!mounted) return;++ setState(() => _saving = false);++ if (cronError != null) {++ showOverlayToast(context, cronError, icon: Icons.error_outline_rounded);++ _selectSection(_LibraryEditorSection.schedule);++ return;++ }++ }++if (_isEdit) {-- final keptIds = _folders.where((f) => f['id'] != null).map((f) => f['id'].toString()).toSet();-- final removed = _originalFolderIds.where((id) => !keptIds.contains(id)).toList();++ final keptIds = _folders++ .where((folder) => folder['id'] != null)++ .map((folder) => folder['id'].toString())++ .toSet();++ final removed = _originalFolderIds++ .where((id) => !keptIds.contains(id))++ .toList();if (removed.isNotEmpty) {-- final ok = await showDialog<bool>(++ final confirmed = await showDialog<bool>(context: context,-- builder: (ctx) => AlertDialog(++ builder: (dialogContext) => AlertDialog(title: Text(l.libRemoveFoldersTitle),content: Text(l.libRemoveFoldersBody),actions: [-- TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),-- FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.remove)),++ TextButton(++ onPressed: () => Navigator.pop(dialogContext, false),++ child: Text(l.cancel),++ ),++ FilledButton(++ onPressed: () => Navigator.pop(dialogContext, true),++ child: Text(l.remove),++ ),],),);-- if (ok != true) return;++ if (confirmed != true) return;}}-- final api = context.read<AuthProvider>().apiService;-- if (api == null) return;setState(() => _saving = true);final body = <String, dynamic>{@@@ -211,237 -211,237 +510,1040 @@@'settings': _settings(),};-- bool ok;++ bool succeeded;if (_isEdit) {-- ok = await api.updateLibrary(widget.library!['id'].toString(), body);++ succeeded = await api.updateLibrary(++ widget.library!['id'].toString(),++ body,++ );} else {-- // folders on create only need fullPath-- body['folders'] = _folders.map((f) => {'fullPath': f['fullPath']}).toList();-- ok = (await api.createLibrary(body)) != null;++ body['folders'] = _folders++ .map((folder) => {'fullPath': folder['fullPath']})++ .toList();++ succeeded = (await api.createLibrary(body)) != null;}if (!mounted) return;setState(() => _saving = false);-- final msg = _isEdit-- ? (ok ? l.libUpdated : l.libUpdateFailed)-- : (ok ? l.libCreated : l.libCreateFailed);-- showOverlayToast(context, msg,-- icon: ok ? Icons.check_circle_outline_rounded : Icons.error_outline_rounded);-- if (ok) Navigator.pop(context, true);++ final message = _isEdit++ ? (succeeded ? l.libUpdated : l.libUpdateFailed)++ : (succeeded ? l.libCreated : l.libCreateFailed);++ showOverlayToast(++ context,++ message,++ icon: succeeded++ ? Icons.check_circle_outline_rounded++ : Icons.error_outline_rounded,++ );++ if (succeeded) Navigator.pop(context, true);++ }++++ Future<void> _removeMetadataFiles(String extension) async {++ final l = AppLocalizations.of(context)!;++ final filename = 'metadata.$extension';++ final confirmed = await showDialog<bool>(++ context: context,++ builder: (dialogContext) => AlertDialog(++ title: Text('Remove all $filename files?'),++ content: Text(++ 'This permanently removes $filename from every item folder in this library. The media files are not changed.',++ ),++ actions: [++ TextButton(++ onPressed: () => Navigator.pop(dialogContext, false),++ child: Text(l.cancel),++ ),++ FilledButton(++ onPressed: () => Navigator.pop(dialogContext, true),++ child: Text(l.remove),++ ),++ ],++ ),++ );++ if (confirmed != true || !mounted) return;++++ final api = context.read<AuthProvider>().apiService;++ if (api == null) return;++ setState(() => _removingMetadataExtension = extension);++ final result = await api.removeLibraryMetadataFiles(++ widget.library!['id'].toString(),++ extension,++ );++ if (!mounted) return;++ setState(() => _removingMetadataExtension = null);++++ if (result == null) {++ showOverlayToast(++ context,++ 'Could not remove $filename files.',++ icon: Icons.error_outline_rounded,++ );++ } else if (result.found == 0) {++ showOverlayToast(++ context,++ 'No $filename files were found.',++ icon: Icons.info_outline_rounded,++ );++ } else if (result.removed == 0) {++ showOverlayToast(++ context,++ '${result.found} $filename files were found, but none could be removed.',++ icon: Icons.error_outline_rounded,++ );++ } else {++ showOverlayToast(++ context,++ 'Removed ${result.removed} of ${result.found} $filename files.',++ icon: Icons.check_circle_outline_rounded,++ );++ }++ }++++ List<_LibraryEditorSection> get _availableSections => [++ _LibraryEditorSection.details,++ _LibraryEditorSection.settings,++ if (_mediaType == 'book') _LibraryEditorSection.scanner,++ _LibraryEditorSection.schedule,++ if (_isEdit) _LibraryEditorSection.tools,++ ];++++ String _sectionLabel(_LibraryEditorSection section, AppLocalizations l) {++ return switch (section) {++ _LibraryEditorSection.details => l.details,++ _LibraryEditorSection.settings => l.settingsTitle,++ _LibraryEditorSection.scanner => l.srvScannerSection,++ _LibraryEditorSection.schedule => 'Schedule',++ _LibraryEditorSection.tools => 'Tools',++ };++ }++++ IconData _sectionIcon(_LibraryEditorSection section) {++ return switch (section) {++ _LibraryEditorSection.details => Icons.info_outline_rounded,++ _LibraryEditorSection.settings => Icons.tune_rounded,++ _LibraryEditorSection.scanner => Icons.document_scanner_outlined,++ _LibraryEditorSection.schedule => Icons.schedule_rounded,++ _LibraryEditorSection.tools => Icons.build_outlined,++ };++ }++++ void _selectSection(_LibraryEditorSection section) {++ if (_interactionLocked) return;++ setState(() => _selectedSection = section);++ WidgetsBinding.instance.addPostFrameCallback((_) {++ if (!mounted || !_sectionScrollController.hasClients) return;++ _sectionScrollController.jumpTo(0);++ });}@overrideWidget build(BuildContext context) {-- final cs = Theme.of(context).colorScheme;-- final tt = Theme.of(context).textTheme;++ final colors = Theme.of(context).colorScheme;final l = AppLocalizations.of(context)!;-- final isPodcast = _mediaType == 'podcast';return Scaffold(backgroundColor: Theme.of(context).scaffoldBackgroundColor,body: SafeArea(-- child: Column(children: [-- Padding(-- padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),-- child: Row(children: [-- Expanded(child: AbsorbPageHeader(-- title: _isEdit ? l.libEditTitle : l.libNewTitle, padding: EdgeInsets.zero)),-- IconButton(-- icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),-- onPressed: () => Navigator.pop(context),-- ),-- ]),-- ),-- const SizedBox(height: 12),-- Expanded(-- child: ListView(-- padding: const EdgeInsets.fromLTRB(16, 0, 16, 100),-- children: [-- TextField(controller: _name,-- decoration: InputDecoration(labelText: l.libName)),-- const SizedBox(height: 16),---- // Media type — fixed once a library has items.-- Text(l.libMediaType, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- const SizedBox(height: 6),-- if (_isEdit)-- Chip(label: Text(isPodcast ? l.libMediaPodcast : l.libMediaBook))-- else-- SegmentedButton<String>(-- segments: [-- ButtonSegment(value: 'book', label: Text(l.libMediaBook), icon: const Icon(Icons.menu_book_rounded)),-- ButtonSegment(value: 'podcast', label: Text(l.libMediaPodcast), icon: const Icon(Icons.podcasts_rounded)),-- ],-- selected: {_mediaType},-- onSelectionChanged: (s) => setState(() => _mediaType = s.first),++ child: Column(++ children: [++ Padding(++ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),++ child: Row(++ children: [++ Expanded(++ child: AbsorbPageHeader(++ title: _isEdit ? l.libEditTitle : l.libNewTitle,++ padding: EdgeInsets.zero,++ ),),-- const SizedBox(height: 16),---- Row(children: [-- Expanded(child: _labeledDropdown(cs, tt, l.libProvider, _provider, _providers,-- (v) => setState(() => _provider = v))),-- const SizedBox(width: 12),-- Expanded(child: _iconDropdown(cs, tt, _icon,-- _icons.contains(_icon) ? _icons : [_icon, ..._icons],-- (v) => setState(() => _icon = v))),-- ]),-- const SizedBox(height: 20),---- // ── Folders ──-- Text(l.libFolders, style: tt.labelLarge?.copyWith(-- color: cs.onSurfaceVariant.withValues(alpha: 0.7), fontWeight: FontWeight.w600)),-- const SizedBox(height: 8),-- Container(-- decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16)),-- padding: const EdgeInsets.symmetric(vertical: 4),-- child: Column(children: [-- if (_folders.isEmpty)-- Padding(-- padding: const EdgeInsets.all(20),-- child: Text(l.libNoFolders,-- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),-- ),-- ..._folders.map((f) => ListTile(-- dense: true,-- leading: Icon(Icons.folder_rounded, color: cs.primary.withValues(alpha: 0.8)),-- title: Text(f['fullPath']?.toString() ?? '', maxLines: 2, overflow: TextOverflow.ellipsis),-- trailing: IconButton(-- icon: Icon(Icons.close_rounded, size: 18, color: cs.onSurfaceVariant),-- onPressed: () => setState(() => _folders = _folders.where((x) => x != f).toList()),-- ),-- )),-- TextButton.icon(-- onPressed: _addFolder,-- icon: const Icon(Icons.add_rounded),-- label: Text(l.libAddFolder),++ IconButton(++ icon: Icon(++ Icons.close_rounded,++ color: colors.onSurfaceVariant,),-- ]),-- ),-- const SizedBox(height: 16),---- // ── Advanced ──-- Theme(-- data: Theme.of(context).copyWith(dividerColor: Colors.transparent),-- child: ExpansionTile(-- tilePadding: EdgeInsets.zero,-- childrenPadding: EdgeInsets.zero,-- title: Text(l.libAdvanced, style: tt.titleSmall),-- children: [-- _coverShape(cs, tt, l),-- _switch(tt, l.libDisableWatcher, _disableWatcher, (v) => setState(() => _disableWatcher = v)),-- if (!isPodcast) ...[-- _switch(tt, l.libSkipAsin, _skipAsin, (v) => setState(() => _skipAsin = v)),-- _switch(tt, l.libSkipIsbn, _skipIsbn, (v) => setState(() => _skipIsbn = v)),-- _switch(tt, l.libHideSingleSeries, _hideSingleSeries, (v) => setState(() => _hideSingleSeries = v)),-- _switch(tt, l.libAudiobooksOnly, _audiobooksOnly, (v) => setState(() => _audiobooksOnly = v)),-- _switch(tt, l.libEpubScripted, _epubScripted, (v) => setState(() => _epubScripted = v)),-- _switch(tt, l.libLaterBooksOnly, _laterBooksOnly, (v) => setState(() => _laterBooksOnly = v)),-- ],-- if (isPodcast) ...[-- const SizedBox(height: 8),-- TextField(controller: _podcastRegion,-- decoration: InputDecoration(labelText: l.libPodcastRegion, hintText: 'us')),++ onPressed: _interactionLocked++ ? null++ : () => Navigator.pop(context),++ ),++ ],++ ),++ ),++ const SizedBox(height: 12),++ Expanded(++ child: LayoutBuilder(++ builder: (context, constraints) {++ final desktop = constraints.maxWidth >= 760;++ if (desktop) {++ return Row(++ crossAxisAlignment: CrossAxisAlignment.stretch,++ children: [++ SizedBox(width: 220, child: _desktopNavigation(l)),++ VerticalDivider(++ width: 1,++ color: colors.outlineVariant.withValues(alpha: 0.5),++ ),++ Expanded(child: _sectionScrollView()),],-- const SizedBox(height: 12),-- Row(children: [-- Expanded(child: TextField(-- controller: _markPercent,-- keyboardType: TextInputType.number,-- decoration: InputDecoration(labelText: l.libMarkPercent),-- )),-- const SizedBox(width: 12),-- Expanded(child: TextField(-- controller: _markTime,-- keyboardType: TextInputType.number,-- decoration: InputDecoration(labelText: l.libMarkTime),-- )),-- ]),-- const SizedBox(height: 12),-- TextField(controller: _autoScan,-- decoration: InputDecoration(labelText: l.libAutoScan, hintText: '0 0 * * *')),++ );++ }++ return Column(++ children: [++ _mobileNavigation(l),const SizedBox(height: 8),++ Expanded(child: _sectionScrollView()),],++ );++ },++ ),++ ),++ if (_selectedSection != _LibraryEditorSection.tools)++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),++ child: Align(++ alignment: Alignment.centerRight,++ child: ConstrainedBox(++ constraints: const BoxConstraints(maxWidth: 320),++ child: SizedBox(++ width: double.infinity,++ child: FilledButton.icon(++ onPressed: _interactionLocked ? null : _save,++ icon: _saving++ ? SizedBox(++ width: 14,++ height: 14,++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: colors.onPrimary,++ ),++ )++ : const Icon(Icons.save_rounded, size: 18),++ label: Text(_isEdit ? l.libUpdate : l.libCreate),++ ),++ ),),),-- const SizedBox(height: 16),-- SizedBox(-- width: double.infinity,-- child: FilledButton.icon(-- onPressed: _saving ? null : _save,-- icon: _saving-- ? SizedBox(width: 14, height: 14,-- child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))-- : const Icon(Icons.save_rounded, size: 18),-- label: Text(_isEdit ? l.libUpdate : l.libCreate),-- ),-- ),-- ],++ ),++ ],++ ),++ ),++ );++ }++++ Widget _desktopNavigation(AppLocalizations l) {++ final colors = Theme.of(context).colorScheme;++ return ListView(++ padding: const EdgeInsets.fromLTRB(12, 4, 12, 16),++ children: [++ for (final section in _availableSections)++ Padding(++ padding: const EdgeInsets.only(bottom: 4),++ child: ListTile(++ shape: RoundedRectangleBorder(++ borderRadius: BorderRadius.circular(12),++ ),++ selected: _selectedSection == section,++ selectedTileColor: colors.secondaryContainer,++ leading: Icon(_sectionIcon(section), size: 20),++ title: Text(_sectionLabel(section, l)),++ onTap: _interactionLocked ? null : () => _selectSection(section),),),-- ]),++ ],++ );++ }++++ Widget _mobileNavigation(AppLocalizations l) {++ return SingleChildScrollView(++ scrollDirection: Axis.horizontal,++ padding: const EdgeInsets.symmetric(horizontal: 16),++ child: Row(++ children: [++ for (final section in _availableSections)++ Padding(++ padding: const EdgeInsets.only(right: 8),++ child: ChoiceChip(++ avatar: Icon(_sectionIcon(section), size: 17),++ label: Text(_sectionLabel(section, l)),++ selected: _selectedSection == section,++ onSelected: _interactionLocked++ ? null++ : (_) => _selectSection(section),++ ),++ ),++ ],),);}-- Widget _coverShape(ColorScheme cs, TextTheme tt, AppLocalizations l) => Padding(-- padding: const EdgeInsets.symmetric(vertical: 8),-- child: Row(children: [-- Expanded(child: Text(l.libCoverShape, style: tt.bodyMedium)),-- // ABS BookCoverAspectRatio enum: SQUARE = 1, STANDARD = 0.-- SegmentedButton<num>(++ Widget _sectionScrollView() {++ return ListView(++ controller: _sectionScrollController,++ padding: const EdgeInsets.fromLTRB(16, 4, 16, 32),++ children: [++ Align(++ alignment: Alignment.topCenter,++ child: ConstrainedBox(++ constraints: const BoxConstraints(maxWidth: 900),++ child: SizedBox(width: double.infinity, child: _sectionContent()),++ ),++ ),++ ],++ );++ }++++ Widget _sectionContent() {++ return switch (_selectedSection) {++ _LibraryEditorSection.details => _detailsSection(),++ _LibraryEditorSection.settings => _settingsSection(),++ _LibraryEditorSection.scanner =>++ _mediaType == 'book' ? _scannerSection() : _settingsSection(),++ _LibraryEditorSection.schedule => _scheduleSection(),++ _LibraryEditorSection.tools =>++ _isEdit ? _toolsSection() : _detailsSection(),++ };++ }++++ Widget _sectionHeading(String title, String description) {++ final textTheme = Theme.of(context).textTheme;++ final colors = Theme.of(context).colorScheme;++ return Padding(++ padding: const EdgeInsets.only(bottom: 20),++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(title, style: textTheme.headlineSmall),++ const SizedBox(height: 4),++ Text(++ description,++ style: textTheme.bodyMedium?.copyWith(++ color: colors.onSurfaceVariant,++ ),++ ),++ ],++ ),++ );++ }++++ Widget _detailsSection() {++ final colors = Theme.of(context).colorScheme;++ final textTheme = Theme.of(context).textTheme;++ final l = AppLocalizations.of(context)!;++ final isPodcast = _mediaType == 'podcast';++ return Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ _sectionHeading(++ l.details,++ 'Set the library name, media type, provider, icon, and folders.',++ ),++ TextField(++ controller: _name,++ decoration: InputDecoration(labelText: l.libName),++ ),++ const SizedBox(height: 16),++ Text(++ l.libMediaType,++ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),++ ),++ const SizedBox(height: 6),++ if (_isEdit)++ Chip(label: Text(isPodcast ? l.libMediaPodcast : l.libMediaBook))++ else++ SegmentedButton<String>(segments: [-- ButtonSegment(value: 1, label: Text(l.libCoverSquare)),-- ButtonSegment(value: 0, label: Text(l.libCoverStandard)),++ ButtonSegment(++ value: 'book',++ label: Text(l.libMediaBook),++ icon: const Icon(Icons.menu_book_rounded),++ ),++ ButtonSegment(++ value: 'podcast',++ label: Text(l.libMediaPodcast),++ icon: const Icon(Icons.podcasts_rounded),++ ),],-- selected: {_coverAspectRatio == 0 ? 0 : 1},-- onSelectionChanged: (s) => setState(() => _coverAspectRatio = s.first),++ selected: {_mediaType},++ onSelectionChanged: (selection) {++ setState(() {++ _mediaType = selection.first;++ if (_mediaType == 'podcast' &&++ _selectedSection == _LibraryEditorSection.scanner) {++ _selectedSection = _LibraryEditorSection.settings;++ }++ });++ },),-- ]),-- );---- Widget _switch(TextTheme tt, String label, bool value, ValueChanged<bool> onChanged) =>-- SwitchListTile(-- contentPadding: EdgeInsets.zero,-- title: Text(label, style: tt.bodyMedium),-- value: value,-- onChanged: onChanged,-- );++ const SizedBox(height: 16),++ LayoutBuilder(++ builder: (context, constraints) {++ final stack = constraints.maxWidth < 520;++ final provider = _labeledDropdown(++ colors,++ textTheme,++ l.libProvider,++ _provider,++ _providers,++ (value) => setState(() => _provider = value),++ );++ final icon = _iconDropdown(++ colors,++ textTheme,++ _icon,++ _icons.contains(_icon) ? _icons : [_icon, ..._icons],++ (value) => setState(() => _icon = value),++ );++ if (stack) {++ return Column(++ children: [provider, const SizedBox(height: 12), icon],++ );++ }++ return Row(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Expanded(child: provider),++ const SizedBox(width: 16),++ Expanded(child: icon),++ ],++ );++ },++ ),++ const SizedBox(height: 24),++ Text(++ l.libFolders,++ style: textTheme.labelLarge?.copyWith(++ color: colors.onSurfaceVariant.withValues(alpha: 0.7),++ fontWeight: FontWeight.w600,++ ),++ ),++ const SizedBox(height: 8),++ Container(++ decoration: BoxDecoration(++ color: colors.surfaceContainerHigh,++ borderRadius: BorderRadius.circular(16),++ ),++ padding: const EdgeInsets.symmetric(vertical: 4),++ child: Column(++ children: [++ if (_folders.isEmpty)++ Padding(++ padding: const EdgeInsets.all(20),++ child: Text(++ l.libNoFolders,++ style: textTheme.bodyMedium?.copyWith(++ color: colors.onSurfaceVariant.withValues(alpha: 0.6),++ ),++ ),++ ),++ ..._folders.asMap().entries.map(++ (entry) => ListTile(++ dense: true,++ leading: Icon(++ Icons.folder_rounded,++ color: colors.primary.withValues(alpha: 0.8),++ ),++ title: Text(++ entry.value['fullPath']?.toString() ?? '',++ maxLines: 2,++ overflow: TextOverflow.ellipsis,++ ),++ trailing: IconButton(++ icon: Icon(++ Icons.close_rounded,++ size: 18,++ color: colors.onSurfaceVariant,++ ),++ onPressed: () => setState(() {++ _folders = [..._folders]..removeAt(entry.key);++ }),++ ),++ ),++ ),++ TextButton.icon(++ onPressed: _addFolder,++ icon: const Icon(Icons.add_rounded),++ label: Text(l.libAddFolder),++ ),++ ],++ ),++ ),++ ],++ );++ }-- Widget _iconDropdown(ColorScheme cs, TextTheme tt, String value,-- List<String> options, ValueChanged<String> onChanged) =>-- Column(crossAxisAlignment: CrossAxisAlignment.start, children: [-- Text(AppLocalizations.of(context)!.libIcon, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- DropdownButton<String>(-- value: options.contains(value) ? value : options.first,-- isExpanded: true,-- borderRadius: BorderRadius.circular(12),-- items: options-- .map((o) => DropdownMenuItem(-- value: o,-- child: Row(children: [-- Icon(_absIcon(o), size: 18, color: cs.onSurfaceVariant),-- const SizedBox(width: 10),-- Flexible(child: Text(o, overflow: TextOverflow.ellipsis)),-- ]),-- ))-- .toList(),-- onChanged: (v) {-- if (v != null) onChanged(v);++ Widget _settingsSection() {++ final textTheme = Theme.of(context).textTheme;++ final l = AppLocalizations.of(context)!;++ final isPodcast = _mediaType == 'podcast';++ final watcherDisabledGlobally =++ context++ .watch<AuthProvider>()++ .serverSettings?['scannerDisableWatcher'] ==++ true;++ return Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ _sectionHeading(++ l.settingsTitle,++ 'Control cover display, matching, completion, and library behavior.',++ ),++ _coverShape(textTheme, l),++ _switch(++ textTheme,++ l.libDisableWatcher,++ watcherDisabledGlobally ? true : _disableWatcher,++ watcherDisabledGlobally++ ? null++ : (value) => setState(() => _disableWatcher = value),++ subtitle: watcherDisabledGlobally++ ? 'The folder watcher is disabled in the server scanner settings.'++ : null,++ ),++ if (!isPodcast) ...[++ _switch(++ textTheme,++ l.libSkipAsin,++ _skipAsin,++ (value) => setState(() => _skipAsin = value),++ ),++ _switch(++ textTheme,++ l.libSkipIsbn,++ _skipIsbn,++ (value) => setState(() => _skipIsbn = value),++ ),++ _switch(++ textTheme,++ l.libHideSingleSeries,++ _hideSingleSeries,++ (value) => setState(() => _hideSingleSeries = value),++ ),++ _switch(++ textTheme,++ l.libAudiobooksOnly,++ _audiobooksOnly,++ (value) => setState(() => _audiobooksOnly = value),++ ),++ _switch(++ textTheme,++ l.libEpubScripted,++ _epubScripted,++ (value) => setState(() => _epubScripted = value),++ ),++ _switch(++ textTheme,++ l.libLaterBooksOnly,++ _laterBooksOnly,++ (value) => setState(() => _laterBooksOnly = value),++ ),++ ],++ if (isPodcast) ...[++ const SizedBox(height: 12),++ TextField(++ controller: _podcastRegion,++ decoration: InputDecoration(++ labelText: l.libPodcastRegion,++ hintText: 'us',++ ),++ ),++ ],++ const SizedBox(height: 20),++ Text('Mark finished', style: textTheme.titleMedium),++ const SizedBox(height: 8),++ DropdownButtonFormField<String>(++ value: _finishedMode,++ decoration: const InputDecoration(labelText: 'Completion rule'),++ items: [++ DropdownMenuItem(value: 'time', child: Text(l.libMarkTime)),++ DropdownMenuItem(value: 'percent', child: Text(l.libMarkPercent)),++ ],++ onChanged: (value) {++ if (value != null) setState(() => _finishedMode = value);},),-- ]);---- Widget _labeledDropdown(ColorScheme cs, TextTheme tt, String label, String value,-- List<String> options, ValueChanged<String> onChanged) =>-- Column(crossAxisAlignment: CrossAxisAlignment.start, children: [-- Text(label, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),-- DropdownButton<String>(-- value: options.contains(value) ? value : options.first,-- isExpanded: true,-- borderRadius: BorderRadius.circular(12),-- items: options.map((o) => DropdownMenuItem(value: o, child: Text(o, overflow: TextOverflow.ellipsis))).toList(),-- onChanged: (v) {-- if (v != null) onChanged(v);++ const SizedBox(height: 12),++ if (_finishedMode == 'time')++ TextField(++ controller: _markTime,++ keyboardType: TextInputType.number,++ decoration: InputDecoration(labelText: l.libMarkTime),++ )++ else++ TextField(++ controller: _markPercent,++ keyboardType: TextInputType.number,++ decoration: InputDecoration(labelText: l.libMarkPercent),++ ),++ ],++ );++ }++++ Widget _scannerSection() {++ final colors = Theme.of(context).colorScheme;++ final textTheme = Theme.of(context).textTheme;++ final l = AppLocalizations.of(context)!;++ final activeSources = _metadataSources++ .where((source) => source.enabled)++ .toList(growable: false);++ return Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ _sectionHeading(++ l.srvScannerSection,++ 'Choose which metadata sources are used. Drag them from highest to lowest priority.',++ ),++ Align(++ alignment: Alignment.centerRight,++ child: TextButton.icon(++ onPressed: () => setState(_resetMetadataSources),++ icon: const Icon(Icons.restart_alt_rounded),++ label: Text(l.resetToDefault),++ ),++ ),++ const SizedBox(height: 8),++ ReorderableListView.builder(++ shrinkWrap: true,++ physics: const NeverScrollableScrollPhysics(),++ buildDefaultDragHandles: false,++ itemCount: _metadataSources.length,++ onReorder: (oldIndex, newIndex) {++ setState(() {++ if (newIndex > oldIndex) newIndex--;++ final source = _metadataSources.removeAt(oldIndex);++ _metadataSources.insert(newIndex, source);++ });},++ itemBuilder: (context, index) {++ final source = _metadataSources[index];++ final activeIndex = activeSources.indexOf(source);++ final priority = !source.enabled++ ? 'Ignored'++ : activeIndex == 0++ ? 'Highest priority'++ : activeIndex == activeSources.length - 1++ ? 'Lowest priority'++ : 'Priority ${activeIndex + 1}';++ return Container(++ key: ValueKey(source.id),++ margin: const EdgeInsets.only(bottom: 8),++ decoration: BoxDecoration(++ color: colors.surfaceContainerHigh,++ borderRadius: BorderRadius.circular(14),++ ),++ child: ListTile(++ leading: Switch(++ value: source.enabled,++ onChanged: (enabled) {++ setState(() => source.enabled = enabled);++ },++ ),++ title: Text(_metadataSourceLabel(source.id)),++ subtitle: Text(priority),++ trailing: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ IconButton(++ tooltip: 'Move up',++ onPressed: index == 0++ ? null++ : () => _moveMetadataSource(index, -1),++ icon: const Icon(Icons.keyboard_arrow_up_rounded),++ ),++ IconButton(++ tooltip: 'Move down',++ onPressed: index == _metadataSources.length - 1++ ? null++ : () => _moveMetadataSource(index, 1),++ icon: const Icon(Icons.keyboard_arrow_down_rounded),++ ),++ ReorderableDragStartListener(++ index: index,++ child: const Padding(++ padding: EdgeInsets.all(8),++ child: Icon(Icons.drag_handle_rounded),++ ),++ ),++ ],++ ),++ ),++ );++ },++ ),++ const SizedBox(height: 8),++ Text(++ 'Disabled sources are ignored when the scanner reads metadata.',++ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),++ ),++ ],++ );++ }++++ void _moveMetadataSource(int index, int offset) {++ final target = index + offset;++ if (target < 0 || target >= _metadataSources.length) return;++ setState(() {++ final source = _metadataSources.removeAt(index);++ _metadataSources.insert(target, source);++ });++ }++++ String _metadataSourceLabel(String id) {++ return switch (id) {++ 'folderStructure' => 'Folder structure',++ 'audioMetatags' =>++ _mediaType == 'book'++ ? 'Audio file metadata or ebook metadata'++ : 'Audio file metadata',++ 'nfoFile' => 'NFO file',++ 'txtFiles' => 'desc.txt and reader.txt files',++ 'opfFile' => 'OPF file',++ 'absMetadata' => 'Audiobookshelf metadata file',++ _ => id,++ };++ }++++ Widget _scheduleSection() {++ final colors = Theme.of(context).colorScheme;++ final textTheme = Theme.of(context).textTheme;++ final l = AppLocalizations.of(context)!;++ final serverTimeZone =++ context.watch<AuthProvider>().serverSettings?['timeZone'] as String?;++++ return Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ _sectionHeading(++ 'Schedule',++ 'Run a library scan automatically on a recurring schedule.',++ ),++ _switch(++ textTheme,++ l.libAutoScan,++ _scheduleEnabled,++ _setScheduleEnabled,++ ),++ if (_scheduleEnabled) ...[++ const SizedBox(height: 12),++ DropdownButtonFormField<String>(++ value: _scheduleMode,++ decoration: InputDecoration(labelText: l.adminPodcastsFrequency),++ items: [++ DropdownMenuItem(++ value: 'hourly',++ child: Text(l.adminPodcastsFreqHourly),++ ),++ DropdownMenuItem(++ value: 'daily',++ child: Text(l.adminPodcastsFreqDaily),++ ),++ DropdownMenuItem(++ value: 'weekly',++ child: Text(l.adminPodcastsFreqWeekly),++ ),++ const DropdownMenuItem(++ value: 'advanced',++ child: Text('Advanced cron'),++ ),++ ],++ onChanged: (value) {++ if (value != null) _setScheduleMode(value);++ },++ ),++ const SizedBox(height: 16),++ if (_scheduleMode == 'hourly') ...[++ Text('Minute ${_scheduleMinute.toString().padLeft(2, '0')}'),++ Slider(++ min: 0,++ max: 59,++ divisions: 59,++ label: _scheduleMinute.toString(),++ value: _scheduleMinute.toDouble(),++ onChanged: (value) {++ setState(() {++ _scheduleMinute = value.round();++ _rebuildCron();++ });++ },++ ),++ ],++ if (_scheduleMode == 'daily' || _scheduleMode == 'weekly') ...[++ if (_scheduleMode == 'weekly') ...[++ DropdownButtonFormField<int>(++ value: _scheduleWeekday,++ decoration: InputDecoration(labelText: l.adminPodcastsDay),++ items: _weekdayLabels(l).entries++ .map(++ (entry) => DropdownMenuItem(++ value: entry.key,++ child: Text(entry.value),++ ),++ )++ .toList(),++ onChanged: (value) {++ if (value == null) return;++ setState(() {++ _scheduleWeekday = value;++ _rebuildCron();++ });++ },++ ),++ const SizedBox(height: 12),++ ],++ ListTile(++ contentPadding: EdgeInsets.zero,++ title: const Text('Time'),++ subtitle: Text(_scheduleTime.format(context)),++ trailing: const Icon(Icons.schedule_rounded),++ onTap: _pickScheduleTime,++ ),++ ],++ if (_scheduleMode == 'advanced')++ TextField(++ controller: _autoScan,++ decoration: InputDecoration(++ labelText: l.libAutoScan,++ hintText: '0 0 * * *',++ helperText: 'Minute Hour Day Month Weekday',++ ),++ )++ else++ Container(++ width: double.infinity,++ padding: const EdgeInsets.all(14),++ decoration: BoxDecoration(++ color: colors.surfaceContainerHigh,++ borderRadius: BorderRadius.circular(12),++ ),++ child: SelectableText(++ _autoScan.text,++ style: textTheme.bodyLarge?.copyWith(fontFamily: 'monospace'),++ ),++ ),++ const SizedBox(height: 12),++ Text(++ serverTimeZone == null || serverTimeZone.isEmpty++ ? l.podcastScheduleServerTimeUnknown++ : l.podcastScheduleServerTime(serverTimeZone),++ style: textTheme.bodySmall?.copyWith(++ color: colors.onSurfaceVariant,++ ),++ ),++ ],++ ],++ );++ }++++ Map<int, String> _weekdayLabels(AppLocalizations l) => {++ DateTime.sunday: l.adminPodcastsDaySun,++ DateTime.monday: l.adminPodcastsDayMon,++ DateTime.tuesday: l.adminPodcastsDayTue,++ DateTime.wednesday: l.adminPodcastsDayWed,++ DateTime.thursday: l.adminPodcastsDayThu,++ DateTime.friday: l.adminPodcastsDayFri,++ DateTime.saturday: l.adminPodcastsDaySat,++ };++++ Widget _toolsSection() {++ final colors = Theme.of(context).colorScheme;++ return Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ _sectionHeading(++ 'Tools',++ 'Clean up generated sidecar metadata files across this library.',++ ),++ _metadataRemovalCard(++ colors,++ extension: 'json',++ description:++ 'Remove every metadata.json file found in the library item folders.',++ ),++ const SizedBox(height: 12),++ _metadataRemovalCard(++ colors,++ extension: 'abs',++ description:++ 'Remove every metadata.abs file found in the library item folders.',),-- ]);++ ],++ );++ }++++ Widget _metadataRemovalCard(++ ColorScheme colors, {++ required String extension,++ required String description,++ }) {++ final busy = _removingMetadataExtension == extension;++ final anyBusy = _removingMetadataExtension != null;++ return Container(++ padding: const EdgeInsets.all(16),++ decoration: BoxDecoration(++ color: colors.surfaceContainerHigh,++ borderRadius: BorderRadius.circular(16),++ ),++ child: LayoutBuilder(++ builder: (context, constraints) {++ final button = OutlinedButton.icon(++ onPressed: anyBusy ? null : () => _removeMetadataFiles(extension),++ icon: busy++ ? const SizedBox(++ width: 16,++ height: 16,++ child: CircularProgressIndicator(strokeWidth: 2),++ )++ : const Icon(Icons.delete_outline_rounded),++ label: Text('Remove metadata.$extension'),++ );++ final copy = Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(++ 'metadata.$extension',++ style: Theme.of(context).textTheme.titleMedium,++ ),++ const SizedBox(height: 4),++ Text(description),++ ],++ );++ if (constraints.maxWidth < 600) {++ return Column(++ crossAxisAlignment: CrossAxisAlignment.stretch,++ children: [copy, const SizedBox(height: 14), button],++ );++ }++ return Row(++ children: [++ Expanded(child: copy),++ const SizedBox(width: 20),++ button,++ ],++ );++ },++ ),++ );++ }++++ Widget _coverShape(TextTheme textTheme, AppLocalizations l) => Padding(++ padding: const EdgeInsets.symmetric(vertical: 8),++ child: LayoutBuilder(++ builder: (context, constraints) {++ final selector = SegmentedButton<num>(++ segments: [++ ButtonSegment(value: 1, label: Text(l.libCoverSquare)),++ ButtonSegment(value: 0, label: Text(l.libCoverStandard)),++ ],++ selected: {_coverAspectRatio == 0 ? 0 : 1},++ onSelectionChanged: (selection) {++ setState(() => _coverAspectRatio = selection.first);++ },++ );++ if (constraints.maxWidth < 500) {++ return Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(l.libCoverShape, style: textTheme.bodyMedium),++ const SizedBox(height: 8),++ selector,++ ],++ );++ }++ return Row(++ children: [++ Expanded(child: Text(l.libCoverShape, style: textTheme.bodyMedium)),++ selector,++ ],++ );++ },++ ),++ );++++ Widget _switch(++ TextTheme textTheme,++ String label,++ bool value,++ ValueChanged<bool>? onChanged, {++ String? subtitle,++ }) => SwitchListTile(++ contentPadding: EdgeInsets.zero,++ title: Text(label, style: textTheme.bodyMedium),++ subtitle: subtitle == null ? null : Text(subtitle),++ value: value,++ onChanged: onChanged,++ );++++ Widget _iconDropdown(++ ColorScheme colors,++ TextTheme textTheme,++ String value,++ List<String> options,++ ValueChanged<String> onChanged,++ ) => Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(++ AppLocalizations.of(context)!.libIcon,++ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),++ ),++ DropdownButton<String>(++ value: options.contains(value) ? value : options.first,++ isExpanded: true,++ borderRadius: BorderRadius.circular(12),++ items: options++ .map(++ (option) => DropdownMenuItem(++ value: option,++ child: Row(++ children: [++ Icon(++ _absIcon(option),++ size: 18,++ color: colors.onSurfaceVariant,++ ),++ const SizedBox(width: 10),++ Flexible(++ child: Text(option, overflow: TextOverflow.ellipsis),++ ),++ ],++ ),++ ),++ )++ .toList(),++ onChanged: (newValue) {++ if (newValue != null) onChanged(newValue);++ },++ ),++ ],++ );++++ Widget _labeledDropdown(++ ColorScheme colors,++ TextTheme textTheme,++ String label,++ String value,++ List<String> options,++ ValueChanged<String> onChanged,++ ) => Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(++ label,++ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),++ ),++ DropdownButton<String>(++ value: options.contains(value) ? value : options.first,++ isExpanded: true,++ borderRadius: BorderRadius.circular(12),++ items: options++ .map(++ (option) => DropdownMenuItem(++ value: option,++ child: Text(option, overflow: TextOverflow.ellipsis),++ ),++ )++ .toList(),++ onChanged: (newValue) {++ if (newValue != null) onChanged(newValue);++ },++ ),++ ],++ );}diff --cc lib/screens/admin_podcasts_screen.dartindex 2858eafe,0bc819f9..d2208b94--- a/lib/screens/admin_podcasts_screen.dart+++ b/lib/screens/admin_podcasts_screen.dart@@@ -7,8 -7,7 +7,9 @@@ import '../providers/auth_provider.dartimport '../services/socket_service.dart';import 'podcast_edit_screen.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/adaptive_modal.dart';+import '../widgets/desktop_page_body.dart';+ import '../widgets/delete_confirm_dialog.dart';import '../widgets/html_description.dart';import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';diff --cc lib/screens/admin_screen.dartindex 6477e570,9f19fd84..0cb3e615--- a/lib/screens/admin_screen.dart+++ b/lib/screens/admin_screen.dart@@@ -21,6 -18,6 +21,7 @@@ import 'admin_email_screen.dart'import 'admin_api_keys_screen.dart';import 'admin_libraries_screen.dart';import 'admin_server_settings_screen.dart';++import 'admin_server_logs_screen.dart';import 'admin_stats_screen.dart';import 'admin_sessions_screen.dart';@@@ -409,6 -304,6 +410,16 @@@ class _AdminScreenState extends State<A},),const SizedBox(height: 10),++ _navButton(cs, tt,++ icon: Icons.description_outlined,++ label: 'Server logs',++ subtitle: l.sendLogsSubtitle,++ onTap: () {++ Navigator.push(context, MaterialPageRoute(++ builder: (_) => const AdminServerLogsScreen()));++ },++ ),++ const SizedBox(height: 10),_navButton(cs, tt,icon: Icons.bar_chart_rounded,label: l.adminStats,@@@ -462,442 -356,6 +473,445 @@@// ─── Shared Widgets ─────────────────────────────────────────+ Widget _buildDesktopScaffold(BuildContext context, AppLocalizations l) {+ final outerNavigator = Navigator.of(context);+ final destinations = <AdminSectionDestination>[+ AdminSectionDestination(_overviewSection, Icons.dashboard_rounded, l.adminServer),+ AdminSectionDestination('users', Icons.people_rounded, l.adminUsers),+ AdminSectionDestination('upload', Icons.cloud_upload_rounded, l.adminUploadTitle),+ if (_hasPodcastLibrary || _desktopSection == 'podcasts')+ AdminSectionDestination('podcasts', Icons.podcasts_rounded, l.adminPodcasts),+ AdminSectionDestination('email', Icons.email_rounded, l.adminEmail),+ AdminSectionDestination('api-keys', Icons.vpn_key_rounded, l.adminApiKeys),+ AdminSectionDestination('libraries', Icons.library_books_rounded, l.adminLibrariesManage),+ AdminSectionDestination('server-settings', Icons.tune_rounded, l.adminServerSettings),++ const AdminSectionDestination('logs', Icons.description_outlined, 'Server logs'),+ AdminSectionDestination('stats', Icons.bar_chart_rounded, l.adminStats),+ AdminSectionDestination('sessions', Icons.history_rounded, l.adminAllSessions),+ ];++ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: SafeArea(+ child: _loading+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))+ : PopScope(+ canPop: !_desktopNavigatorCanPop,+ onPopInvokedWithResult: (didPop, result) {+ if (didPop) return;+ final navigator = _desktopNavigatorKey.currentState;+ if (navigator != null) unawaited(navigator.maybePop(result));+ },+ child: AdminAdaptiveFrame(+ desktopMode: true,+ title: l.adminTitle,+ selectedSection: _desktopSection,+ destinations: destinations,+ onSectionSelected: (section) => unawaited(_selectDesktopSection(section)),+ child: Navigator(+ key: _desktopNavigatorKey,+ observers: [_desktopNavigatorObserver],+ onDidRemovePage: (_) {},+ pages: [+ MaterialPage<void>(+ key: const ValueKey('admin-overview-page'),+ name: '/admin/overview',+ child: Builder(+ builder: (pageContext) => _buildDesktopOverview(+ pageContext,+ onClose: () => outerNavigator.pop(),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _buildDesktopOverview(BuildContext pageContext, {required VoidCallback onClose}) {+ final cs = Theme.of(pageContext).colorScheme;+ final tt = Theme.of(pageContext).textTheme;+ final l = AppLocalizations.of(pageContext)!;++ return DesktopPageBody(+ maxWidth: 1040,+ child: RefreshIndicator(+ onRefresh: _loadAll,+ notificationPredicate: (_) => false,+ child: ListView(+ padding: const EdgeInsets.only(bottom: 24),+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),+ child: Row(children: [+ Expanded(child: AbsorbPageHeader(title: l.adminTitle, padding: EdgeInsets.zero)),+ IconButton(+ tooltip: l.refreshTooltip,+ icon: Icon(Icons.refresh_rounded, color: cs.onSurfaceVariant),+ onPressed: _loadAll,+ ),+ IconButton(+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),+ onPressed: onClose,+ ),+ ]),+ ),+ const SizedBox(height: 20),+ _section(cs, tt, l.adminServer),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Container(+ padding: const EdgeInsets.all(16),+ decoration: _cardDeco(cs),+ child: Row(children: [+ _stat(tt, cs, Icons.dns_rounded, _serverVersion ?? '–', l.adminVersion),+ _stat(tt, cs, Icons.people_rounded, '${_users.length}', l.adminUsers),+ _stat(tt, cs, Icons.wifi_rounded, '${_onlineUsers.length}', l.adminOnline),+ _stat(tt, cs, Icons.backup_rounded, '${_backups.length}', l.adminBackupsLabel),+ ]),+ ),+ ),+ const SizedBox(height: 8),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Row(children: [+ Expanded(child: _actionBtn(cs, tt, Icons.backup_rounded, l.adminBackup, _creatingBackup, _createBackup)),+ const SizedBox(width: 10),+ Expanded(child: _actionBtn(cs, tt, Icons.cleaning_services_rounded, l.adminPurgeCache, _purgingCache, _purgeCache)),+ ]),+ ),+ const SizedBox(height: 28),+ _section(cs, tt, l.adminRmab),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: _hasRmab ? _rmabTile(cs, tt) : _rmabAddRow(cs, tt),+ ),+ const SizedBox(height: 28),+ if (_activeSessions.isNotEmpty) ...[+ _section(cs, tt, l.adminListeningNow),+ ..._activeSessions.map((session) => _sessionCard(cs, tt, session)),+ const SizedBox(height: 18),+ ],+ _section(cs, tt, l.adminLibraries),+ ListenableBuilder(+ listenable: _taskTracker,+ builder: (_, __) => Column(+ children: _libraries.map((library) => _libraryCard(cs, tt, library)).toList(),+ ),+ ),+ ],+ ),+ ),+ );+ }++ void _onDesktopStackChanged() {+ DesktopWorkspaceNavigator.notifyExitGuardChanged();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final canPop = _desktopNavigatorKey.currentState?.canPop() ?? false;+ if (canPop != _desktopNavigatorCanPop) {+ setState(() => _desktopNavigatorCanPop = canPop);+ }+ });+ }++ Future<void> _selectDesktopSection(String section) async {+ final navigator = _desktopNavigatorKey.currentState;+ if (navigator == null || _desktopNavigationChanging) return;+ if (section == _desktopSection &&+ (section != _overviewSection || !navigator.canPop())) return;++ final previousSection = _desktopSection;+ final previousSerial = _desktopNavigationSerial;+ _desktopNavigationChanging = true;+ final navigationSerial = ++_desktopNavigationSerial;++ try {+ if (!await _popDesktopNavigatorToOverview(navigator)) {+ _desktopNavigationSerial = previousSerial;+ return;+ }+ if (!mounted || _desktopNavigatorKey.currentState != navigator) return;+ _markDesktopSectionDirty(previousSection);++ if (section == _overviewSection) {+ if (_desktopSection != _overviewSection || _desktopNavigatorCanPop) {+ setState(() {+ _desktopSection = _overviewSection;+ _desktopNavigatorCanPop = false;+ });+ }+ unawaited(_refreshDesktopOverviewIfNeeded());+ return;+ }++ setState(() {+ _desktopSection = section;+ _desktopNavigatorCanPop = true;+ });+ final sectionPreparation = _prepareDesktopSectionInputs(section);+ final route = MaterialPageRoute<void>(+ settings: RouteSettings(name: '/admin/$section'),+ builder: (routeContext) => _buildPreparedDesktopSectionPage(+ routeContext,+ section,+ sectionPreparation,+ ),+ );+ unawaited(navigator.push(route).then((_) {+ if (!mounted || navigationSerial != _desktopNavigationSerial) return;+ setState(() {+ _desktopSection = _overviewSection;+ _desktopNavigatorCanPop = false;+ });+ _markDesktopSectionDirty(section);+ unawaited(_refreshDesktopOverviewIfNeeded());+ }));+ } finally {+ _desktopNavigationChanging = false;+ }+ }++ Future<bool> _prepareForDesktopPaneReset() async {+ if (!mounted || _desktopPresentation != true) return true;+ final navigator = _desktopNavigatorKey.currentState;+ if (navigator == null || !navigator.canPop()) return true;+ if (_desktopNavigationChanging) return false;++ final previousSerial = _desktopNavigationSerial;+ _desktopNavigationChanging = true;+ _desktopNavigationSerial++;+ try {+ if (!await _popDesktopNavigatorToOverview(navigator)) {+ _desktopNavigationSerial = previousSerial;+ return false;+ }+ if (mounted) {+ setState(() {+ _desktopSection = _overviewSection;+ _desktopNavigatorCanPop = false;+ });+ }+ return true;+ } finally {+ _desktopNavigationChanging = false;+ }+ }++ Future<bool> _popDesktopNavigatorToOverview(+ NavigatorState navigator,+ ) async {+ while (navigator.canPop()) {+ final routeDepth = _desktopNavigatorObserver.routeDepth;+ await navigator.maybePop();+ if (_desktopNavigatorObserver.routeDepth >= routeDepth) return false;+ }+ return true;+ }++ void _markDesktopSectionDirty(String section) {+ if (section == 'users') {+ _desktopUsersDirty = true;+ _desktopUsersDirtyGeneration++;+ _desktopOverviewDirty = true;+ _desktopOverviewDirtyGeneration++;+ } else if (section == 'libraries') {+ _desktopLibrariesDirty = true;+ _desktopLibrariesDirtyGeneration++;+ _desktopOverviewDirty = true;+ _desktopOverviewDirtyGeneration++;+ } else if (section == 'sessions') {+ _desktopOverviewDirty = true;+ _desktopOverviewDirtyGeneration++;+ }+ }++ Future<void> _refreshDesktopOverviewIfNeeded() async {+ if (!_desktopOverviewDirty || _desktopOverviewRefreshActive) return;+ _desktopOverviewRefreshActive = true;+ try {+ do {+ await _loadAll();+ } while (mounted && _desktopOverviewDirty);+ } catch (error) {+ debugPrint('[Admin] Could not refresh overview: $error');+ } finally {+ _desktopOverviewRefreshActive = false;+ }+ }++ Future<void>? _prepareDesktopSectionInputs(String nextSection) {+ if (_desktopUsersDirty &&+ (nextSection == 'email' ||+ nextSection == 'api-keys' ||+ nextSection == 'sessions')) {+ return _refreshDesktopUsers();+ }+ if (_desktopLibrariesDirty &&+ (nextSection == 'users' ||+ nextSection == 'upload' ||+ nextSection == 'podcasts')) {+ return _refreshDesktopLibraries();+ }+ return null;+ }++ Future<void> _refreshDesktopUsers() {+ final activeRefresh = _desktopUsersRefresh;+ if (activeRefresh != null) return activeRefresh;+ final refresh = _runDesktopUsersRefresh();+ _desktopUsersRefresh = refresh;+ unawaited(refresh.whenComplete(() {+ if (identical(_desktopUsersRefresh, refresh)) {+ _desktopUsersRefresh = null;+ }+ }));+ return refresh;+ }++ Future<void> _runDesktopUsersRefresh() async {+ if (!mounted) return;+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ try {+ do {+ final generation = _desktopUsersDirtyGeneration;+ final results = await Future.wait([+ api.getUsers(),+ api.getOnlineUsers(),+ ]);+ if (!mounted) return;+ setState(() {+ _users = results[0];+ _onlineUsers = results[1];+ if (_desktopUsersDirtyGeneration == generation) {+ _desktopUsersDirty = false;+ }+ });+ } while (mounted && _desktopUsersDirty);+ } catch (error) {+ debugPrint('[Admin] Could not refresh users: $error');+ }+ }++ Future<void> _refreshDesktopLibraries() {+ final activeRefresh = _desktopLibrariesRefresh;+ if (activeRefresh != null) return activeRefresh;+ final refresh = _runDesktopLibrariesRefresh();+ _desktopLibrariesRefresh = refresh;+ unawaited(refresh.whenComplete(() {+ if (identical(_desktopLibrariesRefresh, refresh)) {+ _desktopLibrariesRefresh = null;+ }+ }));+ return refresh;+ }++ Future<void> _runDesktopLibrariesRefresh() async {+ if (!mounted) return;+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ try {+ do {+ final generation = _desktopLibrariesDirtyGeneration;+ final libraries = await api.getLibraries();+ if (!mounted) return;+ setState(() {+ _libraries = libraries;+ if (_desktopLibrariesDirtyGeneration == generation) {+ _desktopLibrariesDirty = false;+ }+ });+ } while (mounted && _desktopLibrariesDirty);+ _leaveUnavailablePodcastSection();+ } catch (error) {+ debugPrint('[Admin] Could not refresh libraries: $error');+ }+ }++ void _leaveUnavailablePodcastSection() {+ if (_desktopPresentation != true ||+ _desktopSection != 'podcasts' ||+ _hasPodcastLibrary) {+ return;+ }+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted ||+ _desktopSection != 'podcasts' ||+ _hasPodcastLibrary) {+ return;+ }+ unawaited(_selectDesktopSection(_overviewSection));+ });+ }++ Widget _buildPreparedDesktopSectionPage(+ BuildContext routeContext,+ String section,+ Future<void>? preparation,+ ) {+ if (preparation == null) {+ return _buildDesktopSectionPage(routeContext, section);+ }+ return FutureBuilder<void>(+ future: preparation,+ builder: (context, snapshot) {+ if (snapshot.connectionState != ConnectionState.done) {+ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: const Center(+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ );+ }+ return _buildDesktopSectionPage(context, section);+ },+ );+ }++ Widget _buildDesktopSectionPage(BuildContext routeContext, String section) {+ switch (section) {+ case 'users':+ return AdminUsersScreen(users: _users, onlineUsers: _onlineUsers, libraries: _libraries);+ case 'upload':+ return AdminUploadScreen(+ libraries: _libraries,+ initialLibraryId: routeContext.read<AuthProvider>().defaultLibraryId,+ apiService: routeContext.read<AuthProvider>().apiService,+ onNavigationGuardChanged:+ DesktopWorkspaceNavigator.notifyExitGuardChanged,+ );+ case 'podcasts':+ final podcastLibrary = _libraries.firstWhere(+ (library) => library['mediaType'] == 'podcast',+ orElse: () => null,+ );+ return podcastLibrary == null+ ? const SizedBox.shrink()+ : AdminPodcastsScreen(library: podcastLibrary);+ case 'email':+ return AdminEmailScreen(users: _users);+ case 'api-keys':+ return AdminApiKeysScreen(users: _users);+ case 'libraries':+ return AdminLibrariesScreen(libraries: _libraries);+ case 'server-settings':+ return const AdminServerSettingsScreen();++ case 'logs':++ return const AdminServerLogsScreen();+ case 'stats':+ return const AdminStatsScreen();+ case 'sessions':+ return AdminSessionsScreen(users: _users);+ default:+ return const SizedBox.shrink();+ }+ }+Widget _section(ColorScheme cs, TextTheme tt, String t) => Padding(padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),child: Text(t, style: tt.labelLarge?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6), fontWeight: FontWeight.w600, letterSpacing: 0.5)));diff --cc lib/screens/admin_server_logs_screen.dartindex 00000000,00000000..d8093259new file mode 100644--- /dev/null+++ b/lib/screens/admin_server_logs_screen.dart@@@ -1,0 -1,0 +1,663 @@@++import 'package:flutter/material.dart';++import 'package:provider/provider.dart';++++import '../l10n/app_localizations.dart';++import '../providers/auth_provider.dart';++import '../services/server_log_export_service.dart';++import '../services/socket_service.dart';++import '../widgets/absorb_page_header.dart';++import '../widgets/overlay_toast.dart';++++class AdminServerLogsScreen extends StatefulWidget {++ const AdminServerLogsScreen({super.key});++++ @override++ State<AdminServerLogsScreen> createState() => _AdminServerLogsScreenState();++}++++class _AdminServerLogsScreenState extends State<AdminServerLogsScreen> {++ static const _maxLogs = 5000;++ static const _serverLevels = <int, String>{++ 0: 'Trace',++ 1: 'Debug',++ 2: 'Info',++ 3: 'Warning',++ };++ static const _filterLevels = <int, String>{++ -1: 'All levels',++ 0: 'Trace and higher',++ 1: 'Debug and higher',++ 2: 'Info and higher',++ 3: 'Warning and higher',++ 4: 'Error and higher',++ };++++ final _searchController = TextEditingController();++ final _scrollController = ScrollController();++ final _socket = SocketService();++ late final void Function(Map<String, dynamic>) _socketLogHandler;++++ List<_ServerLogEntry> _logs = [];++ bool _loading = true;++ bool _refreshing = false;++ bool _loadFailed = false;++ bool _savingLogLevel = false;++ int _serverLogLevel = 2;++ int _visibleMinimumLevel = -1;++ String _searchText = '';++++ @override++ void initState() {++ super.initState();++ _socketLogHandler = _onServerLog;++ final rawLevel = context.read<AuthProvider>().serverSettings?['logLevel'];++ _serverLogLevel = _parseServerLevel(rawLevel);++ _socket.addServerLogListener(_socketLogHandler, level: _serverLogLevel);++ _loadLogs();++ }++++ @override++ void dispose() {++ _socket.removeServerLogListener(_socketLogHandler);++ _searchController.dispose();++ _scrollController.dispose();++ super.dispose();++ }++++ int _parseServerLevel(dynamic value) {++ final parsed = value is num++ ? value.toInt()++ : int.tryParse(value?.toString() ?? '');++ return _serverLevels.containsKey(parsed) ? parsed! : 2;++ }++++ List<_ServerLogEntry> get _visibleLogs {++ final query = _searchText.trim().toLowerCase();++ return _logs++ .where((log) {++ if (_visibleMinimumLevel >= 0 && log.level < _visibleMinimumLevel) {++ return false;++ }++ return query.isEmpty || log.searchText.contains(query);++ })++ .toList(growable: false);++ }++++ Future<void> _loadLogs() async {++ final api = context.read<AuthProvider>().apiService;++ if (api == null) {++ setState(() {++ _loading = false;++ _loadFailed = true;++ });++ return;++ }++++ setState(() {++ if (_logs.isEmpty) {++ _loading = true;++ } else {++ _refreshing = true;++ }++ _loadFailed = false;++ });++ final rawLogs = await api.getServerLogs();++ if (!mounted) return;++++ if (rawLogs == null) {++ setState(() {++ _loading = false;++ _refreshing = false;++ _loadFailed = true;++ });++ return;++ }++++ final loaded = rawLogs++ .map(_ServerLogEntry.fromMap)++ .whereType<_ServerLogEntry>();++ final merged = <String, _ServerLogEntry>{};++ for (final log in [...loaded, ..._logs]) {++ merged[log.identity] = log;++ }++ var values = merged.values.toList(growable: false);++ if (values.length > _maxLogs) {++ values = values.sublist(values.length - _maxLogs);++ }++ setState(() {++ _logs = values;++ _loading = false;++ _refreshing = false;++ });++ _scrollToBottom(jump: true);++ }++++ void _onServerLog(Map<String, dynamic> rawLog) {++ final log = _ServerLogEntry.fromMap(rawLog);++ if (log == null || !mounted) return;++ final shouldFollow =++ !_scrollController.hasClients ||++ _scrollController.position.maxScrollExtent -++ _scrollController.position.pixels <++ 96;++ setState(() {++ _logs = [..._logs, log];++ if (_logs.length > _maxLogs + 50) {++ _logs = _logs.sublist(_logs.length - _maxLogs);++ }++ });++ if (shouldFollow) _scrollToBottom();++ }++++ void _scrollToBottom({bool jump = false}) {++ WidgetsBinding.instance.addPostFrameCallback((_) {++ if (!mounted || !_scrollController.hasClients) return;++ final target = _scrollController.position.maxScrollExtent;++ if (jump) {++ _scrollController.jumpTo(target);++ } else {++ _scrollController.animateTo(++ target,++ duration: const Duration(milliseconds: 180),++ curve: Curves.easeOut,++ );++ }++ });++ }++++ Future<void> _changeServerLogLevel(int level) async {++ if (_savingLogLevel || level == _serverLogLevel) return;++ final auth = context.read<AuthProvider>();++ final api = auth.apiService;++ if (api == null) return;++ final previous = _serverLogLevel;++ setState(() {++ _serverLogLevel = level;++ _savingLogLevel = true;++ });++++ final updated = await api.updateServerSettings({'logLevel': level});++ if (!mounted) return;++ if (updated == null) {++ setState(() {++ _serverLogLevel = previous;++ _savingLogLevel = false;++ });++ showOverlayToast(++ context,++ AppLocalizations.of(context)!.srvSaveFailed,++ icon: Icons.error_outline_rounded,++ );++ return;++ }++++ auth.applyServerSettings(updated);++ _socket.updateServerLogListenerLevel(_socketLogHandler, level);++ setState(() => _savingLogLevel = false);++ }++++ Future<void> _exportVisibleLogs(BuildContext buttonContext) async {++ final logs = _visibleLogs;++ if (logs.isEmpty) return;++ final now = DateTime.now();++ String two(int value) => value.toString().padLeft(2, '0');++ final fileName =++ 'audiobookshelf_server_logs_${now.year}-${two(now.month)}-${two(now.day)}_${two(now.hour)}-${two(now.minute)}-${two(now.second)}.txt';++ final content = StringBuffer()++ ..writeln('Audiobookshelf server logs')++ ..writeln('Exported: ${now.toIso8601String()}')++ ..writeln('Server log level: ${_serverLevels[_serverLogLevel]}')++ ..writeln('Visible entries: ${logs.length} of ${_logs.length}')++ ..writeln(++ 'Display filter: ${_filterLevels[_visibleMinimumLevel] ?? 'All levels'}',++ );++ if (_searchText.trim().isNotEmpty) {++ content.writeln('Search: ${_searchText.trim()}');++ }++ content.writeln();++ for (final log in logs) {++ content.writeln(log.exportLine);++ }++++ final box = buttonContext.findRenderObject();++ final origin = box is RenderBox++ ? box.localToGlobal(Offset.zero) & box.size++ : null;++ try {++ await ServerLogExportService.exportText(++ fileName: fileName,++ content: content.toString(),++ sharePositionOrigin: origin,++ );++ } catch (error) {++ if (!mounted) return;++ showOverlayToast(++ context,++ AppLocalizations.of(context)!.failedToShare(error.toString()),++ icon: Icons.error_outline_rounded,++ );++ }++ }++++ @override++ Widget build(BuildContext context) {++ final cs = Theme.of(context).colorScheme;++ final tt = Theme.of(context).textTheme;++ final l = AppLocalizations.of(context)!;++ final visibleLogs = _visibleLogs;++++ return Scaffold(++ backgroundColor: Theme.of(context).scaffoldBackgroundColor,++ body: SafeArea(++ child: Column(++ children: [++ Padding(++ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),++ child: Row(++ children: [++ const Expanded(++ child: AbsorbPageHeader(++ title: 'Server logs',++ padding: EdgeInsets.zero,++ ),++ ),++ if (_refreshing)++ const Padding(++ padding: EdgeInsets.symmetric(horizontal: 12),++ child: SizedBox(++ width: 16,++ height: 16,++ child: CircularProgressIndicator(strokeWidth: 2),++ ),++ )++ else++ IconButton(++ tooltip: l.refreshTooltip,++ onPressed: _loadLogs,++ icon: Icon(++ Icons.refresh_rounded,++ color: cs.onSurfaceVariant,++ ),++ ),++ Builder(++ builder: (buttonContext) => IconButton(++ tooltip: l.sendLogs,++ onPressed: visibleLogs.isEmpty++ ? null++ : () => _exportVisibleLogs(buttonContext),++ icon: const Icon(Icons.download_rounded),++ ),++ ),++ IconButton(++ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),++ onPressed: () => Navigator.pop(context),++ ),++ ],++ ),++ ),++ Padding(++ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),++ child: _buildControls(cs, tt, l),++ ),++ Expanded(++ child: Padding(++ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),++ child: _buildLogPanel(cs, tt, l, visibleLogs),++ ),++ ),++ ],++ ),++ ),++ );++ }++++ Widget _buildControls(ColorScheme cs, TextTheme tt, AppLocalizations l) {++ final search = TextField(++ controller: _searchController,++ onChanged: (value) => setState(() => _searchText = value),++ decoration: InputDecoration(++ labelText: l.search,++ prefixIcon: const Icon(Icons.search_rounded),++ suffixIcon: _searchText.isEmpty++ ? null++ : IconButton(++ onPressed: () {++ _searchController.clear();++ setState(() => _searchText = '');++ },++ icon: const Icon(Icons.close_rounded),++ ),++ ),++ );++ final displayFilter = _dropdown(++ cs,++ tt,++ label: 'Display',++ value: _visibleMinimumLevel,++ options: _filterLevels,++ onChanged: (value) => setState(() => _visibleMinimumLevel = value),++ );++ final serverLevel = _dropdown(++ cs,++ tt,++ label: _savingLogLevel ? 'Saving log level…' : 'Server log level',++ value: _serverLogLevel,++ options: _serverLevels,++ onChanged: _savingLogLevel ? null : _changeServerLogLevel,++ );++++ return LayoutBuilder(++ builder: (context, constraints) {++ if (constraints.maxWidth >= 720) {++ return Row(++ crossAxisAlignment: CrossAxisAlignment.end,++ children: [++ Expanded(child: search),++ const SizedBox(width: 12),++ SizedBox(width: 190, child: displayFilter),++ const SizedBox(width: 12),++ SizedBox(width: 180, child: serverLevel),++ ],++ );++ }++ return Column(++ children: [++ search,++ const SizedBox(height: 10),++ Row(++ children: [++ Expanded(child: displayFilter),++ const SizedBox(width: 10),++ Expanded(child: serverLevel),++ ],++ ),++ ],++ );++ },++ );++ }++++ Widget _dropdown(++ ColorScheme cs,++ TextTheme tt, {++ required String label,++ required int value,++ required Map<int, String> options,++ required ValueChanged<int>? onChanged,++ }) {++ return InputDecorator(++ decoration: InputDecoration(labelText: label),++ child: DropdownButtonHideUnderline(++ child: DropdownButton<int>(++ value: value,++ isDense: true,++ isExpanded: true,++ borderRadius: BorderRadius.circular(12),++ style: tt.bodyMedium?.copyWith(color: cs.onSurface),++ items: options.entries++ .map(++ (entry) => DropdownMenuItem<int>(++ value: entry.key,++ child: Text(++ entry.value,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ ),++ ),++ )++ .toList(growable: false),++ onChanged: onChanged == null++ ? null++ : (selected) {++ if (selected != null) onChanged(selected);++ },++ ),++ ),++ );++ }++++ Widget _buildLogPanel(++ ColorScheme cs,++ TextTheme tt,++ AppLocalizations l,++ List<_ServerLogEntry> visibleLogs,++ ) {++ if (_loading) {++ return const Center(child: CircularProgressIndicator(strokeWidth: 2));++ }++ if (_loadFailed && _logs.isEmpty) {++ return Center(++ child: Column(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(++ Icons.error_outline_rounded,++ size: 42,++ color: cs.error.withValues(alpha: 0.7),++ ),++ const SizedBox(height: 12),++ Text(++ 'Couldn’t load the server logs',++ style: tt.titleSmall?.copyWith(color: cs.onSurface),++ ),++ const SizedBox(height: 8),++ OutlinedButton(onPressed: _loadLogs, child: Text(l.retry)),++ ],++ ),++ );++ }++++ return Container(++ clipBehavior: Clip.antiAlias,++ decoration: BoxDecoration(++ color: cs.surfaceContainerHighest.withValues(alpha: 0.72),++ borderRadius: BorderRadius.circular(16),++ border: Border.all(color: cs.outlineVariant.withValues(alpha: 0.35)),++ ),++ child: visibleLogs.isEmpty++ ? Center(++ child: Text(++ _logs.isEmpty ? 'No server logs yet' : 'No logs match',++ style: tt.bodyMedium?.copyWith(++ color: cs.onSurfaceVariant.withValues(alpha: 0.7),++ ),++ ),++ )++ : LayoutBuilder(++ builder: (context, constraints) {++ final wide = constraints.maxWidth >= 760;++ return SelectionArea(++ child: Scrollbar(++ controller: _scrollController,++ thumbVisibility: wide,++ child: ListView.separated(++ controller: _scrollController,++ padding: const EdgeInsets.symmetric(vertical: 6),++ itemCount: visibleLogs.length,++ separatorBuilder: (_, __) => Divider(++ height: 1,++ thickness: 1,++ color: cs.outlineVariant.withValues(alpha: 0.18),++ ),++ itemBuilder: (_, index) =>++ _logRow(cs, tt, visibleLogs[index], wide: wide),++ ),++ ),++ );++ },++ ),++ );++ }++++ Widget _logRow(++ ColorScheme cs,++ TextTheme tt,++ _ServerLogEntry log, {++ required bool wide,++ }) {++ final levelColor = _levelColor(cs, log.level);++ final level = Container(++ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),++ decoration: BoxDecoration(++ color: levelColor.withValues(alpha: 0.12),++ borderRadius: BorderRadius.circular(6),++ ),++ child: Text(++ log.levelName,++ style: tt.labelSmall?.copyWith(++ color: levelColor,++ fontWeight: FontWeight.w700,++ fontSize: 10,++ ),++ ),++ );++++ if (!wide) {++ return Padding(++ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Row(++ children: [++ Expanded(++ child: Text(++ log.timestamp,++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant.withValues(alpha: 0.7),++ fontFamily: 'monospace',++ ),++ ),++ ),++ level,++ ],++ ),++ if (log.source.isNotEmpty) ...[++ const SizedBox(height: 3),++ Text(++ log.source,++ style: tt.labelSmall?.copyWith(++ color: cs.primary.withValues(alpha: 0.7),++ fontFamily: 'monospace',++ ),++ ),++ ],++ const SizedBox(height: 5),++ Text(++ log.message,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurface.withValues(alpha: 0.88),++ fontFamily: 'monospace',++ height: 1.35,++ ),++ ),++ ],++ ),++ );++ }++++ return Padding(++ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),++ child: Row(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ SizedBox(++ width: 176,++ child: Text(++ log.timestamp,++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant.withValues(alpha: 0.65),++ fontFamily: 'monospace',++ ),++ ),++ ),++ SizedBox(++ width: 82,++ child: Align(alignment: Alignment.topLeft, child: level),++ ),++ if (log.source.isNotEmpty)++ SizedBox(++ width: 150,++ child: Padding(++ padding: const EdgeInsets.only(right: 12),++ child: Text(++ log.source,++ maxLines: 2,++ overflow: TextOverflow.ellipsis,++ style: tt.labelSmall?.copyWith(++ color: cs.primary.withValues(alpha: 0.7),++ fontFamily: 'monospace',++ ),++ ),++ ),++ ),++ Expanded(++ child: Text(++ log.message,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurface.withValues(alpha: 0.88),++ fontFamily: 'monospace',++ height: 1.35,++ ),++ ),++ ),++ ],++ ),++ );++ }++++ Color _levelColor(ColorScheme cs, int level) {++ return switch (level) {++ 0 => cs.onSurfaceVariant,++ 1 => cs.secondary,++ 2 => cs.primary,++ 3 => Colors.amber.shade700,++ 4 => cs.error,++ 5 => Colors.red.shade900,++ 6 => cs.tertiary,++ _ => cs.onSurfaceVariant,++ };++ }++}++++class _ServerLogEntry {++ final String timestamp;++ final String source;++ final String message;++ final String levelName;++ final int level;++++ const _ServerLogEntry({++ required this.timestamp,++ required this.source,++ required this.message,++ required this.levelName,++ required this.level,++ });++++ static _ServerLogEntry? fromMap(Map<String, dynamic> raw) {++ final rawMessage = raw['message'];++ if (rawMessage == null) return null;++ final rawLevel = raw['level'];++ final level = rawLevel is num++ ? rawLevel.toInt()++ : int.tryParse(rawLevel?.toString() ?? '') ?? 0;++ return _ServerLogEntry(++ timestamp: raw['timestamp']?.toString() ?? '',++ source: raw['source']?.toString() ?? '',++ message: rawMessage.toString(),++ levelName: raw['levelName']?.toString().toUpperCase() ?? 'UNKNOWN',++ level: level,++ );++ }++++ String get identity => '$timestamp\u0000$level\u0000$source\u0000$message';++++ String get searchText =>++ '$timestamp $levelName $source $message'.toLowerCase();++++ String get exportLine {++ final sourceText = source.isEmpty ? '' : ' [$source]';++ return '$timestamp ${levelName.padRight(5)}$sourceText $message';++ }++}diff --cc lib/screens/app_shell.dartindex 65fe29d6,1884bcda..12115d3d--- a/lib/screens/app_shell.dart+++ b/lib/screens/app_shell.dart@@@ -4,14 -4,12 +4,16 @@@ import 'package:flutter/foundation.dartimport 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:provider/provider.dart';+import 'package:shared_preferences/shared_preferences.dart';++import 'package:url_launcher/url_launcher.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/chromecast_service.dart';import '../services/home_widget_service.dart';+import '../services/server_task_tracker.dart';import '../services/sleep_timer_service.dart';++import '../services/audiobookshelf_update_service.dart';import 'dart:io';import 'package:cached_network_image/cached_network_image.dart';import 'package:palette_generator/palette_generator.dart';@@@ -187,104 -167,8 +189,106 @@@ class _AppShellState extends State<AppS// work until the user actually visits those tabs.final List<Widget?> _pages = List<Widget?>.filled(5, null, growable: false);- void _openSearch() {- if (!mounted) return;+ // Desktop workspace content-pane navigator: full-page pushes land here so+ // the sidebar and now-playing bar stay visible around them.+ final _paneNavigatorKey = GlobalKey<NavigatorState>();+ late final _PaneNavigatorObserver _paneNavigatorObserver;+ bool _paneRouteOpen = false;+ bool _adminRouteOpen = false;+ bool _desktopWorkspaceWasActive = false;+ bool _desktopCollapseAllowed = false;+ bool _desktopCollapseCheckScheduled = false;+ bool _desktopSidebarPinned = false;+ int _desktopSidebarPreferenceGeneration = 0;+ ServerTaskTracker? _serverTaskTracker;+ Timer? _serverTaskRefreshTimer;+ bool _refreshingServerTasks = false;+ Object? _serverTaskPollingApi;+ bool _serverTaskPollingEnabled = false;+ bool _serverTaskPollingSyncScheduled = false;++ final AudiobookshelfUpdateController _serverUpdateController =++ AudiobookshelfUpdateController.instance;++ Future<void> _loadDesktopSidebarPreference() async {+ final generation = _desktopSidebarPreferenceGeneration;+ final prefs = await SharedPreferences.getInstance();+ final pinned = prefs.getBool(_desktopSidebarPinnedKey) ?? false;+ if (!mounted ||+ generation != _desktopSidebarPreferenceGeneration ||+ pinned == _desktopSidebarPinned) {+ return;+ }+ setState(() => _desktopSidebarPinned = pinned);+ }++ void _setDesktopSidebarPinned(bool pinned) {+ _desktopSidebarPreferenceGeneration++;+ if (pinned == _desktopSidebarPinned) return;+ setState(() => _desktopSidebarPinned = pinned);+ unawaited(_saveDesktopSidebarPreference(pinned));+ }++ Future<void> _saveDesktopSidebarPreference(bool pinned) async {+ final prefs = await SharedPreferences.getInstance();+ await prefs.setBool(_desktopSidebarPinnedKey, pinned);+ }++ void _startServerTaskRefreshTimer() {+ _serverTaskRefreshTimer?.cancel();+ _serverTaskRefreshTimer = null;+ if (!mounted || !AppPlatform.isWeb) return;+ final auth = context.read<AuthProvider>();+ if (!auth.isAdmin || auth.apiService == null || _serverTaskTracker == null) {+ return;+ }+ unawaited(_refreshServerTasks());+ _serverTaskRefreshTimer = Timer.periodic(const Duration(seconds: 3), (_) {+ unawaited(_refreshServerTasks());+ });+ }++ void _syncServerTaskPolling({+ required bool isAdmin,+ required Object? api,+ }) {+ final enabled = isAdmin && api != null && _serverTaskTracker != null;+ if (enabled == _serverTaskPollingEnabled &&+ identical(api, _serverTaskPollingApi)) {+ return;+ }+ _serverTaskPollingEnabled = enabled;+ _serverTaskPollingApi = api;+ if (_serverTaskPollingSyncScheduled) return;+ _serverTaskPollingSyncScheduled = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _serverTaskPollingSyncScheduled = false;+ if (!mounted) return;+ if (_serverTaskPollingEnabled && !_lifecycleBackgrounded) {+ _startServerTaskRefreshTimer();+ } else {+ _serverTaskRefreshTimer?.cancel();+ _serverTaskRefreshTimer = null;+ }+ });+ }++ Future<void> _refreshServerTasks() async {+ if (!mounted || _refreshingServerTasks) return;+ final tracker = _serverTaskTracker;+ final api = context.read<AuthProvider>().apiService;+ if (tracker == null || api == null) return;+ _refreshingServerTasks = true;+ try {+ await tracker.refresh(api);+ } finally {+ _refreshingServerTasks = false;+ }+ }++ void _openSearch() => unawaited(_openSearchAfterPaneReset());++ Future<void> _openSearchAfterPaneReset() async {+ if (!await _preparePaneForNavigation()) return;// If the user triggered Search while a pushed route (Downloads, Bookmarks,// Settings pages, etc.) is on top of the shell, pop back so the shell's// Library tab actually becomes visible.@@@ -499,20 -325,7 +503,21 @@@void initState() {super.initState();_instance = this;- if (!widget.startOnAbsorbing) _loadStartScreen();+ if (AppPlatform.isWeb) {+ _serverTaskTracker = ServerTaskTracker();++ _serverUpdateController.addListener(_onServerUpdateChanged);+ }+ _paneNavigatorObserver = _PaneNavigatorObserver(_syncPaneRouteState);+ DesktopWorkspaceNavigator.register(() => _paneNavigatorKey.currentState);+ DesktopWorkspaceNavigator.exitGuardChanges.addListener(+ _onDesktopExitGuardChanged,+ );+ unawaited(_loadDesktopSidebarPreference());+ if (AppPlatform.isWeb) {+ _currentIndex = 0;+ } else if (!widget.startOnAbsorbing) {+ _loadStartScreen();+ }_ensurePageBuilt(_currentIndex);_playerHadBook = _player.hasBook;_wasPlaying = _player.isPlaying;@@@ -620,6 -433,6 +625,10 @@@await UpdateDialog.show(context, info);}++ void _onServerUpdateChanged() {++ if (mounted) setState(() {});++ }++@overridevoid dispose() {_fadeController.dispose();@@@ -627,8 -440,6 +636,11 @@@_navBarAnimController.dispose();_player.removeListener(_onPlayerChanged);_cast.removeListener(_onCastChanged);+ _serverTaskRefreshTimer?.cancel();+ _serverTaskTracker?.dispose();++ if (AppPlatform.isWeb) {++ _serverUpdateController.removeListener(_onServerUpdateChanged);++ }PlayerSettings.settingsChanged.removeListener(_loadPodcastTabPrefs);try {context.read<LibraryProvider>().removeListener(_onLibraryChanged);@@@ -954,445 -702,54 +966,592 @@@@overrideWidget build(BuildContext context) {- return PopScope(- canPop: false,- onPopInvokedWithResult: (didPop, _) {- if (didPop) return;-- // If on Library tab with active search, clear search first- if (_currentIndex == 1 &&- _libraryKey.currentState?.isSearchActive == true) {- _libraryKey.currentState?.clearSearch();- return;+ if (AppPlatform.isWeb) {+ final taskAccess = context.select<AuthProvider, (bool, Object?)>(+ (auth) => (auth.isAdmin, auth.apiService),+ );+ _syncServerTaskPolling(isAdmin: taskAccess.$1, api: taskAccess.$2);+ }+ return LayoutBuilder(+ builder: (context, constraints) {+ final workspaceTier = AppPlatform.isWeb+ ? workspaceLayoutTierForWidth(constraints.maxWidth)+ : WorkspaceLayoutTier.mobile;+ final desktopRequested = workspaceTier != WorkspaceLayoutTier.mobile;+ var useDesktopWorkspace = desktopRequested;+ if (desktopRequested) {+ _desktopWorkspaceWasActive = true;+ _desktopCollapseAllowed = false;+ } else if (_desktopWorkspaceWasActive && !_desktopCollapseAllowed) {+ useDesktopWorkspace = true;+ _scheduleDesktopWorkspaceCollapseCheck();+ } else {+ _desktopWorkspaceWasActive = false;+ _desktopCollapseAllowed = false;}+ return PopScope(+ canPop: false,+ onPopInvokedWithResult: _handleBack,+ child: useDesktopWorkspace+ ? _buildDesktopWorkspace(+ context,+ allowPinnedSidebar: desktopRequested &&+ usesExtendedDesktopSidebar(workspaceTier),+ )+ : Scaffold(+ body: _buildPageStack(context),+ bottomNavigationBar: _buildBottomNav(context),+ ),+ );+ },+ );+ }- // If already on Absorbing tab, require double-back to exit- if (_currentIndex == 2) {- final now = DateTime.now();- if (_lastBackPress != null &&- now.difference(_lastBackPress!) < const Duration(seconds: 2)) {- SystemChannels.platform.invokeMethod('SystemNavigator.pop', true);- return;- }- _lastBackPress = now;- showOverlayToast(- context,- AppLocalizations.of(context)!.appShellPressBackToExit,- icon: Icons.exit_to_app_rounded,+ void _handleBack(bool didPop, Object? _) {+ if (didPop) return;++ if (AppPlatform.isWeb) {+ final pane = _paneNavigatorKey.currentState;+ if (pane != null && pane.canPop()) {+ unawaited(pane.maybePop());+ return;+ }+ if (_currentIndex == 1 &&+ _libraryKey.currentState?.isSearchActive == true) {+ _libraryKey.currentState?.clearSearch();+ return;+ }+ if (_currentIndex != 0) _navigateTo(0);+ return;+ }++ if (_currentIndex == 1 &&+ _libraryKey.currentState?.isSearchActive == true) {+ _libraryKey.currentState?.clearSearch();+ return;+ }++ if (_currentIndex == 2) {+ final now = DateTime.now();+ if (_lastBackPress != null &&+ now.difference(_lastBackPress!) < const Duration(seconds: 2)) {+ SystemChannels.platform.invokeMethod('SystemNavigator.pop', true);+ return;+ }+ _lastBackPress = now;+ showOverlayToast(+ context,+ AppLocalizations.of(context)!.appShellPressBackToExit,+ icon: Icons.exit_to_app_rounded,+ );+ return;+ }++ _switchToAbsorbing();+ }++ Widget _buildPageStack(BuildContext context) {+ return FadeTransition(+ opacity: _fadeController,+ child: IndexedStack(+ index: _currentIndex,+ children: List<Widget>.generate(+ _pages.length,+ (i) => _pages[i] ?? const SizedBox.shrink(),+ ),+ ),+ );+ }++ Widget _buildDesktopWorkspace(+ BuildContext context, {+ required bool allowPinnedSidebar,+ }) {+ final lib = context.watch<LibraryProvider>();+ final podcastsShown = _podcastsShown(lib);+ final destinations = _buildDestinations(context, podcastsShown);+ final sidebarPinned = allowPinnedSidebar && _desktopSidebarPinned;++ return Scaffold(+ body: DesktopSidebarLayout(+ pinned: sidebarPinned,+ canPin: allowPinnedSidebar,+ onPinnedChanged: _setDesktopSidebarPinned,+ sidebarBuilder: (sidebarContext, extended) => _buildDesktopSidebar(+ sidebarContext,+ lib: lib,+ podcastsShown: podcastsShown,+ destinations: destinations,+ extended: extended,+ ),+ child: LayoutBuilder(+ // The MediaQuery override sits outside the pane Navigator so pushed+ // pages also lay out against the pane, not the window. The tab stack+ // is declarative so it keeps rebuilding below imperative routes.+ builder: (context, constraints) => MediaQuery(+ data: MediaQuery.of(context).copyWith(+ size: Size(constraints.maxWidth, constraints.maxHeight),+ ),+ child: DesktopWorkspaceScope(+ child: ClipRect(+ child: Navigator(+ key: _paneNavigatorKey,+ observers: [_paneNavigatorObserver],+ onDidRemovePage: (page) {},+ pages: [+ MaterialPage(child: _buildPageStack(context)),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ bottomNavigationBar: shouldShowDesktopNowPlayingBar(+ _currentIndex,+ paneRouteOpen: _paneRouteOpen,+ )+ ? DesktopNowPlayingBar(+ player: _player,+ library: lib,+ onOpenNowPlaying: _switchToAbsorbing,+ )+ : null,+ );+ }++ Widget _buildDesktopSidebar(+ BuildContext context, {+ required LibraryProvider lib,+ required bool podcastsShown,+ required List<NavigationDestination> destinations,+ required bool extended,+ }) {+ final theme = Theme.of(context);+ final cs = theme.colorScheme;+ final l = AppLocalizations.of(context)!;+ final auth = context.watch<AuthProvider>();+ final libraryName =+ lib.selectedLibrary?['name'] as String? ?? l.libraryFallback;+ final username = auth.username?.trim();+ final accountName = username == null || username.isEmpty+ ? 'Account'+ : username;+ final serverUrl = auth.serverUrl ?? '';+ final parsedServer = Uri.tryParse(serverUrl);+ final serverLabel = parsedServer?.host.isNotEmpty == true+ ? parsedServer!.host+ : serverUrl;++ final serverVersion = auth.serverVersion?.trim();++ if (serverVersion != null &&++ serverVersion.isNotEmpty &&++ _serverUpdateController.shouldCheck(serverVersion)) {++ WidgetsBinding.instance.addPostFrameCallback((_) {++ if (mounted) {++ unawaited(++ _serverUpdateController.check(currentVersion: serverVersion),+ );++ }++ });++ }+ final taskTracker = _serverTaskTracker;+ void openSearch() => _openSearch();++ Widget buildBranding(List<ServerTask> tasks) {+ final showTasks = auth.isAdmin && tasks.isNotEmpty && taskTracker != null;- return Row(- mainAxisAlignment: extended- ? MainAxisAlignment.start- : MainAxisAlignment.center,- children: [- if (!extended && showTasks)- AdminTaskIndicator(- tasks: tasks,- onPressed: () => showAdminTasksSheet(context, taskTracker),- )- else- Container(- width: 38,- height: 38,- decoration: BoxDecoration(- color: cs.primaryContainer,- borderRadius: BorderRadius.circular(12),- ),- child: Icon(- Icons.graphic_eq_rounded,- color: cs.onPrimaryContainer,- ),- ),- if (extended) ...[- const SizedBox(width: 12),- Expanded(- child: Text(- l.appTitle,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: theme.textTheme.titleMedium?.copyWith(- fontWeight: FontWeight.w800,- letterSpacing: 1.4,- ),- ),- ),- if (showTasks)- AdminTaskIndicator(++ return DesktopSidebarBranding(++ extended: extended,++ leading: showTasks++ ? AdminTaskIndicator(+ tasks: tasks,+ onPressed: () => showAdminTasksSheet(context, taskTracker),++ )++ : Container(++ width: 38,++ height: 38,++ decoration: BoxDecoration(++ color: cs.primaryContainer,++ borderRadius: BorderRadius.circular(12),++ ),++ child: Icon(++ Icons.graphic_eq_rounded,++ color: cs.onPrimaryContainer,++ ),+ ),- ],- ],++ title: l.appTitle,++ titleStyle: theme.textTheme.titleMedium?.copyWith(++ fontWeight: FontWeight.w800,++ letterSpacing: 1.4,++ ),+ );+ }++ void openAdmin() {+ if (_adminRouteOpen) return;+ final navigator = _paneNavigatorKey.currentState;+ if (navigator == null) return;+ _adminRouteOpen = true;+ unawaited(navigator+ .push(MaterialPageRoute<void>(+ builder: (_) => AdminScreen(taskTracker: _serverTaskTracker),+ ))+ .whenComplete(() => _adminRouteOpen = false));+ }++ void openAccountMenu() {+ final wasBuilt = _pages[4] != null;+ _ensurePageBuilt(4);++ final state = _settingsKey.currentState;+ if (state != null) {+ state.showAccountMenu();+ return;+ }++ if (!wasBuilt) setState(() {});+ var attempts = 0;+ void tryOpen() {+ if (!mounted) return;+ final settings = _settingsKey.currentState;+ if (settings != null) {+ settings.showAccountMenu();return;}+ if (++attempts < 10) {+ WidgetsBinding.instance.addPostFrameCallback((_) => tryOpen());+ }+ }- // From any other tab, go to Absorbing- _switchToAbsorbing();- },- child: Scaffold(- body: FadeTransition(- opacity: _fadeController,- child: IndexedStack(- index: _currentIndex,- children: List<Widget>.generate(- _pages.length,- (i) => _pages[i] ?? const SizedBox.shrink(),+ WidgetsBinding.instance.addPostFrameCallback((_) => tryOpen());+ }++ return SafeArea(+ child: SizedBox(+ width: extended+ ? DesktopCollapsibleSidebar.expandedWidth+ : DesktopCollapsibleSidebar.collapsedWidth,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: extended- ? const EdgeInsets.fromLTRB(20, 18, 60, 12)- : const EdgeInsets.fromLTRB(12, 18, 12, 12),++ ? const EdgeInsets.fromLTRB(12, 13, 60, 7)++ : const EdgeInsets.fromLTRB(12, 13, 12, 7),+ child: auth.isAdmin && taskTracker != null+ ? ListenableBuilder(+ listenable: taskTracker,+ builder: (_, __) => buildBranding(+ taskTracker.visibleTasks,+ ),+ )+ : buildBranding(const []),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),+ child: Tooltip(+ message: l.switchLibraryTooltip,+ child: InkWell(+ onTap: lib.libraries.length > 1+ ? () => showLibraryPickerSheet(context, lib)+ : null,+ borderRadius: BorderRadius.circular(12),+ child: Container(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 10,+ ),+ decoration: BoxDecoration(+ color: cs.surfaceContainerLow,+ borderRadius: BorderRadius.circular(12),+ border: Border.all(+ color: cs.outlineVariant.withValues(alpha: 0.45),+ ),+ ),+ child: Row(+ mainAxisAlignment: extended+ ? MainAxisAlignment.start+ : MainAxisAlignment.center,+ children: [+ Icon(+ Icons.library_books_rounded,+ size: 20,+ color: cs.primary,+ ),+ if (extended) ...[+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ libraryName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: theme.textTheme.labelLarge,+ ),+ ),+ if (lib.libraries.length > 1)+ const Icon(Icons.expand_more_rounded, size: 20),+ ],+ ],+ ),+ ),+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12),+ child: extended+ ? FilledButton.tonalIcon(+ onPressed: openSearch,+ icon: const Icon(Icons.search_rounded, size: 20),+ label: Text(l.search),+ style: FilledButton.styleFrom(+ alignment: Alignment.centerLeft,+ minimumSize: const Size.fromHeight(44),+ ),+ )+ : Tooltip(+ message: l.search,+ child: IconButton.filledTonal(+ onPressed: openSearch,+ icon: const Icon(Icons.search_rounded, size: 20),+ ),+ ),+ ),+ const SizedBox(height: 8),+ Expanded(+ child: NavigationRail(+ extended: extended,+ minWidth: 72,+ minExtendedWidth: 248,+ groupAlignment: -1,+ backgroundColor: Colors.transparent,+ selectedIndex: _selectedDest(lib, podcastsShown),+ onDestinationSelected: (dest) =>+ _selectDestination(dest, podcastsShown),+ destinations: [+ for (final destination in destinations)+ NavigationRailDestination(+ icon: destination.icon,+ selectedIcon: destination.selectedIcon,+ label: Text(destination.label),+ ),+ ],+ ),+ ),+ if (auth.isAdmin)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12),+ child: extended+ ? TextButton.icon(+ onPressed: openAdmin,+ icon: const Icon(Icons.admin_panel_settings_outlined),+ label: Text(l.serverAdmin),+ style: TextButton.styleFrom(+ alignment: Alignment.centerLeft,+ minimumSize: const Size.fromHeight(42),+ ),+ )+ : Tooltip(+ message: l.serverAdmin,+ child: IconButton(+ onPressed: openAdmin,+ icon: const Icon(+ Icons.admin_panel_settings_outlined,+ ),+ ),+ ),+ ),++ if (serverVersion != null && serverVersion.isNotEmpty)++ _buildDesktopServerVersion(++ context,++ version: serverVersion,++ extended: extended,++ ),+ Divider(+ height: 1,+ color: cs.outlineVariant.withValues(alpha: 0.45),+ ),+ DesktopAccountButton(+ accountName: accountName,+ serverLabel: serverLabel,+ extended: extended,+ onPressed: openAccountMenu,+ ),+ ],+ ),+ ),+ );+ }+++ Widget _buildDesktopServerVersion(++ BuildContext context, {++ required String version,++ required bool extended,++ }) {++ final theme = Theme.of(context);++ final cs = theme.colorScheme;++ final l = AppLocalizations.of(context)!;++ final checkedFor = _serverUpdateController.checkedFor;++ final isCurrentVersion = checkedFor == version;++ final update = isCurrentVersion ? _serverUpdateController.update : null;++ final isChecking = isCurrentVersion && _serverUpdateController.isChecking;++ final versionLabel = l.serverVersionLabel(version);++ final updateLabel = update == null++ ? null++ : l.serverUpdateAvailable(update.latestVersion);++ final tooltip = updateLabel == null++ ? versionLabel++ : '$versionLabel\n$updateLabel';++++ void openUpdate() {++ if (update == null) return;++ unawaited(++ launchUrl(++ Uri.parse(update.releaseUrl),++ mode: LaunchMode.externalApplication,++ ),++ );++ }++++ return Padding(++ padding: const EdgeInsets.fromLTRB(8, 2, 8, 6),++ child: Tooltip(++ message: tooltip,++ child: Material(++ color: update == null++ ? Colors.transparent++ : cs.primaryContainer.withValues(alpha: 0.45),++ borderRadius: BorderRadius.circular(10),++ clipBehavior: Clip.antiAlias,++ child: InkWell(++ onTap: update == null ? null : openUpdate,++ borderRadius: BorderRadius.circular(10),++ child: Padding(++ padding: extended++ ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8)++ : const EdgeInsets.symmetric(horizontal: 4, vertical: 7),++ child: extended++ ? Row(++ children: [++ Icon(++ update == null++ ? Icons.dns_outlined++ : Icons.system_update_alt_rounded,++ size: 18,++ color: update == null++ ? cs.onSurfaceVariant++ : cs.primary,++ ),++ const SizedBox(width: 10),++ Expanded(++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ Text(++ versionLabel,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: theme.textTheme.bodySmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ if (updateLabel != null)++ Text(++ updateLabel,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: theme.textTheme.labelSmall?.copyWith(++ color: cs.primary,++ fontWeight: FontWeight.w600,++ ),++ ),++ ],++ ),++ ),++ if (isChecking)++ SizedBox(++ width: 14,++ height: 14,++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: cs.onSurfaceVariant,++ ),++ )++ else if (update != null)++ Icon(++ Icons.open_in_new_rounded,++ size: 16,++ color: cs.primary,++ ),++ ],++ )++ : Column(++ mainAxisSize: MainAxisSize.min,++ children: [++ if (isChecking)++ SizedBox(++ width: 18,++ height: 18,++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: cs.onSurfaceVariant,++ ),++ )++ else++ Icon(++ update == null++ ? Icons.dns_outlined++ : Icons.system_update_alt_rounded,++ size: 18,++ color: update == null++ ? cs.onSurfaceVariant++ : cs.primary,++ ),++ const SizedBox(height: 3),++ Text(++ version,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: theme.textTheme.labelSmall?.copyWith(++ color: update == null++ ? cs.onSurfaceVariant++ : cs.primary,++ fontSize: 10,++ fontWeight: update == null++ ? FontWeight.w500++ : FontWeight.w700,++ ),++ ),++ ],++ ),+ ),+ ),+ ),- bottomNavigationBar: _buildBottomNav(context),+ ),+ );+ }++ void _selectDestination(int dest, bool podcastsShown) =>+ unawaited(_selectDestinationAfterPaneReset(dest, podcastsShown));++ Future<void> _selectDestinationAfterPaneReset(+ int dest,+ bool podcastsShown,+ ) async {+ if (!await _preparePaneForNavigation()) return;+ final lib = context.read<LibraryProvider>();+ final page = _pageForDest(dest, podcastsShown);+ if (page == 1 &&+ _currentIndex == 1 &&+ dest == _selectedDest(lib, podcastsShown) &&+ _libraryKey.currentState?.isSearchActive == true) {+ _libraryKey.currentState?.clearSearch();+ return;+ }+ _syncTabLibrary(dest, podcastsShown);+ _navigateToPrepared(page);+ if (page >= 0 && page <= 3) _refreshDataForTab(page);+ }+Widget _buildBottomNav(BuildContext context) {// Determine the *correct* notifier for the active tab so we can detect// both "no listener" and "listener attached to the wrong tab" — thediff --cc lib/screens/home_screen.dartindex 4a610291,1e947bdd..2ab1dfe7--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@@ -23,8 -23,7 +23,10 @@@ import '../widgets/playlist_detail_sheeimport '../widgets/collection_detail_sheet.dart';import '../widgets/section_detail_sheet.dart';import '../widgets/feature_hint.dart';+import '../widgets/hover_cover_actions.dart';import '../widgets/offline_status_icon.dart';++import '../widgets/desktop_batch_actions.dart';++import '../widgets/desktop_cover_size_control.dart';import '../widgets/scroll_reveal.dart';import '../widgets/section_labels.dart';import 'app_shell.dart';@@@ -41,10 -37,10 +43,133 @@@ class HomeScreen extends StatefulWidgeState<HomeScreen> createState() => HomeScreenState();}--class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin {++class HomeScreenState extends State<HomeScreen>++ with SingleTickerProviderStateMixin {final _player = AudioPlayerService();bool _hideEbookOnly = false;bool _rectangleCovers = false;++ int _bookshelfCoverSize = 120;++ bool _selectionMode = false;++ bool _batchActionBusy = false;++ final Set<String> _selectedItemIds = {};++++ double get _desktopShelfScale => 1.2 * (_bookshelfCoverSize / 120);++++ void _resetSelectionState() {++ _selectionMode = false;++ _batchActionBusy = false;++ _selectedItemIds.clear();++ }++++ void _clearSelection() {++ if (!_selectionMode && _selectedItemIds.isEmpty) return;++ setState(_resetSelectionState);++ }++++ void _toggleSelection(Map<String, dynamic> item) {++ final itemId = item['id'] as String?;++ if (itemId == null) return;++ setState(() {++ _selectionMode = true;++ if (!_selectedItemIds.add(itemId)) _selectedItemIds.remove(itemId);++ });++ }++++ Map<String, dynamic>? _selectableHomeItem(++ dynamic entity, {++ required String sectionType,++ }) {++ if (sectionType == 'author' ||++ sectionType == 'authors' ||++ sectionType == 'series' ||++ sectionType == 'episode') {++ return null;++ }++ if (entity is! Map<String, dynamic>) return null;++ var item = entity;++ if (sectionType == 'playlist') {++ if (entity['episodeId'] != null) return null;++ final nested = entity['libraryItem'];++ if (nested is! Map<String, dynamic>) return null;++ item = nested;++ }++ if (item['recentEpisode'] != null || item['id'] is! String) return null;++ return item;++ }++++ List<Map<String, dynamic>> _selectableHomeItems() {++ final byId = <String, Map<String, dynamic>>{};++ for (final item in _cachedClItems ?? const <dynamic>[]) {++ final selectable = _selectableHomeItem(item, sectionType: 'book');++ final id = selectable?['id'] as String?;++ if (id != null) byId[id] = selectable!;++ }++ for (final section in _cachedSections ?? const <Map<String, dynamic>>[]) {++ final id = section['id'] as String? ?? '';++ if (id == 'continue-listening') continue;++ final type = id.startsWith('playlist:')++ ? 'playlist'++ : id.startsWith('collection:')++ ? 'collection'++ : (section['type'] as String? ?? 'book');++ final entities = _filterEbookOnly(++ section['entities'] as List<dynamic>? ?? const [],++ sectionType: section['type'] as String?,++ );++ for (final entity in entities) {++ final selectable = _selectableHomeItem(entity, sectionType: type);++ final itemId = selectable?['id'] as String?;++ if (itemId != null) byId[itemId] = selectable!;++ }++ }++ return byId.values.toList();++ }++++ void _toggleSelectAll() {++ final ids = _selectableHomeItems()++ .map((item) => item['id'] as String)++ .toSet();++ setState(() {++ _selectionMode = true;++ if (ids.isNotEmpty && _selectedItemIds.containsAll(ids)) {++ _selectedItemIds.removeAll(ids);++ } else {++ _selectedItemIds.addAll(ids);++ }++ });++ }++++ Future<void> _runBatchAction(Future<bool?> Function() action) async {++ if (_batchActionBusy) return;++ final visibleIds = _selectableHomeItems()++ .map((item) => item['id'] as String)++ .toSet();++ setState(() {++ _selectedItemIds.retainAll(visibleIds);++ if (_selectedItemIds.isEmpty) {++ _resetSelectionState();++ } else {++ _batchActionBusy = true;++ }++ });++ if (_selectedItemIds.isEmpty) return;++ final success = await action();++ if (!mounted) return;++ setState(() {++ _batchActionBusy = false;++ if (success == true) _resetSelectionState();++ });++ }++++ void _changeBookshelfCoverSize(int direction) {++ final sizes = PlayerSettings.bookshelfCoverSizes;++ final currentIndex = sizes.indexOf(_bookshelfCoverSize);++ final nextIndex = (currentIndex + direction).clamp(0, sizes.length - 1);++ final next = sizes[nextIndex];++ if (next == _bookshelfCoverSize) return;++ setState(() => _bookshelfCoverSize = next);++ PlayerSettings.setBookshelfCoverSize(next);++ }// ── Scroll-to-hide bars ──/// Continuous 0..1 reveal value the AppShell mirrors onto the bottom nav.@@@ -92,16 -88,16 +217,21 @@@String? _coversLibraryId;Future<void> _loadSettings() async {-- final libId = mounted ? context.read<LibraryProvider>().selectedLibraryId : null;++ final libId = mounted++ ? context.read<LibraryProvider>().selectedLibraryId++ : null;_coversLibraryId = libId;final results = await Future.wait([PlayerSettings.getHideEbookOnly(),PlayerSettings.getRectangleCoversFor(libId),++ PlayerSettings.getBookshelfCoverSize(),]);-- if (mounted) setState(() {-- _hideEbookOnly = results[0];-- _rectangleCovers = results[1];-- });++ if (mounted)++ setState(() {++ _hideEbookOnly = results[0] as bool;++ _rectangleCovers = results[1] as bool;++ _bookshelfCoverSize = results[2] as int;++ });}@override@@@ -160,8 -156,8 +290,9 @@@for (final section in sections) {if (section['id'] == 'continue-listening') {clItems = _filterEbookOnly(-- (section['entities'] as List<dynamic>?) ?? [],-- sectionType: section['type'] as String?);++ (section['entities'] as List<dynamic>?) ?? [],++ sectionType: section['type'] as String?,++ );break;}}@@@ -244,13 -224,13 +375,18 @@@final scaffoldBg = Theme.of(context).scaffoldBackgroundColor;final lowerFade = Color.lerp(cs.surface, scaffoldBg, 0.55) ?? scaffoldBg;final lib = context.watch<LibraryProvider>();++ final selectionAvailable = desktop && !lib.isOffline;++ if (!selectionAvailable && _selectionMode) _resetSelectionState();final allLibraries = lib.libraries;-- final libraryName = lib.selectedLibrary?['name'] as String? ?? l.libraryFallback;++ final libraryName =++ lib.selectedLibrary?['name'] as String? ?? l.libraryFallback;// Cover shape can differ per library; re-resolve after a library switch.if (lib.selectedLibraryId != _coversLibraryId) {_coversLibraryId = lib.selectedLibraryId;++ _resetSelectionState();PlayerSettings.getRectangleCoversFor(_coversLibraryId).then((v) {-- if (mounted && v != _rectangleCovers) setState(() => _rectangleCovers = v);++ if (mounted && v != _rectangleCovers)++ setState(() => _rectangleCovers = v);});}if (lib.isLoading) {@@@ -262,346 -242,313 +398,478 @@@} else {_refreshFilteredCache(lib);}++ final selectableHomeItems = selectionAvailable++ ? _selectableHomeItems()++ : const <Map<String, dynamic>>[];++ if (_selectionMode) {++ _selectedItemIds.retainAll(++ selectableHomeItems.map((item) => item['id'] as String).toSet(),++ );++ }return Scaffold(backgroundColor: scaffoldBg,body: Container(-- decoration: flatNotifier.value ? null : BoxDecoration(-- gradient: LinearGradient(-- begin: Alignment.topCenter,-- end: Alignment.bottomCenter,-- stops: const [0.0, 0.22, 0.72, 1.0],-- colors: [-- cs.primary.withValues(alpha: gradientIntensityNotifier.value),-- cs.surface,-- lowerFade,-- scaffoldBg,-- ],-- ),-- ),++ decoration: flatNotifier.value++ ? null++ : BoxDecoration(++ gradient: LinearGradient(++ begin: Alignment.topCenter,++ end: Alignment.bottomCenter,++ stops: const [0.0, 0.22, 0.72, 1.0],++ colors: [++ cs.primary.withValues(++ alpha: gradientIntensityNotifier.value,++ ),++ cs.surface,++ lowerFade,++ scaffoldBg,++ ],++ ),++ ),child: SafeArea(child: NotificationListener<ScrollNotification>(onNotification: (n) {if (n is ScrollEndNotification) _revealDriver.settle();return false;},- child: RefreshIndicator(- onRefresh: () async {- await lib.refresh();- },- child: CustomScrollView(- controller: _scrollController,- slivers: [- // ── Top bar: ABSORB title + page name ──- SliverToBoxAdapter(- child: AbsorbPageHeader(- title: l.homeTitle,- trailing: OfflineStatusIcon(- onTapWhenOnline: () {- lib.setManualOffline(true);- final dl = DownloadService();- final player = AudioPlayerService();- final itemId = player.currentItemId;- final epId = player.currentEpisodeId;- final dlKey = epId != null && itemId != null- ? '$itemId-$epId'- : itemId;- if (dlKey == null || !dl.isDownloaded(dlKey)) {- player.stop();- }- },- ),- actions: [- if (allLibraries.length > 1)- Material(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(20),- clipBehavior: Clip.antiAlias,- child: InkWell(- onTap: () => showLibraryPickerSheet(context, lib),+ child: _refreshWrapper(- desktop: desktop,- lib: lib,- child: CustomScrollView(- controller: _scrollController,- slivers: [- // ── Top bar: ABSORB title + page name ──- SliverToBoxAdapter(- child: AbsorbPageHeader(- title: l.homeTitle,- showBranding: !desktop,- trailing: OfflineStatusIcon(- onTapWhenOnline: () {- lib.setManualOffline(true);- final dl = DownloadService();- final player = AudioPlayerService();- final itemId = player.currentItemId;- final epId = player.currentEpisodeId;- final dlKey = epId != null && itemId != null- ? '$itemId-$epId'- : itemId;- if (dlKey == null || !dl.isDownloaded(dlKey)) {- player.stop();- }- },- ),- actions: [- if (allLibraries.length > 1)- Material(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(20),- clipBehavior: Clip.antiAlias,- child: InkWell(- onTap: () => showLibraryPickerSheet(context, lib),++ desktop: desktop,++ lib: lib,++ child: CustomScrollView(++ controller: _scrollController,++ slivers: [++ // ── Top bar: ABSORB title + page name ──++ SliverToBoxAdapter(++ child: AbsorbPageHeader(++ title: l.homeTitle,++ showBranding: !desktop,++ trailing: OfflineStatusIcon(++ onTapWhenOnline: () {++ lib.setManualOffline(true);++ final dl = DownloadService();++ final player = AudioPlayerService();++ final itemId = player.currentItemId;++ final epId = player.currentEpisodeId;++ final dlKey = epId != null && itemId != null++ ? '$itemId-$epId'++ : itemId;++ if (dlKey == null || !dl.isDownloaded(dlKey)) {++ player.stop();++ }++ },++ ),++ actions: [++ if (allLibraries.length > 1)++ Material(++ color: cs.onSurface.withValues(alpha: 0.06),borderRadius: BorderRadius.circular(20),-- child: Container(-- padding: const EdgeInsets.symmetric(-- horizontal: 10, vertical: 5),-- decoration: BoxDecoration(-- borderRadius: BorderRadius.circular(20),-- border: Border.all(-- color:-- cs.onSurface.withValues(alpha: 0.08)),-- ),-- child: SizedBox(-- height: 20,-- child: Row(-- mainAxisSize: MainAxisSize.min,-- children: [-- Icon(++ clipBehavior: Clip.antiAlias,++ child: InkWell(++ onTap: () => showLibraryPickerSheet(context, lib),++ borderRadius: BorderRadius.circular(20),++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 10,++ vertical: 5,++ ),++ decoration: BoxDecoration(++ borderRadius: BorderRadius.circular(20),++ border: Border.all(++ color: cs.onSurface.withValues(alpha: 0.08),++ ),++ ),++ child: SizedBox(++ height: 20,++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(lib.isPodcastLibrary? Icons.podcasts_rounded: Icons.auto_stories_rounded,size: 18,-- color: cs.onSurfaceVariant),-- const SizedBox(width: 6),-- ConstrainedBox(-- constraints:-- const BoxConstraints(maxWidth: 140),-- child: Text(libraryName,++ color: cs.onSurfaceVariant,++ ),++ const SizedBox(width: 6),++ ConstrainedBox(++ constraints: const BoxConstraints(++ maxWidth: 140,++ ),++ child: Text(++ libraryName,style: TextStyle(-- fontSize: 13,-- fontWeight: FontWeight.w600,-- color: cs.onSurfaceVariant),++ fontSize: 13,++ fontWeight: FontWeight.w600,++ color: cs.onSurfaceVariant,++ ),overflow: TextOverflow.ellipsis,-- maxLines: 1),-- ),-- const SizedBox(width: 4),-- Icon(Icons.unfold_more_rounded,-- size: 18, color: cs.onSurfaceVariant),-- ],++ maxLines: 1,++ ),++ ),++ const SizedBox(width: 4),++ Icon(++ Icons.unfold_more_rounded,++ size: 18,++ color: cs.onSurfaceVariant,++ ),++ ],++ ),),),),),-- ),- if (desktop && !lib.isOffline)- Tooltip(- message: l.refreshTooltip,- child: GestureDetector(- onTap: () => lib.refresh(),- if (!lib.isOffline)- GestureDetector(- onTap: () => HomeCustomizeSheet.show(context),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(20),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),++ if (desktop && !lib.isOffline)++ Tooltip(++ message: l.refreshTooltip,++ child: GestureDetector(++ onTap: () {++ _clearSelection();++ lib.refresh();++ },++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 8,++ vertical: 5,++ ),++ decoration: BoxDecoration(++ color: cs.onSurface.withValues(alpha: 0.06),++ borderRadius: BorderRadius.circular(20),++ border: Border.all(++ color: cs.onSurface.withValues(alpha: 0.08),++ ),++ ),++ child: SizedBox(++ height: 20,++ child: Icon(++ Icons.refresh_rounded,++ size: 18,++ color: cs.onSurfaceVariant,++ ),++ ),++ ),+ ),- child: SizedBox(height: 20, child: Icon(Icons.tune_rounded, size: 18, color: cs.onSurfaceVariant)),+ ),- ),- ],++ if (desktop && !lib.isOffline)++ Tooltip(++ message: _selectionMode++ ? l.downloadsCancelSelection++ : 'Select items',++ child: IconButton(++ onPressed: _selectionMode++ ? _clearSelection++ : () => setState(() => _selectionMode = true),++ icon: Icon(++ _selectionMode++ ? Icons.close_rounded++ : Icons.library_add_check_rounded,++ ),++ ),++ ),++ if (!lib.isOffline)++ GestureDetector(++ onTap: () => HomeCustomizeSheet.show(context),+ child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),++ padding: const EdgeInsets.symmetric(++ horizontal: 8,++ vertical: 5,++ ),+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(20),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),++ border: Border.all(++ color: cs.onSurface.withValues(alpha: 0.08),++ ),++ ),++ child: SizedBox(++ height: 20,++ child: Icon(++ Icons.tune_rounded,++ size: 18,++ color: cs.onSurfaceVariant,++ ),+ ),- child: SizedBox(height: 20, child: Icon(Icons.refresh_rounded, size: 18, color: cs.onSurfaceVariant)),- ),- ),- ),- if (!lib.isOffline)- GestureDetector(- onTap: () => HomeCustomizeSheet.show(context),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(20),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),+ ),- child: SizedBox(height: 20, child: Icon(Icons.tune_rounded, size: 18, color: cs.onSurfaceVariant)),+ ),- ),- ],++ ],++ ),),-- ),-- // (Continue Listening is now rendered in the generic sections loop below)++ // (Continue Listening is now rendered in the generic sections loop below)-- // ── Loading shimmer ──-- if (lib.isLoading) ...[-- const SliverToBoxAdapter(child: SizedBox(height: 16)),-- const SliverToBoxAdapter(child: ShimmerHeroCard()),-- const SliverToBoxAdapter(child: SizedBox(height: 20)),-- const SliverToBoxAdapter(child: ShimmerBookRow()),-- const SliverToBoxAdapter(child: SizedBox(height: 8)),-- const SliverToBoxAdapter(child: ShimmerBookRow()),-- ],++ // ── Loading shimmer ──++ if (lib.isLoading) ...[++ const SliverToBoxAdapter(child: SizedBox(height: 16)),++ const SliverToBoxAdapter(child: ShimmerHeroCard()),++ const SliverToBoxAdapter(child: SizedBox(height: 20)),++ const SliverToBoxAdapter(child: ShimmerBookRow()),++ const SliverToBoxAdapter(child: SizedBox(height: 8)),++ const SliverToBoxAdapter(child: ShimmerBookRow()),++ ],-- // ── Error ──-- if (!lib.isLoading &&-- lib.errorMessage != null &&-- lib.personalizedSections.isEmpty)-- SliverFillRemaining(-- child: Center(-- child: Column(-- mainAxisSize: MainAxisSize.min,-- children: [-- Icon(Icons.cloud_off_rounded,-- size: 48, color: cs.error),-- const SizedBox(height: 12),-- Text(lib.errorMessage!,-- style: tt.bodyLarge?.copyWith(color: cs.error)),-- const SizedBox(height: 16),-- FilledButton.tonal(++ // ── Error ──++ if (!lib.isLoading &&++ lib.errorMessage != null &&++ lib.personalizedSections.isEmpty)++ SliverFillRemaining(++ child: Center(++ child: Column(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(++ Icons.cloud_off_rounded,++ size: 48,++ color: cs.error,++ ),++ const SizedBox(height: 12),++ Text(++ lib.errorMessage!,++ style: tt.bodyLarge?.copyWith(color: cs.error),++ ),++ const SizedBox(height: 16),++ FilledButton.tonal(onPressed: lib.refresh,-- child: Text(l.retry)),-- ],++ child: Text(l.retry),++ ),++ ],++ ),),),-- ),-- // ── Empty ──-- if (!lib.isLoading &&-- lib.errorMessage == null &&-- lib.personalizedSections.isEmpty &&-- (lib.libraries.isNotEmpty || lib.isOffline))-- SliverFillRemaining(-- child: Center(-- child: Column(-- mainAxisSize: MainAxisSize.min,-- children: [-- Icon(-- lib.isOffline-- ? Icons.download_for_offline_outlined-- : Icons.library_music_outlined,-- size: 48,-- color: cs.onSurfaceVariant,-- ),-- const SizedBox(height: 12),-- Text(-- lib.isOffline-- ? l.noDownloadedBooks-- : l.yourLibraryIsEmpty,-- style: tt.bodyLarge?.copyWith(++ // ── Empty ──++ if (!lib.isLoading &&++ lib.errorMessage == null &&++ lib.personalizedSections.isEmpty &&++ (lib.libraries.isNotEmpty || lib.isOffline))++ SliverFillRemaining(++ child: Center(++ child: Column(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(++ lib.isOffline++ ? Icons.download_for_offline_outlined++ : Icons.library_music_outlined,++ size: 48,color: cs.onSurfaceVariant,),-- ),-- if (lib.isOffline) ...[-- const SizedBox(height: 4),++ const SizedBox(height: 12),Text(-- l.downloadBooksWhileOnline,-- style: tt.bodySmall?.copyWith(-- color:-- cs.onSurfaceVariant.withValues(alpha: 0.6),++ lib.isOffline++ ? l.noDownloadedBooks++ : l.yourLibraryIsEmpty,++ style: tt.bodyLarge?.copyWith(++ color: cs.onSurfaceVariant,),),++ if (lib.isOffline) ...[++ const SizedBox(height: 4),++ Text(++ l.downloadBooksWhileOnline,++ style: tt.bodySmall?.copyWith(++ color: cs.onSurfaceVariant.withValues(++ alpha: 0.6,++ ),++ ),++ ),++ ],],-- ],++ ),),),-- ),-- // ── All sections (including Continue Listening) ──-- if (!lib.isLoading)-- ...(_cachedSections ?? []).expand((section) {-- final id = section['id'] as String? ?? '';-- final isPlaylist = id.startsWith('playlist:');-- final isCollection = id.startsWith('collection:');++ // ── All sections (including Continue Listening) ──++ if (!lib.isLoading)++ ...(_cachedSections ?? []).expand((section) {++ final id = section['id'] as String? ?? '';++ final isPlaylist = id.startsWith('playlist:');++ final isCollection = id.startsWith('collection:');-- // Playlists/collections are server-only; hide when offline-- if ((isPlaylist || isCollection) && lib.isOffline) return <Widget>[];++ // Playlists/collections are server-only; hide when offline++ if ((isPlaylist || isCollection) && lib.isOffline)++ return <Widget>[];-- // Continue Listening gets its own compact card layout-- if (id == 'continue-listening') {-- final clItems = _cachedClItems ?? [];-- if (clItems.isEmpty) return <Widget>[];-- return <Widget>[-- SliverToBoxAdapter(-- child: GestureDetector(-- onTap: () => SectionDetailSheet.show(-- context,-- title: l.continueListening,-- icon: Icons.play_circle_outline_rounded,-- entities: clItems,-- coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,-- ),-- behavior: HitTestBehavior.opaque,-- child: Padding(-- padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),-- child: Row(children: [-- Icon(Icons.play_circle_outline_rounded,-- size: 16, color: cs.primary.withValues(alpha: 0.7)),-- const SizedBox(width: 8),-- Text(l.continueListening,-- style: tt.titleSmall?.copyWith(-- fontWeight: FontWeight.w500,-- color: cs.onSurface.withValues(alpha: 0.8),-- letterSpacing: 0.3,-- )),-- const SizedBox(width: 4),-- Icon(Icons.chevron_right_rounded, size: 16,-- color: cs.onSurfaceVariant.withValues(alpha: 0.4)),-- const SizedBox(width: 12),-- Expanded(child: Container(height: 0.5,-- color: cs.outlineVariant.withValues(alpha: 0.2))),-- ]),++ // Continue Listening gets its own compact card layout++ if (id == 'continue-listening') {++ final clItems = _cachedClItems ?? [];++ if (clItems.isEmpty) return <Widget>[];++ return <Widget>[++ SliverToBoxAdapter(++ child: GestureDetector(++ onTap: _selectionMode++ ? null++ : () => SectionDetailSheet.show(++ context,++ title: l.continueListening,++ icon: Icons.play_circle_outline_rounded,++ entities: clItems,++ coverAspectRatio: _rectangleCovers++ ? 2 / 3++ : 1.0,++ ),++ behavior: HitTestBehavior.opaque,++ child: Padding(++ padding: const EdgeInsets.fromLTRB(++ 20,++ 24,++ 20,++ 0,++ ),++ child: Row(++ children: [++ Icon(++ Icons.play_circle_outline_rounded,++ size: 16,++ color: cs.primary.withValues(alpha: 0.7),++ ),++ const SizedBox(width: 8),++ Text(++ l.continueListening,++ style: tt.titleSmall?.copyWith(++ fontWeight: FontWeight.w500,++ color: cs.onSurface.withValues(++ alpha: 0.8,++ ),++ letterSpacing: 0.3,++ ),++ ),++ const SizedBox(width: 4),++ Icon(++ Icons.chevron_right_rounded,++ size: 16,++ color: cs.onSurfaceVariant.withValues(++ alpha: 0.4,++ ),++ ),++ const SizedBox(width: 12),++ Expanded(++ child: Container(++ height: 0.5,++ color: cs.outlineVariant.withValues(++ alpha: 0.2,++ ),++ ),++ ),++ ],++ ),++ ),),),-- ),- if (!desktop && !AppPlatform.isWeb)- const SliverToBoxAdapter(- child: FeatureHint(- prefKey: 'hint_continue_listening_gestures',- message:- 'Tap a card to resume. Press and hold to see details.',- const SliverToBoxAdapter(- child: FeatureHint(- prefKey: 'hint_continue_listening_gestures',- message:- 'Tap a card to resume. Press and hold to see details.',- ),- ),- SliverToBoxAdapter(- child: Padding(- padding: const EdgeInsets.only(top: 12),- child: SizedBox(- // Taller row when 2:3 covers are on; the card's- // cover alone is ~225 with rectangle covers.- height: _rectangleCovers ? 320 : 250,- child: ListView.separated(- scrollDirection: Axis.horizontal,- padding: const EdgeInsets.symmetric(horizontal: 20),- physics: const BouncingScrollPhysics(),- itemCount: clItems.length,- separatorBuilder: (_, __) => const SizedBox(width: 10),- itemBuilder: (context, i) {- final item = clItems[i] as Map<String, dynamic>;- return RepaintBoundary(child: _ContinueListeningCard(- item: item, lib: lib, player: _player,- rectangleCovers: _rectangleCovers,- ));- },++ if (!desktop && !AppPlatform.isWeb)++ const SliverToBoxAdapter(++ child: FeatureHint(++ prefKey: 'hint_continue_listening_gestures',++ message:++ 'Tap a card to resume. Press and hold to see details.',++ ),+ ),- ),- SliverToBoxAdapter(- child: Padding(- padding: const EdgeInsets.only(top: 12),- child: SizedBox(- // Taller row when 2:3 covers are on; the card's- // cover alone is ~225 with rectangle covers.- height: (_rectangleCovers ? 320 : 250) *- (desktop ? 1.2 : 1.0),- child: desktop- ? SnapScrollList(- cardWidth: 180,- desktop: true,- itemCount: clItems.length,- itemBuilder: (context, i) {- final item =- clItems[i] as Map<String, dynamic>;- return RepaintBoundary(++ SliverToBoxAdapter(++ child: Padding(++ padding: const EdgeInsets.only(top: 12),++ child: SizedBox(++ // Taller row when 2:3 covers are on; the card's++ // cover alone is ~225 with rectangle covers.++ height:++ (_rectangleCovers ? 320 : 250) *++ (desktop ? _desktopShelfScale : 1.0),++ child: desktop++ ? SnapScrollList(++ cardWidth:++ 180 * (_bookshelfCoverSize / 120),++ desktop: true,++ itemCount: clItems.length,++ itemBuilder: (context, i) {++ final item =++ clItems[i]++ as Map<String, dynamic>;++ return RepaintBoundary(+ child: _ContinueListeningCard(- item: item, lib: lib, player: _player,- rectangleCovers: _rectangleCovers,- ));- },- )- : ListView.separated(- scrollDirection: Axis.horizontal,- padding: const EdgeInsets.symmetric(horizontal: 20),- physics: const BouncingScrollPhysics(),- itemCount: clItems.length,- separatorBuilder: (_, __) => const SizedBox(width: 10),- itemBuilder: (context, i) {- final item = clItems[i] as Map<String, dynamic>;- return RepaintBoundary(child: _ContinueListeningCard(- item: item, lib: lib, player: _player,- rectangleCovers: _rectangleCovers,- ));- },- ),++ item: item,++ lib: lib,++ player: _player,++ rectangleCovers: _rectangleCovers,++ desktopWidth:++ 180 *++ (_bookshelfCoverSize / 120),++ selectionMode:++ selectionAvailable &&++ _selectionMode,++ selected: _selectedItemIds++ .contains(++ item['id'] as String?,++ ),++ onSelectionToggle:++ selectionAvailable &&++ item['recentEpisode'] ==++ null &&++ item['id'] is String++ ? () => _toggleSelection(item)++ : null,++ ),++ );++ },++ )++ : ListView.separated(++ scrollDirection: Axis.horizontal,++ padding: const EdgeInsets.symmetric(++ horizontal: 20,++ ),++ physics: const BouncingScrollPhysics(),++ itemCount: clItems.length,++ separatorBuilder: (_, __) =>++ const SizedBox(width: 10),++ itemBuilder: (context, i) {++ final item =++ clItems[i]++ as Map<String, dynamic>;++ return RepaintBoundary(++ child: _ContinueListeningCard(++ item: item,++ lib: lib,++ player: _player,++ rectangleCovers: _rectangleCovers,++ ),++ );++ },++ ),+ ),),),-- ),-- ];-- }++ ];++ }-- final label = sectionLabel(id, section['label'] as String?, l);-- final entities = _filterEbookOnly(++ final label = sectionLabel(++ id,++ section['label'] as String?,++ l,++ );++ final entities = _filterEbookOnly((section['entities'] as List<dynamic>?) ?? [],-- sectionType: section['type'] as String?);-- final type = isPlaylist ? 'playlist'-- : isCollection ? 'collection'-- : (section['type'] ?? 'book');-- if (entities.isEmpty) return <Widget>[];---- VoidCallback? titleTap;-- IconData sectionIcon;-- if (isPlaylist) {-- titleTap = () => PlaylistDetailSheet.show(-- context, section['_playlistId'] as String);-- sectionIcon = Icons.playlist_play_rounded;-- } else if (isCollection) {-- titleTap = () => CollectionDetailSheet.show(-- context, section['_collectionId'] as String);-- sectionIcon = Icons.collections_bookmark_rounded;-- } else if (id.startsWith('genre:')) {-- sectionIcon = Icons.label_outline_rounded;-- final sectionLabel = label;-- titleTap = () => SectionDetailSheet.show(-- context,-- title: sectionLabel,-- icon: sectionIcon,-- entities: entities,-- coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,++ sectionType: section['type'] as String?,);-- } else {-- sectionIcon = _sectionIcons[id] ?? Icons.album_outlined;-- // Author/series sections don't have book-shaped entities,-- // so skip the book-oriented SectionDetailSheet for them.-- if (type != 'authors' && type != 'series') {++ final type = isPlaylist++ ? 'playlist'++ : isCollection++ ? 'collection'++ : (section['type'] ?? 'book');++ if (entities.isEmpty) return <Widget>[];++++ VoidCallback? titleTap;++ IconData sectionIcon;++ if (isPlaylist) {++ titleTap = () => PlaylistDetailSheet.show(++ context,++ section['_playlistId'] as String,++ );++ sectionIcon = Icons.playlist_play_rounded;++ } else if (isCollection) {++ titleTap = () => CollectionDetailSheet.show(++ context,++ section['_collectionId'] as String,++ );++ sectionIcon = Icons.collections_bookmark_rounded;++ } else if (id.startsWith('genre:')) {++ sectionIcon = Icons.label_outline_rounded;final sectionLabel = label;titleTap = () => SectionDetailSheet.show(context,@@@ -610,31 -557,31 +878,101 @@@entities: entities,coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,);++ } else {++ sectionIcon = _sectionIcons[id] ?? Icons.album_outlined;++ // Author/series sections don't have book-shaped entities,++ // so skip the book-oriented SectionDetailSheet for them.++ if (type != 'authors' && type != 'series') {++ final sectionLabel = label;++ titleTap = () => SectionDetailSheet.show(++ context,++ title: sectionLabel,++ icon: sectionIcon,++ entities: entities,++ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,++ );++ }}-- }-- return <Widget>[-- SliverToBoxAdapter(-- child: HomeSection(-- title: label,-- icon: sectionIcon,-- entities: entities,-- sectionType: type,-- sectionId: id,-- onTitleTap: titleTap,-- coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,++ return <Widget>[++ SliverToBoxAdapter(++ child: HomeSection(++ title: label,++ icon: sectionIcon,++ entities: entities,++ sectionType: type,++ sectionId: id,++ onTitleTap: _selectionMode ? null : titleTap,++ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,++ desktopScale: _desktopShelfScale,++ selectionMode: selectionAvailable && _selectionMode,++ selectedItemIds: _selectedItemIds,++ onSelectionToggle: selectionAvailable++ ? _toggleSelection++ : null,++ ),),-- ),-- ];-- }),++ ];++ }),- SliverPadding(padding: EdgeInsets.only(bottom: desktop ? 24 : 100)),- const SliverPadding(padding: EdgeInsets.only(bottom: 100)),-- ],++ SliverPadding(++ padding: EdgeInsets.only(bottom: desktop ? 80 : 100),++ ),++ ],++ ),),),-- ),),),++ floatingActionButton: !desktop++ ? null++ : _selectionMode++ ? DesktopBatchActionBar(++ selectedCount: _selectedItemIds.length,++ selectableCount: selectableHomeItems.length,++ busy: _batchActionBusy,++ canQuickMatch:++ context.watch<AuthProvider>().isAdmin &&++ !lib.isPodcastLibrary &&++ !lib.isOffline,++ canMarkProgress: !lib.isPodcastLibrary,++ canDelete:++ context.watch<AuthProvider>().canDelete && !lib.isOffline,++ onSelectAll: _toggleSelectAll,++ onClear: _clearSelection,++ onQuickMatch: () => _runBatchAction(++ () => DesktopBatchActions.quickMatch(++ context,++ _selectedItemIds.toList(),++ ),++ ),++ onMarkFinished: () => _runBatchAction(++ () => DesktopBatchActions.setFinished(++ context,++ _selectedItemIds.toList(),++ isFinished: true,++ ),++ ),++ onMarkUnfinished: () => _runBatchAction(++ () => DesktopBatchActions.setFinished(++ context,++ _selectedItemIds.toList(),++ isFinished: false,++ ),++ ),++ onDelete: () => _runBatchAction(++ () => DesktopBatchActions.delete(++ context,++ _selectedItemIds.toList(),++ ),++ ),++ )++ : DesktopCoverSizeControl(++ value: _bookshelfCoverSize,++ onDecrease: () => _changeBookshelfCoverSize(-1),++ onIncrease: () => _changeBookshelfCoverSize(1),++ ),++ floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,);}}@@@ -653,12 -600,12 +991,20 @@@ class _ContinueListeningCard extends Stfinal LibraryProvider lib;final AudioPlayerService player;final bool rectangleCovers;++ final double desktopWidth;++ final bool selectionMode;++ final bool selected;++ final VoidCallback? onSelectionToggle;const _ContinueListeningCard({required this.item,required this.lib,required this.player,required this.rectangleCovers,++ this.desktopWidth = 180,++ this.selectionMode = false,++ this.selected = false,++ this.onSelectionToggle,});@override@@@ -676,18 -623,18 +1022,29 @@@ class _ContinueListeningCardState extenreturn '${formatHm(s)} left';}-- Widget _buildCoverImage(String? coverUrl, ColorScheme cs, Map<String, String> headers) {++ Widget _buildCoverImage(++ String? coverUrl,++ ColorScheme cs,++ Map<String, String> headers,++ ) {final fallback = Container(color: cs.surfaceContainerHighest,-- child: Icon(Icons.headphones_rounded, size: 32, color: cs.onSurfaceVariant),++ child: Icon(++ Icons.headphones_rounded,++ size: 32,++ color: cs.onSurfaceVariant,++ ),);if (coverUrl == null) return fallback;final isLocal = coverUrl.startsWith('/');Widget image({required BoxFit fit}) {if (isLocal) {-- return Image.file(File(coverUrl), fit: fit,-- errorBuilder: (_, __, ___) => fallback);++ return Image.file(++ File(coverUrl),++ fit: fit,++ errorBuilder: (_, __, ___) => fallback,++ );}return CachedNetworkImage(imageUrl: coverUrl,@@@ -736,7 -683,7 +1093,10 @@@if (coverUrl.startsWith('/')) {provider = FileImage(File(coverUrl));} else {-- provider = CachedNetworkImageProvider(coverUrl, headers: widget.lib.mediaHeaders);++ provider = CachedNetworkImageProvider(++ coverUrl,++ headers: widget.lib.mediaHeaders,++ );}PaletteGenerator.fromImageProvider(provider, maximumColorCount: 16).then((palette) {@@@ -785,7 -731,7 +1145,8 @@@? lib.getEpisodeProgressData(itemId, episodeId): lib.getProgressData(itemId);final isCurrentItem = player.currentItemId == itemId;-- final serverCurrentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;++ final serverCurrentTime =++ (progressData?['currentTime'] as num?)?.toDouble() ?? 0;double currentTime;double totalDuration;@@@ -794,7 -740,7 +1155,8 @@@totalDuration = player.totalDuration;} else {currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;-- totalDuration = (progressData?['duration'] as num?)?.toDouble() ??++ totalDuration =++ (progressData?['duration'] as num?)?.toDouble() ??(recentEpisode != null? (recentEpisode['duration'] as num?)?.toDouble() ?? 0: (media['duration'] as num?)?.toDouble() ?? 0);@@@ -809,15 -755,15 +1171,21 @@@? null: HSLColor.fromColor(accent).withSaturation((HSLColor.fromColor(accent).saturation * (isDark ? 0.85 : 0.55))-- .clamp(0.0, 1.0));++ .clamp(0.0, 1.0),++ );final Color cardBgTop = bgHsl != null? bgHsl.withLightness(isDark ? 0.19 : 0.95).toColor()-- : (isCurrentItem ? cs.primary.withValues(alpha: 0.08) : cs.surfaceContainerHigh);++ : (isCurrentItem++ ? cs.primary.withValues(alpha: 0.08)++ : cs.surfaceContainerHigh);final Color cardBgBottom = bgHsl != null? bgHsl.withLightness(isDark ? 0.11 : 0.88).toColor(): cardBgTop;final progressValue =-- (totalDuration > 0 ? currentTime / totalDuration : progress).clamp(0.0, 1.0);++ (totalDuration > 0 ? currentTime / totalDuration : progress).clamp(++ 0.0,++ 1.0,++ );final remaining = totalDuration > 0 ? totalDuration - currentTime : 0.0;void resume() {@@@ -863,154 -809,142 +1231,197 @@@}}- final canEdit = !lib.isPodcastLibrary &&- return Material(- color: Colors.transparent,- borderRadius: BorderRadius.circular(14),- clipBehavior: Clip.antiAlias,- child: Ink(- decoration: BoxDecoration(- borderRadius: BorderRadius.circular(14),- gradient: LinearGradient(- begin: Alignment.topLeft,- end: Alignment.bottomRight,- colors: [cardBgTop, cardBgBottom],++ final canEdit =++ !lib.isPodcastLibrary &&+ !lib.isOffline &&+ recentEpisode == null &&+ context.watch<AuthProvider>().canUpdateMetadata;+ return HoverCoverActions(- onMenu: openQuickActions,- editItemId: canEdit ? itemId : null,++ onMenu: widget.selectionMode ? null : openQuickActions,++ editItemId: canEdit && !widget.selectionMode ? itemId : null,++ selectionMode: widget.selectionMode,++ selected: widget.selected,++ onSelectionToggle: widget.onSelectionToggle,+ child: Material(- color: Colors.transparent,- borderRadius: BorderRadius.circular(14),- clipBehavior: Clip.antiAlias,- child: Ink(- decoration: BoxDecoration(- borderRadius: BorderRadius.circular(14),- gradient: LinearGradient(- begin: Alignment.topLeft,- end: Alignment.bottomRight,- colors: [cardBgTop, cardBgBottom],++ color: Colors.transparent,++ borderRadius: BorderRadius.circular(14),++ clipBehavior: Clip.antiAlias,++ child: Ink(++ decoration: BoxDecoration(++ borderRadius: BorderRadius.circular(14),++ gradient: LinearGradient(++ begin: Alignment.topLeft,++ end: Alignment.bottomRight,++ colors: [cardBgTop, cardBgBottom],++ ),),-- ),-- child: InkWell(- onTap: gesturePolicy.continueListeningTapOpensDetails- ? openDetails- : resume,- onLongPress: gesturePolicy.allowsLongPressShortcuts- ? openQuickActions- : null,- onTap: resume,- onLongPress: openQuickActions,-- borderRadius: BorderRadius.circular(14),-- child: SizedBox(- width: isDesktopWorkspace(context) ? 180 : 150,- width: 150,-- child: Column(-- crossAxisAlignment: CrossAxisAlignment.stretch,-- children: [-- // Floating cover with a colored glow-- Padding(-- padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),-- child: DecoratedBox(-- decoration: BoxDecoration(-- borderRadius: BorderRadius.circular(10),-- boxShadow: [-- BoxShadow(-- color: accent.withValues(alpha: 0.45),-- blurRadius: 14,-- spreadRadius: -2,-- offset: const Offset(0, 5),-- ),-- ],-- ),-- child: ClipRRect(-- borderRadius: BorderRadius.circular(10),-- child: AspectRatio(-- aspectRatio: widget.rectangleCovers ? 2 / 3 : 1,-- child: Stack(children: [-- Positioned.fill(-- child: _buildCoverImage(coverUrl, cs, lib.mediaHeaders),-- ),-- if (isCurrentItem && player.isPlaying)-- Positioned(-- right: 6, bottom: 6,-- child: Container(-- padding: const EdgeInsets.all(5),-- decoration: BoxDecoration(-- color: Colors.black.withValues(alpha: 0.55),-- shape: BoxShape.circle,-- ),-- child: const Icon(Icons.graphic_eq_rounded,-- size: 14, color: Colors.white),++ child: InkWell(++ onTap: widget.selectionMode && widget.onSelectionToggle != null++ ? widget.onSelectionToggle++ : gesturePolicy.continueListeningTapOpensDetails++ ? openDetails++ : resume,++ onLongPress:++ !widget.selectionMode && gesturePolicy.allowsLongPressShortcuts++ ? openQuickActions++ : null,++ borderRadius: BorderRadius.circular(14),++ child: SizedBox(++ width: isDesktopWorkspace(context) ? widget.desktopWidth : 150,++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.stretch,++ children: [++ // Floating cover with a colored glow++ Padding(++ padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),++ child: DecoratedBox(++ decoration: BoxDecoration(++ borderRadius: BorderRadius.circular(10),++ boxShadow: [++ BoxShadow(++ color: accent.withValues(alpha: 0.45),++ blurRadius: 14,++ spreadRadius: -2,++ offset: const Offset(0, 5),++ ),++ ],),-- ),-- if (_isLoading)-- Positioned.fill(-- child: Container(-- color: Colors.black.withValues(alpha: 0.4),-- child: const Center(-- child: SizedBox(-- width: 22, height: 22,-- child: CircularProgressIndicator(-- strokeWidth: 2, color: Colors.white),++ child: ClipRRect(++ borderRadius: BorderRadius.circular(10),++ child: AspectRatio(++ aspectRatio: widget.rectangleCovers ? 2 / 3 : 1,++ child: Stack(++ children: [++ Positioned.fill(++ child: _buildCoverImage(++ coverUrl,++ cs,++ lib.mediaHeaders,++ ),++ ),++ if (isCurrentItem && player.isPlaying)++ Positioned(++ right: 6,++ bottom: 6,++ child: Container(++ padding: const EdgeInsets.all(5),++ decoration: BoxDecoration(++ color: Colors.black.withValues(++ alpha: 0.55,++ ),++ shape: BoxShape.circle,++ ),++ child: const Icon(++ Icons.graphic_eq_rounded,++ size: 14,++ color: Colors.white,++ ),++ ),++ ),++ if (_isLoading)++ Positioned.fill(++ child: Container(++ color: Colors.black.withValues(alpha: 0.4),++ child: const Center(++ child: SizedBox(++ width: 22,++ height: 22,++ child: CircularProgressIndicator(++ strokeWidth: 2,++ color: Colors.white,++ ),++ ),++ ),++ ),++ ),++ ],),),),),-- ]),-- ),),-- ),-- ),-- // Text + progress area-- Expanded(-- child: Padding(-- padding: const EdgeInsets.fromLTRB(12, 8, 12, 10),-- child: Column(-- crossAxisAlignment: CrossAxisAlignment.start,-- children: [-- // Reserve 2 lines of title height so the author row-- // stays in a consistent position whether the title-- // wraps or not.-- SizedBox(-- height: 30,-- child: Text(title, maxLines: 2,-- overflow: TextOverflow.ellipsis,-- style: tt.bodySmall?.copyWith(++ // Text + progress area++ Expanded(++ child: Padding(++ padding: const EdgeInsets.fromLTRB(12, 8, 12, 10),++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ // Reserve 2 lines of title height so the author row++ // stays in a consistent position whether the title++ // wraps or not.++ SizedBox(++ height: 30,++ child: Text(++ title,++ maxLines: 2,++ overflow: TextOverflow.ellipsis,++ style: tt.bodySmall?.copyWith(fontWeight: FontWeight.w600,color: cs.onSurface,-- height: 1.2)),-- ),-- if (author.isNotEmpty) ...[-- const SizedBox(height: 2),-- Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,-- style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),-- ],-- const Spacer(),-- ClipRRect(-- borderRadius: BorderRadius.circular(2),-- child: LinearProgressIndicator(-- value: progressValue,-- minHeight: 3,-- backgroundColor: cs.outlineVariant.withValues(alpha: 0.3),-- valueColor: AlwaysStoppedAnimation(accent),-- ),-- ),-- const SizedBox(height: 4),-- Row(children: [-- Text('${(progressValue * 100).round()}%',-- style: tt.labelSmall?.copyWith(-- fontWeight: FontWeight.w700,-- color: accent,-- fontSize: 11)),-- if (remaining > 0) ...[-- const SizedBox(width: 6),-- Expanded(-- child: Text(_fmtRemaining(remaining),-- maxLines: 1,-- overflow: TextOverflow.ellipsis,++ height: 1.2,++ ),++ ),++ ),++ if (author.isNotEmpty) ...[++ const SizedBox(height: 2),++ Text(++ author,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),++ ],++ const Spacer(),++ ClipRRect(++ borderRadius: BorderRadius.circular(2),++ child: LinearProgressIndicator(++ value: progressValue,++ minHeight: 3,++ backgroundColor: cs.outlineVariant.withValues(++ alpha: 0.3,++ ),++ valueColor: AlwaysStoppedAnimation(accent),++ ),++ ),++ const SizedBox(height: 4),++ Row(++ children: [++ Text(++ '${(progressValue * 100).round()}%',style: tt.labelSmall?.copyWith(-- color: cs.onSurfaceVariant, fontSize: 10)),++ fontWeight: FontWeight.w700,++ color: accent,++ fontSize: 11,++ ),++ ),++ if (remaining > 0) ...[++ const SizedBox(width: 6),++ Expanded(++ child: Text(++ _fmtRemaining(remaining),++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant,++ fontSize: 10,++ ),++ ),++ ),++ ],++ ],),],-- ]),-- ],++ ),++ ),),-- ),++ ],),-- ],++ ),),),-- ),- ),),);}@@@ -1031,7 -965,7 +1442,8 @@@// Podcast episode — play the recent episode directlyfinal l = AppLocalizations.of(context)!;final episodeId = recentEpisode['id'] as String? ?? '';-- final episodeTitle = recentEpisode['title'] as String? ?? l.homeScreenEpisodeFallback;++ final episodeTitle =++ recentEpisode['title'] as String? ?? l.homeScreenEpisodeFallback;final media = widget.item['media'] as Map<String, dynamic>? ?? {};final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final showTitle = metadata['title'] as String? ?? '';diff --cc lib/screens/library_screen.dartindex 5170acb1,28bb78e0..9ad06de6--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@@ -32,6 -31,6 +32,8 @@@ import 'app_shell.dart'import 'upcoming_releases_screen.dart';import '../widgets/audible_series_sheet.dart' show showAudibleRegionPicker;import '../widgets/offline_status_icon.dart';++import '../widgets/desktop_batch_actions.dart';++import '../widgets/desktop_cover_size_control.dart';import '../widgets/rmab_config_sheet.dart'show kRmabBaseUrlKey, kRmabApiTokenKey;import '../widgets/rmab_search_results_sheet.dart';@@@ -39,99 -38,12 +41,95 @@@ import '../widgets/scroll_reveal.dart'import '../services/scoped_prefs.dart';import '../services/user_account_service.dart';import '../l10n/app_localizations.dart';+import '../utils/desktop_workspace.dart';++const double kDesktopLibraryTileMaxExtent = 220;++LinearGradient _libraryBackgroundGradient(+ ColorScheme colorScheme,+ Color scaffoldBackground,+) {+ final lowerFade =+ Color.lerp(colorScheme.surface, scaffoldBackground, 0.55) ??+ scaffoldBackground;+ return LinearGradient(+ begin: Alignment.topCenter,+ end: Alignment.bottomCenter,+ stops: const [0.0, 0.22, 0.72, 1.0],+ colors: [- colorScheme.primary.withValues(- alpha: gradientIntensityNotifier.value,- ),++ colorScheme.primary.withValues(alpha: gradientIntensityNotifier.value),+ colorScheme.surface,+ lowerFade,+ scaffoldBackground,+ ],+ );+}++class _LibraryHeaderGradientPainter extends CustomPainter {+ const _LibraryHeaderGradientPainter({+ required this.backgroundColor,+ required this.gradient,+ required this.topInset,+ required this.screenHeight,+ });++ final Color backgroundColor;+ final LinearGradient gradient;+ final double topInset;+ final double screenHeight;++ @override+ void paint(Canvas canvas, Size size) {+ final paintBounds = Offset.zero & size;+ canvas.drawRect(paintBounds, Paint()..color = backgroundColor);- final shaderBounds = Rect.fromLTWH(- 0,- -topInset,- size.width,- screenHeight,- );++ final shaderBounds = Rect.fromLTWH(0, -topInset, size.width, screenHeight);+ canvas.drawRect(+ paintBounds,+ Paint()..shader = gradient.createShader(shaderBounds),+ );+ }-/// Responsive grid column count based on available width.-/// Returns 3 on phones, scales up on tablets/iPads.-int responsiveGridCount(BuildContext context) {- final width = MediaQuery.of(context).size.width;- return (width / 130).floor().clamp(3, 10);+ @override+ bool shouldRepaint(_LibraryHeaderGradientPainter oldDelegate) =>+ backgroundColor != oldDelegate.backgroundColor ||+ gradient != oldDelegate.gradient ||+ topInset != oldDelegate.topInset ||+ screenHeight != oldDelegate.screenHeight;+}++SliverGridDelegate libraryGridDelegateForWidth(+ double width, {+ required bool desktopWorkspace,+ required double childAspectRatio,++ double desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,+}) {+ if (desktopWorkspace) {+ return SliverGridDelegateWithMaxCrossAxisExtent(- maxCrossAxisExtent: kDesktopLibraryTileMaxExtent,++ maxCrossAxisExtent: desktopMaxCrossAxisExtent,+ childAspectRatio: childAspectRatio,+ crossAxisSpacing: 10,+ mainAxisSpacing: 10,+ );+ }+ return SliverGridDelegateWithFixedCrossAxisCount(+ crossAxisCount: (width / 130).floor().clamp(3, 10),+ childAspectRatio: childAspectRatio,+ crossAxisSpacing: 10,+ mainAxisSpacing: 10,+ );+}++SliverGridDelegate libraryGridDelegate(+ BuildContext context, {+ required double childAspectRatio,++ double desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,+}) {+ return libraryGridDelegateForWidth(+ MediaQuery.sizeOf(context).width,+ desktopWorkspace: isDesktopWorkspace(context),+ childAspectRatio: childAspectRatio,++ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,+ );}/// Bottom padding for the library tab grids/lists so the last row clears the@@@ -139,9 -51,8 +137,9 @@@/// `NavigationBar` once both reappear at the end of a scroll. When the bars/// hide-on-scroll then snap back, the viewport shrinks but the scroll offset/// stays put, so the bottom items end up closer to the pill than steady-state-/// math would suggest. This value keeps a comfortable gap even in that case.-const double libraryGridBottomPadding = 180;+/// math would suggest. The desktop workspace has neither bar.+double libraryGridBottomPadding(BuildContext context) =>- isDesktopWorkspace(context) ? 24 : 180;++ isDesktopWorkspace(context) ? 80 : 180;// ─── Sort modes ──────────────────────────────────────────────enum LibrarySort {@@@ -279,20 -190,20 +277,34 @@@ String? buildLibraryFilterQueryreturn switch (filter) {LibraryFilter.hasEbook => _encodedLibraryFilter('ebooks', 'ebook'),LibraryFilter.noEbook => _encodedLibraryFilter('ebooks', 'no-ebook'),-- LibraryFilter.hasSupplementaryEbook =>-- _encodedLibraryFilter('ebooks', 'supplementary'),-- LibraryFilter.noSupplementaryEbook =>-- _encodedLibraryFilter('ebooks', 'no-supplementary'),-- LibraryFilter.series when filterValue != null =>-- _encodedLibraryFilter('series', filterValue),-- LibraryFilter.author when filterValue != null =>-- _encodedLibraryFilter('authors', filterValue),-- LibraryFilter.narrator when filterValue != null =>-- _encodedLibraryFilter('narrators', filterValue),-- LibraryFilter.language when filterValue != null =>-- _encodedLibraryFilter('languages', filterValue),-- LibraryFilter.publisher when filterValue != null =>-- _encodedLibraryFilter('publishers', filterValue),++ LibraryFilter.hasSupplementaryEbook => _encodedLibraryFilter(++ 'ebooks',++ 'supplementary',++ ),++ LibraryFilter.noSupplementaryEbook => _encodedLibraryFilter(++ 'ebooks',++ 'no-supplementary',++ ),++ LibraryFilter.series when filterValue != null => _encodedLibraryFilter(++ 'series',++ filterValue,++ ),++ LibraryFilter.author when filterValue != null => _encodedLibraryFilter(++ 'authors',++ filterValue,++ ),++ LibraryFilter.narrator when filterValue != null => _encodedLibraryFilter(++ 'narrators',++ filterValue,++ ),++ LibraryFilter.language when filterValue != null => _encodedLibraryFilter(++ 'languages',++ filterValue,++ ),++ LibraryFilter.publisher when filterValue != null => _encodedLibraryFilter(++ 'publishers',++ filterValue,++ ),LibraryFilter.publishedDecade when filterValue != null =>_encodedLibraryFilter('publishedDecades', filterValue),LibraryFilter.noTracks => _encodedLibraryFilter('tracks', 'none'),@@@ -302,8 -213,8 +314,10 @@@LibraryFilter.issues => 'issues',LibraryFilter.feedOpen => 'feed-open',LibraryFilter.explicit => 'explicit',-- LibraryFilter.genre when genre != null =>-- _encodedLibraryFilter('genres', genre),++ LibraryFilter.genre when genre != null => _encodedLibraryFilter(++ 'genres',++ genre,++ ),LibraryFilter.tag when tag != null => _encodedLibraryFilter('tags', tag),LibraryFilter.missingMetadata when missingMetadata != null =>_encodedLibraryFilter('missing', missingMetadata.filterValue),@@@ -527,7 -438,7 +541,107 @@@ class LibraryScreenState extends State<// ── Cover aspect ratio ──bool _rectangleCovers = false;++ int _bookshelfCoverSize = 120;double get _coverAspectRatio => _rectangleCovers ? 2 / 3 : 1.0;++ double get _desktopTileMaxExtent =>++ kDesktopLibraryTileMaxExtent * (_bookshelfCoverSize / 120);++++ bool _selectionMode = false;++ bool _batchActionBusy = false;++ final Set<String> _selectedItemIds = {};++ int? _lastSelectedVisibleIndex;++++ void _resetSelectionState() {++ _selectionMode = false;++ _batchActionBusy = false;++ _selectedItemIds.clear();++ _lastSelectedVisibleIndex = null;++ }++++ void _clearSelection() {++ if (!_selectionMode && _selectedItemIds.isEmpty) return;++ setState(_resetSelectionState);++ }++++ List<Map<String, dynamic>> _selectableVisibleItems() {++ final lib = context.read<LibraryProvider>();++ return _visibleLibraryItems(lib)++ .where(++ (item) =>++ !item.containsKey('collapsedSeries') && item['id'] is String,++ )++ .toList();++ }++++ void _toggleSelection(Map<String, dynamic> item, int visibleIndex) {++ final itemId = item['id'] as String?;++ if (itemId == null) return;++ final shiftPressed = HardwareKeyboard.instance.isShiftPressed;++ setState(() {++ _selectionMode = true;++ if (shiftPressed && _lastSelectedVisibleIndex != null) {++ final items = _visibleLibraryItems(context.read<LibraryProvider>());++ final start = min(_lastSelectedVisibleIndex!, visibleIndex);++ final end = max(_lastSelectedVisibleIndex!, visibleIndex);++ for (var index = start; index <= end && index < items.length; index++) {++ final rangeItem = items[index];++ if (rangeItem.containsKey('collapsedSeries')) continue;++ final rangeId = rangeItem['id'] as String?;++ if (rangeId != null) _selectedItemIds.add(rangeId);++ }++ } else if (!_selectedItemIds.add(itemId)) {++ _selectedItemIds.remove(itemId);++ }++ _lastSelectedVisibleIndex = visibleIndex;++ });++ }++++ void _toggleSelectAll() {++ final ids = _selectableVisibleItems()++ .map((item) => item['id'] as String)++ .toSet();++ setState(() {++ _selectionMode = true;++ if (ids.isNotEmpty && _selectedItemIds.containsAll(ids)) {++ _selectedItemIds.removeAll(ids);++ } else {++ _selectedItemIds.addAll(ids);++ }++ _lastSelectedVisibleIndex = null;++ });++ }++++ Future<void> _runBatchAction(Future<bool?> Function() action) async {++ if (_batchActionBusy) return;++ final visibleIds = _selectableVisibleItems()++ .map((item) => item['id'] as String)++ .toSet();++ setState(() {++ _selectedItemIds.retainAll(visibleIds);++ if (_selectedItemIds.isEmpty) {++ _resetSelectionState();++ } else {++ _batchActionBusy = true;++ }++ });++ if (_selectedItemIds.isEmpty) return;++ final success = await action();++ if (!mounted) return;++ setState(() {++ _batchActionBusy = false;++ if (success == true) _resetSelectionState();++ });++ }++++ void _changeBookshelfCoverSize(int direction) {++ final sizes = PlayerSettings.bookshelfCoverSizes;++ final currentIndex = sizes.indexOf(_bookshelfCoverSize);++ final nextIndex = (currentIndex + direction).clamp(0, sizes.length - 1);++ final next = sizes[nextIndex];++ if (next == _bookshelfCoverSize) return;++ setState(() => _bookshelfCoverSize = next);++ PlayerSettings.setBookshelfCoverSize(next);++ }// ── Scroll-to-hide bars ──/// Continuous 0..1 reveal: 1 = header + nav fully visible, 0 = both hidden.@@@ -612,7 -523,7 +726,10 @@@if (_tabController == null || _tabController!.indexIsChanging) return;final newTab = _tabController!.index;if (newTab == _currentTab) return;-- setState(() => _currentTab = newTab);++ setState(() {++ _currentTab = newTab;++ _resetSelectionState();++ });// Reset reveal so the SliverAppBar is fully visible after a tab switch._revealDriver.resetToShown();PlayerSettings.setLibraryTab(newTab);@@@ -661,6 -572,6 +778,7 @@@}setState(() {++ _resetSelectionState();_podcastView = 0;_items.clear();_page = 0;@@@ -717,6 -628,6 +835,9 @@@PlayerSettings.getRectangleCoversFor(lib.selectedLibraryId).then((v) {if (mounted) setState(() => _rectangleCovers = v);});++ PlayerSettings.getBookshelfCoverSize().then((value) {++ if (mounted) setState(() => _bookshelfCoverSize = value);++ });_restoreSortFilter().then((_) {if (!mounted) return;_lastLibraryId = lib.selectedLibraryId;@@@ -814,10 -725,10 +935,7 @@@(f) => f.name == restoredFilterName,orElse: () => LibraryFilter.none,);-- if (!libraryFilterSupportsMediaType(-- _filter,-- isPodcast: isPodcast,-- )) {++ if (!libraryFilterSupportsMediaType(_filter, isPodcast: isPodcast)) {_filter = LibraryFilter.none;}final restoredGenre = isPodcast ? podcastGenreFilter : genreFilter;@@@ -828,14 -739,14 +946,15 @@@final restoredValueLabel = isPodcast? podcastFilterValueLabel: libraryFilterValueLabel;-- _genreFilter = _filter == LibraryFilter.genre && restoredGenre.isNotEmpty++ _genreFilter =++ _filter == LibraryFilter.genre && restoredGenre.isNotEmpty? restoredGenre: null;_tagFilter = _filter == LibraryFilter.tag && restoredTag.isNotEmpty? restoredTag: null;-- _filterValue = libraryFilterRequiresValue(_filter) &&-- restoredValue.isNotEmpty++ _filterValue =++ libraryFilterRequiresValue(_filter) && restoredValue.isNotEmpty? restoredValue: null;_filterValueLabel = _filterValue == null@@@ -941,14 -852,14 +1060,20 @@@PlayerSettings.getRectangleCoversFor(context.read<LibraryProvider>().selectedLibraryId,),++ PlayerSettings.getBookshelfCoverSize(),]).then((values) {-- final newHideEbook = values[0];-- final newCollapse = values[1];-- final newRectCovers = values[2];++ final newHideEbook = values[0] as bool;++ final newCollapse = values[1] as bool;++ final newRectCovers = values[2] as bool;++ final newCoverSize = values[3] as int;if (!mounted) return;final coversChanged = newRectCovers != _rectangleCovers;-- if (coversChanged) {-- setState(() => _rectangleCovers = newRectCovers);++ final coverSizeChanged = newCoverSize != _bookshelfCoverSize;++ if (coversChanged || coverSizeChanged) {++ setState(() {++ _rectangleCovers = newRectCovers;++ _bookshelfCoverSize = newCoverSize;++ });}if (newHideEbook != _hideEbookOnly || newCollapse != _collapseSeries) {_loadGeneration++;@@@ -1000,62 -911,62 +1125,59 @@@..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));_availableTags = tags.map(unwrap).where((t) => t.isNotEmpty).toList()..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));-- _availableSeriesFilters = series-- .whereType<Map>()-- .map(-- (value) => {-- 'id': value['id']?.toString() ?? '',-- 'name': value['name']?.toString() ?? '',-- },-- )-- .where(-- (value) =>-- value['id']!.isNotEmpty && value['name']!.isNotEmpty,-- )-- .toList()-- ..sort(-- (a, b) => a['name']!.toLowerCase().compareTo(-- b['name']!.toLowerCase(),-- ),-- );-- _availableAuthorFilters = authors-- .whereType<Map>()-- .map(-- (value) => {-- 'id': value['id']?.toString() ?? '',-- 'name': value['name']?.toString() ?? '',-- },-- )-- .where(-- (value) =>-- value['id']!.isNotEmpty && value['name']!.isNotEmpty,-- )-- .toList()-- ..sort(-- (a, b) => a['name']!.toLowerCase().compareTo(-- b['name']!.toLowerCase(),-- ),-- );-- _availableNarrators = narrators-- .map(unwrap)-- .where((value) => value.isNotEmpty)-- .toList()-- ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));-- _availableLanguages = languages-- .map(unwrap)-- .where((value) => value.isNotEmpty)-- .toList()-- ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));-- _availablePublishers = publishers-- .map(unwrap)-- .where((value) => value.isNotEmpty)-- .toList()-- ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));-- _availablePublishedDecades = publishedDecades-- .map(unwrap)-- .where((value) => value.isNotEmpty)-- .toList()-- ..sort();++ _availableSeriesFilters =++ series++ .whereType<Map>()++ .map(++ (value) => {++ 'id': value['id']?.toString() ?? '',++ 'name': value['name']?.toString() ?? '',++ },++ )++ .where(++ (value) =>++ value['id']!.isNotEmpty && value['name']!.isNotEmpty,++ )++ .toList()++ ..sort(++ (a, b) => a['name']!.toLowerCase().compareTo(++ b['name']!.toLowerCase(),++ ),++ );++ _availableAuthorFilters =++ authors++ .whereType<Map>()++ .map(++ (value) => {++ 'id': value['id']?.toString() ?? '',++ 'name': value['name']?.toString() ?? '',++ },++ )++ .where(++ (value) =>++ value['id']!.isNotEmpty && value['name']!.isNotEmpty,++ )++ .toList()++ ..sort(++ (a, b) => a['name']!.toLowerCase().compareTo(++ b['name']!.toLowerCase(),++ ),++ );++ _availableNarrators =++ narrators.map(unwrap).where((value) => value.isNotEmpty).toList()++ ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));++ _availableLanguages =++ languages.map(unwrap).where((value) => value.isNotEmpty).toList()++ ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));++ _availablePublishers =++ publishers.map(unwrap).where((value) => value.isNotEmpty).toList()++ ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));++ _availablePublishedDecades =++ publishedDecades++ .map(unwrap)++ .where((value) => value.isNotEmpty)++ .toList()++ ..sort();});}}@@@ -1664,6 -1580,6 +1791,7 @@@// Tapping the same sort toggles direction (except Random)if (newSort == LibrarySort.random) return;setState(() {++ _resetSelectionState();_sortAsc = !_sortAsc;_items.clear();_page = 0;@@@ -1681,6 -1597,6 +1809,7 @@@return;}setState(() {++ _resetSelectionState();_sort = newSort;// Smart defaults: A-Z and Length start ascending, others start descending_sortAsc =@@@ -1881,12 -1797,12 +2010,11 @@@filterValue != 'no-series');_loadGeneration++;setState(() {++ _resetSelectionState();_filter = effective;_genreFilter = effective == LibraryFilter.genre ? genre : null;_tagFilter = effective == LibraryFilter.tag ? tag : null;-- _filterValue = libraryFilterRequiresValue(effective)-- ? filterValue-- : null;++ _filterValue = libraryFilterRequiresValue(effective) ? filterValue : null;_filterValueLabel = _filterValue == null? null: (filterValueLabel ?? filterValue);@@@ -2040,6 -1956,6 +2168,7 @@@void _onSearchChanged(String query) {_debounce?.cancel();++ if (_selectionMode) _clearSelection();// Always show bars when entering/exiting search_revealDriver.resetToShown();if (query.trim().isEmpty) {@@@ -2249,8 -2165,8 +2378,7 @@@LibraryFilter.narrator => _filterValueLabel ?? l.libraryTabNarrators,LibraryFilter.language => _filterValueLabel ?? l.languageLabel,LibraryFilter.publisher => _filterValueLabel ?? l.publisherLabel,-- LibraryFilter.publishedDecade =>-- _filterValueLabel ?? l.publishedDecade,++ LibraryFilter.publishedDecade => _filterValueLabel ?? l.publishedDecade,LibraryFilter.noTracks => l.noTracks,LibraryFilter.singleTrack => l.singleTrack,LibraryFilter.multipleTracks => l.multipleTracks,@@@ -2258,9 -2174,9 +2386,10 @@@LibraryFilter.issues => l.issues,LibraryFilter.feedOpen => l.rssFeedOpen,LibraryFilter.explicit => l.explicitContent,-- LibraryFilter.missingMetadata => _missingMetadataFilter == null-- ? l.missingMetadata-- : missingMetadataFieldLabel(l, _missingMetadataFilter!),++ LibraryFilter.missingMetadata =>++ _missingMetadataFilter == null++ ? l.missingMetadata++ : missingMetadataFieldLabel(l, _missingMetadataFilter!),LibraryFilter.genre => _genreFilter ?? l.genre,LibraryFilter.tag => _tagFilter ?? l.tag,LibraryFilter.none => '',@@@ -2369,6 -2283,6 +2498,7 @@@_listsScrollController.jumpTo(0);} else {setState(() {++ _resetSelectionState();_sortAsc = !_sortAsc;_items.clear();_page = 0;@@@ -2387,24 -2301,24 +2517,25 @@@}Navigator.pop(ctx);},-- onFilterChanged: (-- filter, {-- String? genre,-- String? tag,-- String? filterValue,-- String? filterValueLabel,-- MissingMetadataField? missingMetadata,-- }) {-- Navigator.pop(ctx);-- _changeFilter(-- filter,-- genre: genre,-- tag: tag,-- filterValue: filterValue,-- filterValueLabel: filterValueLabel,-- missingMetadata: missingMetadata,-- );-- },++ onFilterChanged:++ (++ filter, {++ String? genre,++ String? tag,++ String? filterValue,++ String? filterValueLabel,++ MissingMetadataField? missingMetadata,++ }) {++ Navigator.pop(ctx);++ _changeFilter(++ filter,++ genre: genre,++ tag: tag,++ filterValue: filterValue,++ filterValueLabel: filterValueLabel,++ missingMetadata: missingMetadata,++ );++ },onClearFilter: () {Navigator.pop(ctx);_changeFilter(LibraryFilter.none);@@@ -2413,6 -2327,6 +2544,7 @@@onCollapseSeriesChanged: (value) {_loadGeneration++;setState(() {++ _resetSelectionState();_collapseSeries = value;_items.clear();_page = 0;@@@ -2424,8 -2338,8 +2556,9 @@@_loadPage();},isPodcastLibrary: context.read<LibraryProvider>().isPodcastLibrary,-- canAccessExplicitContent:-- context.read<AuthProvider>().canAccessExplicitContent,++ canAccessExplicitContent: context++ .read<AuthProvider>()++ .canAccessExplicitContent,onUpcomingReleases: tab == LibraryTab.series? () {Navigator.pop(ctx);@@@ -2455,6 -2368,6 +2588,7 @@@// or its data changes; the actual lib object is consumed inside// _buildHeaderSliver via context.watch.final libWatch = context.watch<LibraryProvider>();++ final auth = context.watch<AuthProvider>();// Reload the grid when the offline state flips so it swaps between the full// library and the downloads-only offline view.if (libWatch.isOffline != _wasOffline) {@@@ -2462,6 -2375,6 +2596,7 @@@WidgetsBinding.instance.addPostFrameCallback((_) {if (!mounted) return;setState(() {++ _resetSelectionState();_items.clear();_page = 0;_hasMore = true;@@@ -2471,6 -2384,6 +2606,25 @@@});}final hasTabs = _tabController != null && !_isInSearchMode;++ final selectionAvailable =++ desktopWorkspace &&++ !libWatch.isOffline &&++ !_isInSearchMode &&++ (hasTabs ? _currentTab == 0 : _podcastView == 0);++ if (!selectionAvailable && _selectionMode) _resetSelectionState();++ final showCoverControl =++ desktopWorkspace &&++ !_isInSearchMode &&++ (hasTabs ? _currentTab != 3 : _podcastView == 0);++ final selectableItems = selectionAvailable++ ? _selectableVisibleItems()++ : const <Map<String, dynamic>>[];++ if (_selectionMode) {++ _selectedItemIds.retainAll(++ selectableItems.map((item) => item['id'] as String).toSet(),++ );++ }++ final selectableCount = selectableItems.length;return Scaffold(backgroundColor: scaffoldBg,@@@ -2595,6 -2524,6 +2749,53 @@@),],),++ floatingActionButton: !desktopWorkspace++ ? null++ : _selectionMode && selectionAvailable++ ? DesktopBatchActionBar(++ selectedCount: _selectedItemIds.length,++ selectableCount: selectableCount,++ busy: _batchActionBusy,++ canQuickMatch: auth.isAdmin && !libWatch.isPodcastLibrary,++ canMarkProgress: !libWatch.isPodcastLibrary,++ canDelete: auth.canDelete,++ onSelectAll: _toggleSelectAll,++ onClear: _clearSelection,++ onQuickMatch: () => _runBatchAction(++ () => DesktopBatchActions.quickMatch(++ context,++ _selectedItemIds.toList(),++ ),++ ),++ onMarkFinished: () => _runBatchAction(++ () => DesktopBatchActions.setFinished(++ context,++ _selectedItemIds.toList(),++ isFinished: true,++ ),++ ),++ onMarkUnfinished: () => _runBatchAction(++ () => DesktopBatchActions.setFinished(++ context,++ _selectedItemIds.toList(),++ isFinished: false,++ ),++ ),++ onDelete: () => _runBatchAction(++ () => DesktopBatchActions.delete(++ context,++ _selectedItemIds.toList(),++ ),++ ),++ )++ : showCoverControl++ ? DesktopCoverSizeControl(++ value: _bookshelfCoverSize,++ onDecrease: () => _changeBookshelfCoverSize(-1),++ onIncrease: () => _changeBookshelfCoverSize(1),++ )++ : null,++ floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,);}@@@ -2622,19 -2552,41 +2823,24 @@@final screenH = MediaQuery.of(context).size.height;final headerBackground = flatNotifier.value? ColoredBox(color: scaffoldBg)- : ClipRect(- child: OverflowBox(- maxHeight: screenH,- minHeight: 0,- alignment: Alignment.topCenter,- child: Transform.translate(- offset: Offset(0, -topInset),- child: SizedBox(- height: screenH,- width: double.infinity,- child: DecoratedBox(- decoration: BoxDecoration(- color: scaffoldBg,- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- stops: const [0.0, 0.22, 0.72, 1.0],- colors: [- cs.primary.withValues(- alpha: gradientIntensityNotifier.value,- ),- cs.surface,- lowerFade,- scaffoldBg,- ],- ),- ),- ),- ),- ),+ : CustomPaint(+ painter: _LibraryHeaderGradientPainter(+ backgroundColor: scaffoldBg,+ gradient: _libraryBackgroundGradient(cs, scaffoldBg),+ topInset: topInset,+ screenHeight: screenH,),);+ final desktop = isDesktopWorkspace(context);++ final canSelectItems =++ desktop &&++ !lib.isOffline &&++ !_isInSearchMode &&++ (_tabController == null ? _podcastView == 0 : _currentTab == 0);return SliverAppBar(- floating: true,- snap: true,+ floating: !desktop,+ snap: !desktop,+ pinned: desktop,// primary: false disables Material's automatic status// bar padding so the header doesn't get inset twice// (we already wrap the whole NestedScrollView in@@@ -2676,152 -2627,108 +2882,173 @@@}},),-- actions: hasMultipleLibraries-- ? [-- GestureDetector(-- onTap: () => showLibraryPickerSheet(context, lib),-- child: Container(-- padding: const EdgeInsets.symmetric(-- horizontal: 10,-- vertical: 5,-- ),-- decoration: BoxDecoration(-- color: cs.onSurface.withValues(alpha: 0.06),-- borderRadius: BorderRadius.circular(20),-- border: Border.all(-- color: cs.onSurface.withValues(alpha: 0.08),++ actions: [++ if (hasMultipleLibraries)++ GestureDetector(++ onTap: () => showLibraryPickerSheet(context, lib),++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 10,++ vertical: 5,++ ),++ decoration: BoxDecoration(++ color: cs.onSurface.withValues(alpha: 0.06),++ borderRadius: BorderRadius.circular(20),++ border: Border.all(++ color: cs.onSurface.withValues(alpha: 0.08),++ ),++ ),++ child: SizedBox(++ height: 20,++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(++ lib.isPodcastLibrary++ ? Icons.podcasts_rounded++ : Icons.auto_stories_rounded,++ size: 18,++ color: cs.onSurfaceVariant,),-- ),-- child: SizedBox(-- height: 20,-- child: Row(-- mainAxisSize: MainAxisSize.min,-- children: [-- Icon(-- lib.isPodcastLibrary-- ? Icons.podcasts_rounded-- : Icons.auto_stories_rounded,- size: 18,- color: cs.onSurfaceVariant,- ),- const SizedBox(width: 6),- ConstrainedBox(- constraints: const BoxConstraints(- maxWidth: 140,- ),- child: Text(- libraryName,- style: TextStyle(- fontSize: 13,- fontWeight: FontWeight.w600,- color: cs.onSurfaceVariant,- ),- overflow: TextOverflow.ellipsis,- maxLines: 1,- ),- ),- const SizedBox(width: 4),- Icon(- Icons.unfold_more_rounded,-- size: 18,++ const SizedBox(width: 6),++ ConstrainedBox(++ constraints: const BoxConstraints(++ maxWidth: 140,++ ),++ child: Text(++ libraryName,++ style: TextStyle(++ fontSize: 13,++ fontWeight: FontWeight.w600,color: cs.onSurfaceVariant,),- const SizedBox(width: 6),- ConstrainedBox(- constraints: const BoxConstraints(- maxWidth: 140,- ),- child: Text(- libraryName,- style: TextStyle(- fontSize: 13,- fontWeight: FontWeight.w600,- color: cs.onSurfaceVariant,- ),- overflow: TextOverflow.ellipsis,- maxLines: 1,- ),- ),- const SizedBox(width: 4),- Icon(- Icons.unfold_more_rounded,- size: 18,- color: cs.onSurfaceVariant,- ),-- ],++ overflow: TextOverflow.ellipsis,++ maxLines: 1,++ ),),-- ),++ const SizedBox(width: 4),++ Icon(++ Icons.unfold_more_rounded,++ size: 18,++ color: cs.onSurfaceVariant,++ ),++ ],),),-- ]-- : null,-- ),- Builder(builder: (context) {- final searchBar = SearchBar(- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),- child: SearchBar(-- // Same GlobalKey on whichever SearchBar gets the shared-- // focus, so when _isInSearchMode toggles and the tree-- // swaps from tabbed -> search results, Flutter re-parents-- // the existing Element instead of destroying and-- // recreating it. Keeps focus + keyboard alive.-- key: useSharedFocus ? _searchBarKey : null,-- controller: _searchController,-- // Only the active tab's SearchBar binds to the screen--- // level focus node. Inactive tabs' SearchBars use their-- // own internal focus so multiple instances in the-- // IndexedStack don't fight over the same FocusNode (the-- // bug that left tap-to-focus dead until you switched-- // libraries to force a state reset).-- focusNode: useSharedFocus ? _focusNode : null,-- hintText: lib.isPodcastLibrary-- ? l.librarySearchShowsHint-- : l.librarySearchBooksHint,-- leading: const Padding(-- padding: EdgeInsets.only(left: 8),-- child: Icon(Icons.search_rounded),-- ),-- trailing: [-- if (_searchController.text.isNotEmpty)-- IconButton(-- icon: const Icon(Icons.clear_rounded),-- onPressed: () {-- _searchController.clear();-- _onSearchChanged('');-- _focusNode.unfocus();-- },),-- ],-- onChanged: _onSearchChanged,-- padding: const WidgetStatePropertyAll(-- EdgeInsets.symmetric(horizontal: 8),-- ),-- side: WidgetStatePropertyAll(-- BorderSide(color: cs.onSurface.withValues(alpha: 0.08)),-- ),- );- if (!desktop) {- ),++ ),++ if (canSelectItems)++ Tooltip(++ message: _selectionMode++ ? l.downloadsCancelSelection++ : 'Select items',++ child: IconButton(++ onPressed: _selectionMode++ ? _clearSelection++ : () => setState(() => _selectionMode = true),++ icon: Icon(++ _selectionMode++ ? Icons.close_rounded++ : Icons.library_add_check_rounded,++ ),++ ),++ ),++ ],++ ),++ Builder(++ builder: (context) {++ final searchBar = SearchBar(++ // Same GlobalKey on whichever SearchBar gets the shared++ // focus, so when _isInSearchMode toggles and the tree++ // swaps from tabbed -> search results, Flutter re-parents++ // the existing Element instead of destroying and++ // recreating it. Keeps focus + keyboard alive.++ key: useSharedFocus ? _searchBarKey : null,++ controller: _searchController,++ // Only the active tab's SearchBar binds to the screen-++ // level focus node. Inactive tabs' SearchBars use their++ // own internal focus so multiple instances in the++ // IndexedStack don't fight over the same FocusNode (the++ // bug that left tap-to-focus dead until you switched++ // libraries to force a state reset).++ focusNode: useSharedFocus ? _focusNode : null,++ hintText: lib.isPodcastLibrary++ ? l.librarySearchShowsHint++ : l.librarySearchBooksHint,++ leading: const Padding(++ padding: EdgeInsets.only(left: 8),++ child: Icon(Icons.search_rounded),++ ),++ trailing: [++ if (_searchController.text.isNotEmpty)++ IconButton(++ icon: const Icon(Icons.clear_rounded),++ onPressed: () {++ _searchController.clear();++ _onSearchChanged('');++ _focusNode.unfocus();++ },++ ),++ ],++ onChanged: _onSearchChanged,++ padding: const WidgetStatePropertyAll(++ EdgeInsets.symmetric(horizontal: 8),++ ),++ side: WidgetStatePropertyAll(++ BorderSide(color: cs.onSurface.withValues(alpha: 0.08)),++ ),++ );++ if (!desktop) {++ return Padding(++ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),++ child: searchBar,++ );++ }++ final hasBookTabs =++ _tabController != null && !_isInSearchMode;++ final showsPodcastPill =++ !hasBookTabs &&++ lib.isPodcastLibrary &&++ !_isInSearchMode;+ return Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),- child: searchBar,- );- }- final hasBookTabs =- _tabController != null && !_isInSearchMode;- final showsPodcastPill =- !hasBookTabs && lib.isPodcastLibrary && !_isInSearchMode;- return Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),- child: Row(- children: [- Flexible(- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 560),- child: searchBar,++ child: Row(++ children: [++ Flexible(++ child: ConstrainedBox(++ constraints: const BoxConstraints(maxWidth: 560),++ child: searchBar,++ ),+ ),- ),- if (hasBookTabs) ...[- const SizedBox(width: 12),- _buildFloatingTabBar(cs, floating: false),- ],- if (showsPodcastPill) ...[- const SizedBox(width: 12),- _buildPodcastViewPill(cs, floating: false),- if (context.read<AuthProvider>().isAdmin) ...[- const SizedBox(width: 8),- _buildFloatingManageButton(cs),++ if (hasBookTabs) ...[++ const SizedBox(width: 12),++ _buildFloatingTabBar(cs, floating: false),+ ],- ],- const Spacer(),- if (!lib.isOffline)- Tooltip(- message: l.refreshTooltip,- child: IconButton(- onPressed: _refreshCurrentTab,- icon: Icon(Icons.refresh_rounded,- color: cs.onSurfaceVariant),++ if (showsPodcastPill) ...[++ const SizedBox(width: 12),++ _buildPodcastViewPill(cs, floating: false),++ if (context.read<AuthProvider>().isAdmin) ...[++ const SizedBox(width: 8),++ _buildFloatingManageButton(cs),++ ],++ ],++ const Spacer(),++ if (!lib.isOffline)++ Tooltip(++ message: l.refreshTooltip,++ child: IconButton(++ onPressed: _refreshCurrentTab,++ icon: Icon(++ Icons.refresh_rounded,++ color: cs.onSurfaceVariant,++ ),++ ),+ ),- ),- ],- ),- );- }),++ ],++ ),++ );++ },+ ),// Item count + filter badge rowif (!_isInSearchMode) _buildInfoRow(cs, tt, l),],@@@ -2834,81 -2741,9 +3061,78 @@@// Shows | Episodes switcher for podcast libraries, styled like the book// libraries' floating tab pills.- Widget _buildPodcastViewPill(ColorScheme cs) {+ Widget _buildPodcastViewPill(ColorScheme cs, {bool floating = true}) {final l = AppLocalizations.of(context)!;final labels = [l.appShellShowsTab, l.libraryTabEpisodes];+ final pill = Container(- padding: const EdgeInsets.all(4),- decoration: BoxDecoration(- color: floating- ? cs.surface.withValues(alpha: 0.6)- : cs.surfaceContainerLow,- borderRadius: BorderRadius.circular(24),- border: Border.all(- color: floating- ? cs.primary.withValues(alpha: 0.25)- : cs.outlineVariant.withValues(alpha: 0.45),- ),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: List.generate(labels.length, (i) {- final active = _podcastView == i;- return GestureDetector(- onTap: () {- if (!active) {- setState(() => _podcastView = i);- PlayerSettings.setPodcastView(i);- } else if (i == 0) {- // Re-tap on the active Shows pill opens the sort sheet,- // same as the book libraries' pills.- _showSortFilterSheet(- context,- cs,- Theme.of(context).textTheme,- );- }- },- child: AnimatedContainer(- duration: const Duration(milliseconds: 200),- curve: Curves.easeInOut,- padding: EdgeInsets.symmetric(- horizontal: active ? 14 : 12,- vertical: 8,- ),- decoration: BoxDecoration(- color: active- ? cs.primary.withValues(alpha: 0.15)- : Colors.transparent,- borderRadius: BorderRadius.circular(20),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Text(- labels[i],- maxLines: 1,- softWrap: false,- style: TextStyle(- fontSize: 13,- fontWeight: active- ? FontWeight.w700- : FontWeight.w500,- color: active ? cs.primary : cs.onSurfaceVariant,- ),- ),- if (active && i == 0) ...[- const SizedBox(width: 4),- Icon(Icons.sort_rounded, size: 14, color: cs.primary),- ],- ],++ padding: const EdgeInsets.all(4),++ decoration: BoxDecoration(++ color: floating++ ? cs.surface.withValues(alpha: 0.6)++ : cs.surfaceContainerLow,++ borderRadius: BorderRadius.circular(24),++ border: Border.all(++ color: floating++ ? cs.primary.withValues(alpha: 0.25)++ : cs.outlineVariant.withValues(alpha: 0.45),++ ),++ ),++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: List.generate(labels.length, (i) {++ final active = _podcastView == i;++ return GestureDetector(++ onTap: () {++ if (!active) {++ setState(() {++ _podcastView = i;++ _resetSelectionState();++ });++ PlayerSettings.setPodcastView(i);++ } else if (i == 0) {++ // Re-tap on the active Shows pill opens the sort sheet,++ // same as the book libraries' pills.++ _showSortFilterSheet(context, cs, Theme.of(context).textTheme);++ }++ },++ child: AnimatedContainer(++ duration: const Duration(milliseconds: 200),++ curve: Curves.easeInOut,++ padding: EdgeInsets.symmetric(++ horizontal: active ? 14 : 12,++ vertical: 8,++ ),++ decoration: BoxDecoration(++ color: active++ ? cs.primary.withValues(alpha: 0.15)++ : Colors.transparent,++ borderRadius: BorderRadius.circular(20),++ ),++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ Text(++ labels[i],++ maxLines: 1,++ softWrap: false,++ style: TextStyle(++ fontSize: 13,++ fontWeight: active ? FontWeight.w700 : FontWeight.w500,++ color: active ? cs.primary : cs.onSurfaceVariant,++ ),+ ),- ),- );- }),- ),- );++ if (active && i == 0) ...[++ const SizedBox(width: 4),++ Icon(Icons.sort_rounded, size: 14, color: cs.primary),++ ],++ ],++ ),++ ),++ );++ }),++ ),++ );+ if (!floating) return pill;return ClipRRect(borderRadius: BorderRadius.circular(24),child: BackdropFilter(@@@ -2927,84 -2826,6 +3151,76 @@@l.libraryTabNarrators,if (_showLists) 'Lists',];+ final pill = Container(+ padding: const EdgeInsets.all(4),+ decoration: BoxDecoration(+ color: floating+ ? cs.surface.withValues(alpha: 0.6)+ : cs.surfaceContainerLow,+ borderRadius: BorderRadius.circular(24),+ border: Border.all(+ color: floating+ ? cs.primary.withValues(alpha: 0.25)+ : cs.outlineVariant.withValues(alpha: 0.45),+ ),+ ),+ child: FittedBox(+ fit: BoxFit.scaleDown,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: List.generate(labels.length, (i) {+ final active = _currentTab == i;+ return GestureDetector(+ onTap: () {+ if (active) {+ _showSortFilterSheet(+ context,+ cs,+ Theme.of(context).textTheme,+ );+ } else {+ _tabController?.animateTo(i);+ }+ },+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 200),+ curve: Curves.easeInOut,+ padding: EdgeInsets.symmetric(+ horizontal: active ? 14 : 12,+ vertical: 8,+ ),+ decoration: BoxDecoration(+ color: active+ ? cs.primary.withValues(alpha: 0.15)+ : Colors.transparent,+ borderRadius: BorderRadius.circular(20),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ labels[i],+ maxLines: 1,+ softWrap: false,+ style: TextStyle(+ fontSize: 13,- fontWeight: active- ? FontWeight.w700- : FontWeight.w500,- color: active- ? cs.primary- : cs.onSurfaceVariant,++ fontWeight: active ? FontWeight.w700 : FontWeight.w500,++ color: active ? cs.primary : cs.onSurfaceVariant,+ ),+ ),+ if (active) ...[+ const SizedBox(width: 4),- Icon(- Icons.sort_rounded,- size: 14,- color: cs.primary,- ),++ Icon(Icons.sort_rounded, size: 14, color: cs.primary),+ ],+ ],+ ),+ ),+ );+ }),+ ),+ ),+ );+ if (!floating) return pill;return Center(child: Padding(// Inset from the screen edges; the FittedBox below scales the whole@@@ -3219,6 -3110,6 +3435,7 @@@// yet - show a spinner instead of flashing the empty state.isLoading: entries.isEmpty && _cachedHasLists,coverAspectRatio: _coverAspectRatio,++ desktopMaxCrossAxisExtent: _desktopTileMaxExtent,onOpenCollection: (c) {final id = c['id'] as String?;if (id != null && id.isNotEmpty)@@@ -3255,6 -3130,6 +3472,7 @@@final lib = context.read<LibraryProvider>();await lib.refresh();setState(() {++ _resetSelectionState();_items.clear();_page = 0;_hasMore = true;@@@ -3289,6 -3164,6 +3507,7 @@@// ═══════════════════════════════════════════════════════════════Widget _buildGrid(Widget headerSliver) {final lib = context.watch<LibraryProvider>();++ final selectionAvailable = isDesktopWorkspace(context) && !lib.isOffline;return LibraryBooksTab(items: _visibleLibraryItems(lib),isLoadingPage: _isLoadingPage,@@@ -3299,6 -3174,6 +3518,10 @@@isPodcastLibrary: context.read<LibraryProvider>().isPodcastLibrary,rectangleCovers: _rectangleCovers,coverAspectRatio: _coverAspectRatio,++ desktopMaxCrossAxisExtent: _desktopTileMaxExtent,++ selectionMode: selectionAvailable && _selectionMode,++ selectedItemIds: _selectedItemIds,++ onSelectionToggle: selectionAvailable ? _toggleSelection : null,onRefresh: _refreshAll,onClearFilter: () => _changeFilter(LibraryFilter.none),headerSliver: headerSliver,@@@ -3325,6 -3200,6 +3548,7 @@@hasMoreSeries: _hasMoreSeries,rectangleCovers: _rectangleCovers,coverAspectRatio: _coverAspectRatio,++ desktopMaxCrossAxisExtent: _desktopTileMaxExtent,onRefresh: _refreshSeries,headerSliver: headerSliver,scrollController: _seriesScrollController,@@@ -3340,6 -3215,6 +3564,7 @@@authors: _authors,isLoadingAuthors: _isLoadingAuthors,authorsLoaded: _authorsLoaded,++ desktopMaxCrossAxisExtent: _desktopTileMaxExtent,onRefresh: _refreshAuthors,headerSliver: headerSliver,scrollController: _authorsScrollController,diff --cc lib/screens/settings_screen.dartindex fa9528b6,08e55509..dfe86b73--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@@ -319,9 -174,9 +320,14 @@@ class SettingsScreenState extends StateString? _rmabApiToken;bool _loaded = false;int _adminIssueCount = 0;-- AudiobookshelfServerUpdate? _serverUpdate;-- String? _serverUpdateCheckedFor;-- bool _serverUpdateCheckRunning = false;++ final AudiobookshelfUpdateController _serverUpdateController =++ AudiobookshelfUpdateController.instance;++ AudiobookshelfServerUpdate? get _serverUpdate =>++ _serverUpdateController.update;++ String? get _serverUpdateCheckedFor =>++ _serverUpdateController.checkedFor;++ bool get _serverUpdateCheckRunning =>++ _serverUpdateController.isChecking;String _downloadLocationLabel = 'App Internal Storage (Default)';bool _canPickDownloadLocation = false;int _totalDownloadSizeBytes = 0;@@@ -364,6 -214,6 +370,7 @@@void initState() {super.initState();_localServerController = TextEditingController();++ _serverUpdateController.addListener(_onServerUpdateChanged);_loadSettings();_loadAdminIssueCount();SocketService().addItemsChangedListener(_onServerItemsChanged);@@@ -405,12 -255,12 +412,11 @@@}Future<void> _loadServerUpdate(String currentVersion) async {-- _serverUpdateCheckedFor = currentVersion;-- _serverUpdateCheckRunning = true;- final update = await AudiobookshelfUpdateService.check(currentVersion: currentVersion,);- final update = await AudiobookshelfUpdateService.check(currentVersion: currentVersion);-- _serverUpdateCheckRunning = false;-- if (!mounted || _serverUpdateCheckedFor != currentVersion) return;-- setState(() => _serverUpdate = update);++ await _serverUpdateController.check(currentVersion: currentVersion);++ }++++ void _onServerUpdateChanged() {++ if (mounted) setState(() {});}@override@@@ -418,8 -268,7 +424,9 @@@SocketService().removeItemsChangedListener(_onServerItemsChanged);_issueBadgeDebounce?.cancel();PlayerSettings.settingsChanged.removeListener(_onExternalSettingsChange);++ _serverUpdateController.removeListener(_onServerUpdateChanged);_localServerController.dispose();+ _settingsScrollController.dispose();super.dispose();}@@@ -682,14 -563,28 +722,28 @@@);}- Future<void> _editStatsTimeTarget() async {+ Future<void> _editStatsTimeTarget(String period) async {final l = AppLocalizations.of(context)!;- final input = await _promptStatsValue(l.statsGoalEnterTimeHint, TextInputType.datetime);+ final input = await _promptStatsValue(l.statsGoalEnterTimeHint, TextInputType.datetime,);if (input == null) return;- final minutes = _parseGoalMinutes(input);+ final minutes = _parseGoalMinutes(input, period);if (minutes == null) return;- setState(() => _statsGoalMinutes = minutes);- PlayerSettings.setStatsGoalMinutes(minutes);+ _setStatsGoalMinutes(period, minutes);+ }++ void _setStatsGoalMinutes(String period, int minutes) {+ final clamped = minutes.clamp(0, PlayerSettings.maxStatsGoalMinutes(period));+ setState(() => _statsGoalMinutes[period] = clamped);+ PlayerSettings.setStatsGoalMinutesFor(period, clamped);+ }++ /// Switching a period on reinstates whatever target it last held, so the+ /// stored value has to come back from the store rather than being assumed.+ Future<void> _toggleStatsGoal(String period, bool on) async {+ await PlayerSettings.setStatsGoalEnabled(period, on);+ final minutes = await PlayerSettings.getStatsGoalMinutesFor(period);+ if (!mounted) return;+ setState(() => _statsGoalMinutes[period] = minutes);}Future<void> _editStatsBookTarget() async {@@@ -897,17 -792,11 +951,17 @@@PlayerSettings.getFullScreenPlayer(), // 21PlayerSettings.getThemeMode(), // 22PlayerSettings.getSnappyTransitions(), // 23- DownloadService().downloadLocationLabel, // 24- DownloadService().totalDownloadSize, // 25- DownloadService.getDeviceStorage(), // 26+ AppPlatform.isWeb+ ? Future.value('Streaming only')+ : DownloadService().downloadLocationLabel, // 24+ AppPlatform.isWeb+ ? Future.value(0)+ : DownloadService().totalDownloadSize, // 25+ AppPlatform.isWeb+ ? Future<Map<String, int>?>.value(null)+ : DownloadService.getDeviceStorage(), // 26AutoSleepSettings.load(), // 27- PackageInfo.fromPlatform(), // 29+ UpdateCheckerService.currentInstalledVersion(), // 29PlayerSettings.getStreamingCacheSizeMb(), // 30PlayerSettings.getLocalServerEnabled(), // 31PlayerSettings.getLocalServerUrl(), // 32@@@ -1089,10 -979,12 +1144,12 @@@_sleepChimeVolume = chimeVol;_shakeSensitivity = shakeSens;_language = language;- _canPickDownloadLocation = true;+ _canPickDownloadLocation = !AppPlatform.isWeb;- _statsGoalType = statsGoalType;- _statsGoalMinutes = statsGoalMinutes;+ _statsGoalMinutes+ ..clear()+ ..addAll(statsGoalMinutes);_statsBookGoal = statsBookGoal;+ _statsWeekStart = statsWeekStart;_statsChartStyle = statsChartStyle;_statsChartRange = statsChartRange;_statsSectionOrder = statsSectionOrder;@@@ -1956,44 -1798,39 +2101,39 @@@width: double.infinity,child: SegmentedButton<String>(showSelectedIcon: false,+ multiSelectionEnabled: true,+ emptySelectionAllowed: true,segments: [- ButtonSegment(value: 'off', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalOff, maxLines: 1,- ),- ),),- ButtonSegment(value: 'daily', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalDaily, maxLines: 1,- ),- ),),- ButtonSegment(value: 'weekly', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalWeekly, maxLines: 1,- ),- ),),- ButtonSegment(value: 'monthly', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalMonthly, maxLines: 1,- ),- ),),+ for (final p in PlayerSettings.statsGoalPeriods)+ ButtonSegment(+ value: p,+ label: FittedBox(+ fit: BoxFit.scaleDown,+ child: Text(_statsGoalLabel(l, p), maxLines: 1))),],- selected: {_statsGoalType},+ selected: {+ for (final e in _statsGoalMinutes.entries)+ if (e.value > 0) e.key+ },onSelectionChanged: _loaded ? (selected) {- setState(() => _statsGoalType = selected.first,);- PlayerSettings.setStatsGoalType(_statsGoalType,);+ for (final p in PlayerSettings.statsGoalPeriods) {+ final on = selected.contains(p);+ if (on == (_statsGoalMinutes[p]! > 0)) continue;+ _toggleStatsGoal(p, on);+ }} : null,- style: const ButtonStyle(visualDensity: VisualDensity.compact),+ style: const ButtonStyle(visualDensity: VisualDensity.compact,),),),- if (_statsGoalType != 'off')- _statsStepperRow(cs, tt, l.statsGoalTarget,- _statsMinutesLabel(l, _statsGoalMinutes),- onTapValue: _editStatsTimeTarget,- onMinus: _statsGoalMinutes > 5- ? () {- setState(() => _statsGoalMinutes -= 5,);- PlayerSettings.setStatsGoalMinutes(_statsGoalMinutes,);- }- : null,- onPlus: _statsGoalMinutes < 600- ? () {- setState(() => _statsGoalMinutes += 5,);- PlayerSettings.setStatsGoalMinutes(_statsGoalMinutes,);- }- : null,),+ if (_statsGoalMinutes.values.every((m) => m == 0))+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(l.statsGoalOff,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ ),+ for (final p in PlayerSettings.statsGoalPeriods)+ if (_statsGoalMinutes[p]! > 0)+ _statsGoalRow(cs, tt, l, p),],),),@@@ -2941,16 -2687,14 +3107,17 @@@icon: Icons.bedtime_outlined,title: l.sectionSleepTimer,cs: cs,- isExpanded: _expandedSection == 'Sleep Timer',+ isExpanded: expandedSection == 'Sleep Timer',+ desktopMode: isDesktopSettings,onExpansionChanged: (v) => _onSectionExpanded('Sleep Timer', v),children: [-- Padding(++ if (!AppPlatform.isWeb) ...[++ Padding(padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),- child: Text(l.shakeDuringSleepTimer, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),- ),- Padding(+ child: Text(l.shakeDuringSleepTimer, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant,+ ),),- ),- Padding(++ ),++ Padding(padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),child: SizedBox(width: double.infinity,@@@ -2970,51 -2711,47 +3137,51 @@@PlayerSettings.setShakeMode(v.first);SleepTimerService().restartShakeDetection();} : null,++ ),),),-- ),-- if (_shakeMode != 'off') ...[- const Divider(height: 1, indent: 16, endIndent: 16),++ if (_shakeMode != 'off') ...[+ const Divider(height: 1, indent: 16, endIndent: 16,),Padding(- padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4,),child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [- Text(l.shakeSensitivity, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),- Text(_shakeSensitivityLabel(l, _shakeSensitivity),- style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),+ Text(l.shakeSensitivity, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant,+ ),),+ Text(_shakeSensitivityLabel(l, _shakeSensitivity,),+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary,+ ),),],++ ),),-- ),AbsorbSlider(- value: _shakeSensitivityIndex(_shakeSensitivity).toDouble(),+ value: _shakeSensitivityIndex(_shakeSensitivity,).toDouble(),min: 0, max: 4, divisions: 4,onChanged: _loaded ? (v) {- final key = _shakeSensitivityKey(v.round());+ final key = _shakeSensitivityKey(v.round(),);setState(() => _shakeSensitivity = key);PlayerSettings.setShakeSensitivity(key);SleepTimerService().restartShakeDetection();} : null,),const SizedBox(height: 4),-- ],-- if (_shakeMode == 'addTime') ...[- const Divider(height: 1, indent: 16, endIndent: 16),++ ],++ if (_shakeMode == 'addTime') ...[+ const Divider(height: 1, indent: 16, endIndent: 16,),Padding(- padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4,),child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [- Text(l.shakeAdds, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ Text(l.shakeAdds, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant,+ ),),Text(l.shakeAddsValue(_shakeAddMinutes),- style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary,+ ),),],++ ),),-- ),AbsorbSlider(value: _shakeAddMinutes.toDouble(),min: 1, max: 30, divisions: 29,@@@ -3024,8 -2761,8 +3191,9 @@@} : null,),const SizedBox(height: 4),++ ],++ const Divider(height: 1, indent: 16, endIndent: 16),],-- const Divider(height: 1, indent: 16, endIndent: 16),SwitchListTile(title: Text(l.resetTimerOnPause),subtitle: Text(@@@ -3380,12 -3098,12 +3557,13 @@@title: Text(l.autoDownload),subtitle: Text(l.autoDownloadSubtitle,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- leading: Icon(Icons.downloading_rounded, color: cs.primary),+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant,+ ),),+ leading: Icon(Icons.downloading_rounded, color: cs.primary,),),+ _buildAutoDownloadSources(lib, l, cs, tt),Padding(- padding: const EdgeInsets.symmetric(horizontal: 16),+ padding: const EdgeInsets.symmetric(horizontal: 16,),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [diff --cc lib/services/api_service.dartindex 89acf027,fda5e6bd..1e8cd832--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@@ -84,19 -84,19 +84,20 @@@ class MediaUploadResultconst MediaUploadResult({required this.success, this.error});}--enum _RefreshOutcome {-- refreshed,-- rejected,-- transientFailure,--}++class LibraryMetadataRemovalResult {++ final int found;++ final int removed;--enum PasswordChangeStatus {-- success,-- invalidPassword,-- unsupported,-- failed,++ const LibraryMetadataRemovalResult({++ required this.found,++ required this.removed,++ });}++enum _RefreshOutcome { refreshed, rejected, transientFailure }++++enum PasswordChangeStatus { success, invalidPassword, unsupported, failed }++class PasswordChangeResult {final PasswordChangeStatus status;final String? message;@@@ -105,6 -105,6 +106,50 @@@}class ApiService {++ /// Remove sidecar metadata files from every item in a library (admin only).++ /// [extension] is the server-supported sidecar type: `json` or `abs`.++ Future<LibraryMetadataRemovalResult?> removeLibraryMetadataFiles(++ String libraryId,++ String extension,++ ) async {++ if (extension != 'json' && extension != 'abs') {++ throw ArgumentError.value(extension, 'extension', 'Must be json or abs');++ }++ try {++ final uri = Uri.parse(++ '$_cleanBaseUrl/api/libraries/$libraryId/remove-metadata',++ ).replace(queryParameters: {'ext': extension});++ final r = await _authPost(uri, timeout: const Duration(minutes: 30));++ if (r.statusCode != 200) {++ debugPrint('[API] removeLibraryMetadataFiles failed: ${r.statusCode}');++ return null;++ }++ final data = jsonDecode(r.body) as Map<String, dynamic>;++ return LibraryMetadataRemovalResult(++ found: (data['found'] as num?)?.toInt() ?? 0,++ removed: (data['removed'] as num?)?.toInt() ?? 0,++ );++ } catch (e) {++ debugPrint('[API] removeLibraryMetadataFiles error: $e');++ return null;++ }++ }++++ Future<String?> validateCronExpression(String expression) async {++ try {++ final r = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/validate-cron'),++ body: jsonEncode({'expression': expression}),++ );++ if (r.statusCode == 200) return null;++ final message = r.body.trim();++ return message.isEmpty ? 'Invalid cron expression' : message;++ } catch (e) {++ debugPrint('[API] validateCronExpression error: $e');++ return 'Could not validate the cron expression';++ }++ }++static String appVersion = '1.3.0'; // fallback; overwritten by initVersion()static String appBuild = ''; // build number; set by initVersion()@@@ -141,7 -141,7 +186,8 @@@final http.Client? _httpClient;/// Called after a successful token refresh so the auth layer can persist.-- FutureOr<void> Function(String newAccessToken, String? newRefreshToken)? onTokensRefreshed;++ FutureOr<void> Function(String newAccessToken, String? newRefreshToken)?++ onTokensRefreshed;/// Loads the latest persisted tokens before refreshing. Background isolates/// can rotate tokens while this instance is still alive, so the store is the@@@ -170,7 -170,7 +216,8 @@@final prefs = await SharedPreferences.getInstance();var id = prefs.getString('absorb_device_id');if (id == null || id.isEmpty) {-- id = 'absorb-${DateTime.now().millisecondsSinceEpoch.toRadixString(36)}-${(DateTime.now().microsecond * 31337).toRadixString(36)}';++ id =++ 'absorb-${DateTime.now().millisecondsSinceEpoch.toRadixString(36)}-${(DateTime.now().microsecond * 31337).toRadixString(36)}';await prefs.setString('absorb_device_id', id);}deviceId = id;@@@ -187,11 -187,13 +234,13 @@@this.onAuthExpired,Duration refreshRetryDelay = const Duration(milliseconds: 250),http.Client? httpClient,-- }) : _accessToken = token,-- _refreshToken = refreshToken,-- _isLegacyToken = isLegacyToken,-- _refreshRetryDelay = refreshRetryDelay,- _httpClient = httpClient;- _httpClient = httpClient {++ }) : _accessToken = token,++ _refreshToken = refreshToken,++ _isLegacyToken = isLegacyToken,++ _refreshRetryDelay = refreshRetryDelay,++ _httpClient = httpClient {+ _loadCachedServerVersion(baseUrl);+ }/// Current access token (for external use like cover URLs, socket auth).String get token => _accessToken;@@@ -202,16 -204,16 +251,16 @@@static String get userAgent => 'Absorb/$appVersionFull';Map<String, String> get _headers => {-- ...customHeaders,-- 'Authorization': 'Bearer $_accessToken',-- 'Content-Type': 'application/json',-- };++ ...customHeaders,++ 'Authorization': 'Bearer $_accessToken',++ 'Content-Type': 'application/json',++ };/// Public headers for image/audio requests (no Content-Type needed).Map<String, String> get mediaHeaders => {-- ...customHeaders,-- 'Authorization': 'Bearer $_accessToken',-- };++ ...customHeaders,++ 'Authorization': 'Bearer $_accessToken',++ };/// Playback-session tracks use ABS's unguessable public session URLs, so/// only reverse-proxy headers belong on the media request. Keeping the@@@ -222,21 -224,29 +271,39 @@@String get _cleanBaseUrl => normalizeServerUrl(baseUrl);Future<http.Response> _get(Uri url, {Map<String, String>? headers}) {-- return _httpClient?.get(url, headers: headers) ?? http.get(url, headers: headers);++ return _httpClient?.get(url, headers: headers) ??++ http.get(url, headers: headers);}-- Future<http.Response> _post(Uri url, {Map<String, String>? headers, Object? body}) {++ Future<http.Response> _post(++ Uri url, {++ Map<String, String>? headers,++ Object? body,++ }) {return _httpClient?.post(url, headers: headers, body: body) ??http.post(url, headers: headers, body: body);}-- Future<http.Response> _patch(Uri url, {Map<String, String>? headers, Object? body}) {++ Future<http.Response> _patch(++ Uri url, {++ Map<String, String>? headers,++ Object? body,++ }) {return _httpClient?.patch(url, headers: headers, body: body) ??http.patch(url, headers: headers, body: body);}Future<http.Response> _delete(Uri url, {Map<String, String>? headers}) {-- return _httpClient?.delete(url, headers: headers) ?? http.delete(url, headers: headers);++ return _httpClient?.delete(url, headers: headers) ??++ http.delete(url, headers: headers);+ }++ /// Loggable token identity: length plus the signature tail, enough to tell+ /// token A from token B across a log without exposing the credential.+ static String tokenFp(String? token) {+ if (token == null || token.isEmpty) return 'none';+ final tail = token.length <= 8 ? token : token.substring(token.length - 8);+ return '${token.length}:$tail';}Future<bool> _adoptPersistedTokens() async {@@@ -299,10 -317,16 +374,17 @@@if (!kIsWeb) 'User-Agent': userAgent,},).timeout(const Duration(seconds: 15));- if (response.statusCode != 200) return false;+ if (response.statusCode != 200) {+ debugPrint(+ '[API] Proactive token refresh failed: ${response.statusCode} '+ '(refresh=${tokenFp(refreshToken)})',+ );+ return false;+ }final data = jsonDecode(response.body) as Map<String, dynamic>;final tokens = AuthTokens.fromResponse(data);-- if (tokens.accessToken == null || tokens.refreshToken == null) return false;++ if (tokens.accessToken == null || tokens.refreshToken == null)++ return false;_accessToken = tokens.accessToken!;_refreshToken = tokens.refreshToken!;await _notifyTokensRefreshed();@@@ -317,7 -345,7 +403,9 @@@/// an explicit 401/403 can expire the local session.Future<_RefreshOutcome> _refreshAccessToken() async {if (_isLegacyToken || _refreshToken == null) {-- debugPrint('[API] Cannot refresh: isLegacy=$_isLegacyToken, hasRefreshToken=${_refreshToken != null}');++ debugPrint(++ '[API] Cannot refresh: isLegacy=$_isLegacyToken, hasRefreshToken=${_refreshToken != null}',++ );return _RefreshOutcome.transientFailure;}@@@ -398,12 -440,12 +500,17 @@@}/// Make an authenticated GET request, retrying once on 401 with a refreshed token.-- Future<http.Response> _authGet(Uri url, {Map<String, String>? headers, Duration timeout = const Duration(seconds: 15)}) async {--++ Future<http.Response> _authGet(++ Uri url, {++ Map<String, String>? headers,++ Duration timeout = const Duration(seconds: 15),++ }) async {final h = headers ?? _headers;var response = await _get(url, headers: h).timeout(timeout);if (response.statusCode == 401) {-- debugPrint('[API] 401 on GET ${url.path} - isLegacy=$_isLegacyToken, hasRefresh=${_refreshToken != null}, tokenLen=${_accessToken.length}');++ debugPrint(++ '[API] 401 on GET ${url.path} - isLegacy=$_isLegacyToken, hasRefresh=${_refreshToken != null}, tokenLen=${_accessToken.length}',++ );}if (response.statusCode == 401 && !_isLegacyToken) {final outcome = await _refreshAccessToken();@@@ -422,8 -464,8 +529,12 @@@}/// Make an authenticated POST request, retrying once on 401 with a refreshed token.-- Future<http.Response> _authPost(Uri url, {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) async {--++ Future<http.Response> _authPost(++ Uri url, {++ Map<String, String>? headers,++ Object? body,++ Duration timeout = const Duration(seconds: 15),++ }) async {final h = headers ?? _headers;var response = await _post(url, headers: h, body: body).timeout(timeout);if (response.statusCode == 401 && !_isLegacyToken) {@@@ -431,7 -473,7 +542,11 @@@if (outcome == _RefreshOutcome.refreshed) {final refreshedHeaders = Map<String, String>.from(h)..['Authorization'] = 'Bearer $_accessToken';-- response = await _post(url, headers: refreshedHeaders, body: body).timeout(timeout);++ response = await _post(++ url,++ headers: refreshedHeaders,++ body: body,++ ).timeout(timeout);}if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();}@@@ -439,7 -481,7 +554,12 @@@}/// Make an authenticated PATCH request, retrying once on 401 with a refreshed token.-- Future<http.Response> _authPatch(Uri url, {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) async {++ Future<http.Response> _authPatch(++ Uri url, {++ Map<String, String>? headers,++ Object? body,++ Duration timeout = const Duration(seconds: 15),++ }) async {final h = headers ?? _headers;var response = await _patch(url, headers: h, body: body).timeout(timeout);if (response.statusCode == 401 && !_isLegacyToken) {@@@ -447,7 -489,7 +567,11 @@@if (outcome == _RefreshOutcome.refreshed) {final refreshedHeaders = Map<String, String>.from(h)..['Authorization'] = 'Bearer $_accessToken';-- response = await _patch(url, headers: refreshedHeaders, body: body).timeout(timeout);++ response = await _patch(++ url,++ headers: refreshedHeaders,++ body: body,++ ).timeout(timeout);}if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();}@@@ -455,7 -497,7 +579,11 @@@}/// Make an authenticated DELETE request, retrying once on 401 with a refreshed token.-- Future<http.Response> _authDelete(Uri url, {Map<String, String>? headers, Duration timeout = const Duration(seconds: 15)}) async {++ Future<http.Response> _authDelete(++ Uri url, {++ Map<String, String>? headers,++ Duration timeout = const Duration(seconds: 15),++ }) async {final h = headers ?? _headers;var response = await _delete(url, headers: h).timeout(timeout);if (response.statusCode == 401 && !_isLegacyToken) {@@@ -463,7 -505,7 +591,10 @@@if (outcome == _RefreshOutcome.refreshed) {final refreshedHeaders = Map<String, String>.from(h)..['Authorization'] = 'Bearer $_accessToken';-- response = await _delete(url, headers: refreshedHeaders).timeout(timeout);++ response = await _delete(++ url,++ headers: refreshedHeaders,++ ).timeout(timeout);}if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();}@@@ -515,10 -557,10 +646,12 @@@final url = '${base}api/me';try {-- final response = await http.get(-- Uri.parse(url),-- headers: {...customHeaders, 'Authorization': 'Bearer $apiKey'},-- ).timeout(const Duration(seconds: 15));++ final response = await http++ .get(++ Uri.parse(url),++ headers: {...customHeaders, 'Authorization': 'Bearer $apiKey'},++ )++ .timeout(const Duration(seconds: 15));if (response.statusCode == 200) {return (jsonDecode(response.body) as Map<String, dynamic>, 200);@@@ -530,12 -572,12 +663,19 @@@}/// Ping the server to check connectivity.-- static Future<bool> pingServer(String serverUrl, {Map<String, String> customHeaders = const {}}) async {++ static Future<bool> pingServer(++ String serverUrl, {++ Map<String, String> customHeaders = const {},++ }) async {final url = serverUrl.endsWith('/')? '${serverUrl}ping': '$serverUrl/ping';try {-- final response = await http.get(Uri.parse(url), headers: customHeaders.isNotEmpty ? customHeaders : null)++ final response = await http++ .get(++ Uri.parse(url),++ headers: customHeaders.isNotEmpty ? customHeaders : null,++ ).timeout(const Duration(seconds: 10));return response.statusCode == 200;} catch (_) {@@@ -553,13 -595,13 +693,21 @@@String serverUrl, {Map<String, String> customHeaders = const {},}) async {-- final url = serverUrl.endsWith('/') ? '${serverUrl}ping' : '$serverUrl/ping';++ final url = serverUrl.endsWith('/')++ ? '${serverUrl}ping'++ : '$serverUrl/ping';try {final response = await http-- .get(Uri.parse(url), headers: customHeaders.isNotEmpty ? customHeaders : null)++ .get(++ Uri.parse(url),++ headers: customHeaders.isNotEmpty ? customHeaders : null,++ ).timeout(const Duration(seconds: 15));if (response.statusCode == 200) return (ok: true, detail: null);-- return (ok: false, detail: 'Server returned HTTP ${response.statusCode} instead of 200.');++ return (++ ok: false,++ detail: 'Server returned HTTP ${response.statusCode} instead of 200.',++ );} catch (e) {return (ok: false, detail: _describePingError(e));}@@@ -574,10 -616,10 +722,13 @@@}final msg = e.toString();final lower = msg.toLowerCase();-- if (lower.contains('failed host lookup') || lower.contains('nodename nor servname')) {++ if (lower.contains('failed host lookup') ||++ lower.contains('nodename nor servname')) {return 'Could not resolve the domain (DNS). Check the address is spelled right. ($msg)';}-- if (lower.contains('handshake') || lower.contains('certificate') || lower.contains('tls')) {++ if (lower.contains('handshake') ||++ lower.contains('certificate') ||++ lower.contains('tls')) {return 'Secure connection (TLS) failed. If your server uses a self-signed certificate, turn on Trust all certificates above. Otherwise the server may be blocking non-browser apps. ($msg)';}if (lower.contains('connection refused')) {@@@ -588,19 -630,19 +739,27 @@@lower.contains('protocol error')) {return 'The server closed the connection early. This can happen when a proxy only speaks HTTP/2. ($msg)';}-- if (lower.contains('connection reset') || lower.contains('connection terminated')) {++ if (lower.contains('connection reset') ||++ lower.contains('connection terminated')) {return 'The connection was reset, which usually means a proxy or firewall is blocking the app even though browsers get through. ($msg)';}return msg;}/// Get the server version via the /status endpoint (no auth needed).-- static Future<String?> getServerVersion(String serverUrl, {Map<String, String> customHeaders = const {}}) async {++ static Future<String?> getServerVersion(++ String serverUrl, {++ Map<String, String> customHeaders = const {},++ }) async {final url = serverUrl.endsWith('/')? '${serverUrl}status': '$serverUrl/status';try {-- final response = await http.get(Uri.parse(url), headers: customHeaders.isNotEmpty ? customHeaders : null)++ final response = await http++ .get(++ Uri.parse(url),++ headers: customHeaders.isNotEmpty ? customHeaders : null,++ ).timeout(const Duration(seconds: 10));if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;@@@ -610,6 -654,71 +771,73 @@@return null;}+ // Last-known version per server origin. Stream URL shape depends on the+ // server's capabilities, and buildTrackUrl is synchronous, so the version+ // has to already be in memory by the time playback starts. Persisted per+ // origin and re-hydrated on construction to cover cold starts where the+ // /status fetch hasn't answered yet.+ static final Map<String, String> _serverVersions = {};+ static final Set<String> _serverVersionLoads = {};++ static String? _originOf(String url) {+ try {+ return Uri.parse(normalizeServerUrl(url)).origin;+ } catch (_) {+ return null;+ }+ }++ /// Remember [version] for the server at [serverUrl], in memory and in prefs.+ /// Called from every place a version is learned: login responses, /status,+ /// and admin settings saves.+ static void cacheServerVersion(String serverUrl, String? version) {+ if (version == null || version.isEmpty) return;+ final origin = _originOf(serverUrl);+ if (origin == null) return;+ _serverVersionLoads.add(origin);+ if (_serverVersions[origin] == version) return;+ _serverVersions[origin] = version;+ unawaited(+ SharedPreferences.getInstance()+ .then((p) => p.setString('server_version_$origin', version))+ .catchError((Object _) => false),+ );+ }++ static void _loadCachedServerVersion(String serverUrl) {+ final origin = _originOf(serverUrl);+ if (origin == null || !_serverVersionLoads.add(origin)) return;+ unawaited(- SharedPreferences.getInstance().then((p) {- final v = p.getString('server_version_$origin');- if (v != null && v.isNotEmpty) {- _serverVersions.putIfAbsent(origin, () => v);- }- }).catchError((Object _) {}),++ SharedPreferences.getInstance()++ .then((p) {++ final v = p.getString('server_version_$origin');++ if (v != null && v.isNotEmpty) {++ _serverVersions.putIfAbsent(origin, () => v);++ }++ })++ .catchError((Object _) {}),+ );+ }++ /// True when [version] parses as `major.minor[.patch]` (optionally with a+ /// leading `v`) and is at least [major].[minor]. Unparseable = false.+ static bool serverVersionAtLeast(String? version, int major, int minor) {+ final m = RegExp(r'^\s*v?(\d+)\.(\d+)').firstMatch(version ?? '');+ if (m == null) return false;+ final vMajor = int.parse(m.group(1)!);+ if (vMajor != major) return vMajor > major;+ return int.parse(m.group(2)!) >= minor;+ }++ /// Whether this server has the tokenless public session track endpoint+ /// (added in Audiobookshelf v2.22.0). False while the version is unknown,+ /// which safely degrades to the tokened URL form.+ bool get _hasPublicSessionTracks {+ final origin = _originOf(_cleanBaseUrl);+ if (origin == null) return false;+ return serverVersionAtLeast(_serverVersions[origin], 2, 22);+ }+/// Get all libraries.Future<List<dynamic>> getLibraries() async {try {@@@ -652,8 -761,8 +880,9 @@@if (limit != null) query['limit'] = '$limit';final response = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/personalized')-- .replace(queryParameters: query.isEmpty ? null : query),++ Uri.parse(++ '$_cleanBaseUrl/api/libraries/$libraryId/personalized',++ ).replace(queryParameters: query.isEmpty ? null : query),);if (response.statusCode == 200) {@@@ -684,7 -793,7 +913,8 @@@bool collapseSeries = false,}) async {try {-- var url = '$_cleanBaseUrl/api/libraries/$libraryId/items'++ var url =++ '$_cleanBaseUrl/api/libraries/$libraryId/items''?page=$page&limit=$limit&sort=$sort&desc=$desc'// Ask the server to populate numEpisodesIncomplete on podcast items// so podcast tiles can show an unplayed-count badge without loading@@@ -693,9 -802,9 +923,7 @@@if (filter != null) url += '&filter=$filter';if (expanded) url += '&minified=0';if (collapseSeries) url += '&collapseseries=1';-- final response = await _authGet(-- Uri.parse(url),-- );++ final response = await _authGet(Uri.parse(url));if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;@@@ -754,7 -863,7 +982,8 @@@try {final response = await _authPost(Uri.parse('$_cleanBaseUrl/api/authorize'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;}@@@ -770,7 -879,7 +999,8 @@@try {final response = await _authGet(Uri.parse('$_cleanBaseUrl/api/me'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;@@@ -787,7 -896,7 +1017,8 @@@try {final response = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/progress'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;return (data['mediaProgress'] as List<dynamic>? ?? const [])@@@ -810,7 -919,7 +1041,8 @@@try {final response = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/bookmarks'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;return (data['bookmarks'] as List<dynamic>? ?? const [])@@@ -828,16 -937,16 +1060,22 @@@}}-- Future<AuthSessionsResult> getAuthSessions({int page = 0, int itemsPerPage = 20}) async {++ Future<AuthSessionsResult> getAuthSessions({++ int page = 0,++ int itemsPerPage = 20,++ }) async {try {final refreshToken = _refreshToken;final response = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/me/sessions?page=$page&itemsPerPage=$itemsPerPage'),++ Uri.parse(++ '$_cleanBaseUrl/api/me/sessions?page=$page&itemsPerPage=$itemsPerPage',++ ),headers: {..._headers,if (refreshToken != null) 'x-refresh-token': refreshToken,},-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 404) {return const AuthSessionsResult(AuthSessionsStatus.unsupported);}@@@ -847,7 -956,7 +1085,8 @@@final data = jsonDecode(response.body) as Map<String, dynamic>;return AuthSessionsResult(AuthSessionsStatus.supported,-- AuthSessionsPage.fromJson(data));++ AuthSessionsPage.fromJson(data),++ );} catch (e) {debugPrint('[API] getAuthSessions error: $e');return const AuthSessionsResult(AuthSessionsStatus.failed);@@@ -859,7 -968,7 +1098,8 @@@try {final response = await _authDelete(Uri.parse('$_cleanBaseUrl/api/me/sessions/${session.id}'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return response.statusCode >= 200 && response.statusCode < 300;} catch (e) {debugPrint('[API] deleteAuthSession error: $e');@@@ -878,7 -987,7 +1118,8 @@@...customHeaders,'x-refresh-token': refreshToken,if (!kIsWeb) 'User-Agent': userAgent,-- }).timeout(const Duration(seconds: 10));++ },++ ).timeout(const Duration(seconds: 10));return response.statusCode >= 200 && response.statusCode < 300;} catch (e) {debugPrint('[API] logout error: $e');@@@ -894,14 -1003,14 +1135,17 @@@try {await _adoptPersistedTokens();Future<http.Response> sendPasswordChange() => _patch(-- Uri.parse('$_cleanBaseUrl/api/me/password'),-- headers: {-- ..._headers,-- if (_refreshToken != null) 'x-refresh-token': _refreshToken!,-- if (!kIsWeb) 'User-Agent': userAgent,-- },-- body: jsonEncode({'password': currentPassword, 'newPassword': newPassword})-- ).timeout(const Duration(seconds: 15));++ Uri.parse('$_cleanBaseUrl/api/me/password'),++ headers: {++ ..._headers,++ if (_refreshToken != null) 'x-refresh-token': _refreshToken!,++ if (!kIsWeb) 'User-Agent': userAgent,++ },++ body: jsonEncode({++ 'password': currentPassword,++ 'newPassword': newPassword,++ }),++ ).timeout(const Duration(seconds: 15));var response = await sendPasswordChange();if (response.statusCode == 401 && !_isLegacyToken) {@@@ -917,7 -1026,7 +1161,8 @@@if (response.statusCode == 400) {return PasswordChangeResult(PasswordChangeStatus.invalidPassword,-- message: response.body.trim().isEmpty ? null : response.body.trim());++ message: response.body.trim().isEmpty ? null : response.body.trim(),++ );}if (response.statusCode != 200) {return const PasswordChangeResult(PasswordChangeStatus.failed);@@@ -959,7 -1068,7 +1204,8 @@@try {final response = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/listening-stats'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;@@@ -969,11 -1078,11 +1215,17 @@@}/// Get user's listening sessions (paginated).-- Future<Map<String, dynamic>?> getListeningSessions({int page = 0, int itemsPerPage = 20}) async {++ Future<Map<String, dynamic>?> getListeningSessions({++ int page = 0,++ int itemsPerPage = 20,++ }) async {try {final response = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/me/listening-sessions?itemsPerPage=$itemsPerPage&page=$page'),-- timeout: const Duration(seconds: 10));++ Uri.parse(++ '$_cleanBaseUrl/api/me/listening-sessions?itemsPerPage=$itemsPerPage&page=$page',++ ),++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;@@@ -998,10 -1107,10 +1250,9 @@@try {while (true) {-- final uri = Uri.parse(endpoint).replace(queryParameters: {-- 'itemsPerPage': '$itemsPerPage',-- 'page': '$page',-- });++ final uri = Uri.parse(endpoint).replace(++ queryParameters: {'itemsPerPage': '$itemsPerPage', 'page': '$page'},++ );final response = await _authGet(uri,timeout: const Duration(seconds: 10),@@@ -1025,11 -1134,11 +1276,18 @@@}/// Get a specific user's listening sessions (admin, paginated).-- Future<Map<String, dynamic>?> getUserListeningSessions(String userId, {int page = 0, int itemsPerPage = 10}) async {++ Future<Map<String, dynamic>?> getUserListeningSessions(++ String userId, {++ int page = 0,++ int itemsPerPage = 10,++ }) async {try {final response = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/users/$userId/listening-sessions?itemsPerPage=$itemsPerPage&page=$page'),-- timeout: const Duration(seconds: 10));++ Uri.parse(++ '$_cleanBaseUrl/api/users/$userId/listening-sessions?itemsPerPage=$itemsPerPage&page=$page',++ ),++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;}@@@ -1065,7 -1174,7 +1323,8 @@@/// Build an author image URL.String getAuthorImageUrl(String authorId, {int width = 200, int? updatedAt}) {-- var url = '$_cleanBaseUrl/api/authors/$authorId/image?width=$width&token=$token';++ var url =++ '$_cleanBaseUrl/api/authors/$authorId/image?width=$width&token=$token';if (updatedAt != null) url += '&ts=$updatedAt';return url;}@@@ -1097,11 -1206,11 +1356,10 @@@}) async {try {final filterValue = base64Encode(utf8.encode(authorId));-- final url = '$_cleanBaseUrl/api/libraries/$libraryId/items'++ final url =++ '$_cleanBaseUrl/api/libraries/$libraryId/items''?filter=authors.$filterValue&sort=media.metadata.title&limit=$limit';-- final response = await _authGet(-- Uri.parse(url),-- );++ final response = await _authGet(Uri.parse(url));if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;@@@ -1157,11 -1266,11 +1415,10 @@@}) async {try {final filterValue = base64Encode(utf8.encode(narratorName));-- final url = '$_cleanBaseUrl/api/libraries/$libraryId/items'++ final url =++ '$_cleanBaseUrl/api/libraries/$libraryId/items''?filter=narrators.$filterValue&sort=media.metadata.title&limit=$limit';-- final response = await _authGet(-- Uri.parse(url),-- );++ final response = await _authGet(Uri.parse(url));if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;@@@ -1174,13 -1283,13 +1431,14 @@@}/// Get full author details including description/bio.-- Future<Map<String, dynamic>?> getAuthorById(String authorId, {String? libraryId}) async {++ Future<Map<String, dynamic>?> getAuthorById(++ String authorId, {++ String? libraryId,++ }) async {try {var url = '$_cleanBaseUrl/api/authors/$authorId?include=items';if (libraryId != null) url += '&library=$libraryId';-- final response = await _authGet(-- Uri.parse(url),-- );++ final response = await _authGet(Uri.parse(url));if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;@@@ -1222,7 -1331,7 +1480,9 @@@}return {'ok': true, 'author': data['author'] ?? data};}-- } catch (e) { debugPrint('updateAuthor error: $e'); }++ } catch (e) {++ debugPrint('updateAuthor error: $e');++ }return {'ok': false};}@@@ -1246,10 -1355,10 +1506,13 @@@final data = jsonDecode(r.body) as Map<String, dynamic>;// Server signals no match with { updated: false } and no author payload.if (data['updated'] == false) return null;-- if (data['author'] is Map) return data['author'] as Map<String, dynamic>;++ if (data['author'] is Map)++ return data['author'] as Map<String, dynamic>;return data;}-- } catch (e) { debugPrint('matchAuthor error: $e'); }++ } catch (e) {++ debugPrint('matchAuthor error: $e');++ }return null;}@@@ -1264,7 -1373,7 +1527,9 @@@);debugPrint('[API] updateAuthorImageFromUrl $authorId -> ${r.statusCode}');return r.statusCode == 200;-- } catch (e) { debugPrint('updateAuthorImageFromUrl error: $e'); }++ } catch (e) {++ debugPrint('updateAuthorImageFromUrl error: $e');++ }return false;}@@@ -1276,7 -1385,7 +1541,9 @@@Uri.parse('$_cleanBaseUrl/api/authors/$authorId/image'),);return r.statusCode == 200;-- } catch (e) { debugPrint('deleteAuthorImage error: $e'); }++ } catch (e) {++ debugPrint('deleteAuthorImage error: $e');++ }return false;}@@@ -1289,12 -1398,12 +1556,11 @@@}) async {try {final filterValue = base64Encode(utf8.encode(seriesId));-- final url = '$_cleanBaseUrl/api/libraries/$libraryId/items'++ final url =++ '$_cleanBaseUrl/api/libraries/$libraryId/items''?filter=series.$filterValue''&sort=media.metadata.series.sequence&limit=$limit&collapseseries=0';-- final response = await _authGet(-- Uri.parse(url),-- );++ final response = await _authGet(Uri.parse(url));if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;@@@ -1312,22 -1421,22 +1578,32 @@@/// The device descriptor ABS attaches to playback sessions. Shared by the/// /play session calls and the client-owned local-session calls.Map<String, dynamic> get _deviceInfo => {-- 'clientName': 'Absorb',-- 'clientVersion': appVersion,-- 'deviceId': deviceId,-- 'deviceName': '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'.trim(),-- 'manufacturer': deviceManufacturer,-- 'model': deviceModel,-- };++ 'clientName': 'Absorb',++ 'clientVersion': appVersion,++ 'deviceId': deviceId,++ 'deviceName':++ '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'++ .trim(),++ 'manufacturer': deviceManufacturer,++ 'model': deviceModel,++ };/// Start a playback session for a library item./// POST /api/items/:id/play/// Returns the full session object including audioTracks with contentUrl.-- Future<Map<String, dynamic>?> startPlaybackSession(String itemId, {String? episodeId, bool forceDirectPlay = false, bool forceTranscode = false, double? startOffset}) async {++ Future<Map<String, dynamic>?> startPlaybackSession(++ String itemId, {++ String? episodeId,++ bool forceDirectPlay = false,++ bool forceTranscode = false,++ double? startOffset,++ }) async {try {final epPath = episodeId != null ? '/$episodeId' : '';final url = '$_cleanBaseUrl/api/items/$itemId/play$epPath';-- debugPrint('[ABS] Starting playback session: POST $url (forceDirectPlay: $forceDirectPlay, forceTranscode: $forceTranscode)');++ debugPrint(++ '[ABS] Starting playback session: POST $url (forceDirectPlay: $forceDirectPlay, forceTranscode: $forceTranscode)',++ );final body = <String, dynamic>{'deviceInfo': _deviceInfo,'forceDirectPlay': !forceTranscode,@@@ -1351,11 -1460,11 +1627,13 @@@'audio/x-ms-wma',],};-- if (startOffset != null && startOffset > 0) body['startOffset'] = startOffset;++ if (startOffset != null && startOffset > 0)++ body['startOffset'] = startOffset;final response = await _authPost(Uri.parse(url),body: jsonEncode(body),-- timeout: const Duration(seconds: 20));++ timeout: const Duration(seconds: 20),++ );debugPrint('[ABS] Play session response: ${response.statusCode}');if (response.statusCode == 200) {@@@ -1365,7 -1474,7 +1643,9 @@@debugPrint('[ABS] Audio tracks: ${tracks?.length ?? 0}');if (tracks != null && tracks.isNotEmpty) {final firstTrack = tracks.first as Map<String, dynamic>;-- debugPrint('[ABS] First track contentUrl: ${firstTrack['contentUrl']}');++ debugPrint(++ '[ABS] First track contentUrl: ${firstTrack['contentUrl']}',++ );}return data;} else {@@@ -1446,7 -1577,7 +1748,8 @@@'duration': duration,'progress': duration > 0 ? currentTime / duration : 0,}),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return response.statusCode == 200;} catch (_) {return false;@@@ -1459,7 -1590,7 +1762,8 @@@try {await _authPost(Uri.parse('$_cleanBaseUrl/api/session/$sessionId/close'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );} catch (_) {}}@@@ -1468,7 -1599,7 +1772,9 @@@/// client-supplied date/timestamps, unlike /play which forces Direct Play./// [session] is a fully-built session map; deviceInfo/mediaPlayer/playMethod/// are stamped here so they can't be omitted.-- Future<LocalSessionResult> syncLocalSession(Map<String, dynamic> session) async {++ Future<LocalSessionResult> syncLocalSession(++ Map<String, dynamic> session,++ ) async {try {final body = {...session,@@@ -1479,7 -1610,7 +1785,8 @@@final resp = await _authPost(Uri.parse('$_cleanBaseUrl/api/session/local'),body: jsonEncode(body),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return LocalSessionResult(ok: resp.statusCode == 200,serverTooOld: resp.statusCode == 404 || resp.statusCode == 501,@@@ -1492,8 -1623,8 +1799,10 @@@/// Batch-upsert local sessions, used to replay the offline queue on reconnect./// POST /api/session/local-allFuture<LocalSessionResult> syncLocalSessionsAll(-- List<Map<String, dynamic>> sessions) async {-- if (sessions.isEmpty) return const LocalSessionResult(ok: true, serverTooOld: false);++ List<Map<String, dynamic>> sessions,++ ) async {++ if (sessions.isEmpty)++ return const LocalSessionResult(ok: true, serverTooOld: false);try {final body = {'sessions': sessions@@@ -1504,7 -1635,7 +1813,8 @@@final resp = await _authPost(Uri.parse('$_cleanBaseUrl/api/session/local-all'),body: jsonEncode(body),-- timeout: const Duration(seconds: 20));++ timeout: const Duration(seconds: 20),++ );return LocalSessionResult(ok: resp.statusCode == 200,serverTooOld: resp.statusCode == 404 || resp.statusCode == 501,@@@ -1524,7 -1655,7 +1834,8 @@@final resp = await _authPost(Uri.parse('$_cleanBaseUrl/api/session/local'),body: jsonEncode(session),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return resp.statusCode == 200;} catch (_) {return false;@@@ -1537,7 -1668,7 +1848,8 @@@try {final resp = await _authDelete(Uri.parse('$_cleanBaseUrl/api/sessions/$sessionId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return resp.statusCode == 200;} catch (_) {return false;@@@ -1555,7 -1686,7 +1867,8 @@@: itemId;final resp = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -1688,8 -1819,8 +2001,11 @@@final resp = await _authPatch(Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),body: body,-- timeout: const Duration(seconds: 10));-- debugPrint('[API] updateProgress response: ${resp.statusCode} ${resp.body}');++ timeout: const Duration(seconds: 10),++ );++ debugPrint(++ '[API] updateProgress response: ${resp.statusCode} ${resp.body}',++ );} catch (e) {debugPrint('[API] updateProgress error: $e');rethrow;@@@ -1717,13 -1848,13 +2033,19 @@@final progressPath = itemId.length > 36? '${itemId.substring(0, 36)}/${itemId.substring(37)}': itemId;-- debugPrint('[API] updateEbookProgress PATCH /api/me/progress/$progressPath');-- final resp = await http.patch(-- Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),-- headers: _headers,-- body: body,-- ).timeout(const Duration(seconds: 10));-- debugPrint('[API] updateEbookProgress response: ${resp.statusCode} ${resp.body}');++ debugPrint(++ '[API] updateEbookProgress PATCH /api/me/progress/$progressPath',++ );++ final resp = await http++ .patch(++ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),++ headers: _headers,++ body: body,++ )++ .timeout(const Duration(seconds: 10));++ debugPrint(++ '[API] updateEbookProgress response: ${resp.statusCode} ${resp.body}',++ );return resp.statusCode >= 200 && resp.statusCode < 300;} catch (e) {debugPrint('[API] updateEbookProgress error: $e');@@@ -1742,7 -1873,7 +2064,8 @@@}/// Mark a book as not finished (reset progress to a position).-- Future<void> markNotFinished(String itemId, {++ Future<void> markNotFinished(++ String itemId, {required double currentTime,required double duration,}) async {@@@ -1767,14 -1898,14 +2090,22 @@@// DELETE progress entryawait _authDelete(Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );// Start session at 0 and close — forces server to update position-- final sessionData = await startPlaybackSession(apiItemId, episodeId: episodeId);++ final sessionData = await startPlaybackSession(++ apiItemId,++ episodeId: episodeId,++ );if (sessionData != null) {final sessionId = sessionData['id'] as String?;if (sessionId != null) {-- await syncPlaybackSession(sessionId, currentTime: 0, duration: duration);++ await syncPlaybackSession(++ sessionId,++ currentTime: 0,++ duration: duration,++ );await closePlaybackSession(sessionId);}}@@@ -1789,7 -1920,7 +2120,8 @@@'hideFromContinueListening': true,'lastUpdate': DateTime.now().millisecondsSinceEpoch,}),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return true;} catch (e) {@@@ -1803,8 -1934,8 +2135,11 @@@Future<bool> removeSeriesFromContinueListening(String seriesId) async {try {final resp = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/me/series/$seriesId/remove-from-continue-listening'),-- timeout: const Duration(seconds: 10));++ Uri.parse(++ '$_cleanBaseUrl/api/me/series/$seriesId/remove-from-continue-listening',++ ),++ timeout: const Duration(seconds: 10),++ );return resp.statusCode == 200;} catch (e) {debugPrint('[API] removeSeriesFromContinueListening error: $e');@@@ -1818,8 -1949,8 +2153,11 @@@Future<bool> removeItemFromContinueListening(String mediaProgressId) async {try {final resp = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/me/progress/$mediaProgressId/remove-from-continue-listening'),-- timeout: const Duration(seconds: 10));++ Uri.parse(++ '$_cleanBaseUrl/api/me/progress/$mediaProgressId/remove-from-continue-listening',++ ),++ timeout: const Duration(seconds: 10),++ );return resp.statusCode == 200;} catch (e) {debugPrint('[API] removeItemFromContinueListening error: $e');@@@ -1832,10 -1963,10 +2170,15 @@@/// Start a playback session for a podcast episode./// POST /api/items/:itemId/play/:episodeIdFuture<Map<String, dynamic>?> startEpisodePlaybackSession(-- String itemId, String episodeId, {bool forceTranscode = false}) async {++ String itemId,++ String episodeId, {++ bool forceTranscode = false,++ }) async {try {final url = '$_cleanBaseUrl/api/items/$itemId/play/$episodeId';-- debugPrint('[ABS] Starting episode session: POST $url (forceTranscode: $forceTranscode)');++ debugPrint(++ '[ABS] Starting episode session: POST $url (forceTranscode: $forceTranscode)',++ );final response = await _authPost(Uri.parse(url),body: jsonEncode({@@@ -1859,7 -1990,7 +2202,8 @@@'audio/x-ms-wma',],}),-- timeout: const Duration(seconds: 20));++ timeout: const Duration(seconds: 20),++ );debugPrint('[ABS] Episode session response: ${response.statusCode}');if (response.statusCode == 200) {@@@ -1876,11 -2007,11 +2220,14 @@@/// Get server progress for a podcast episode./// GET /api/me/progress/:itemId/:episodeIdFuture<Map<String, dynamic>?> getEpisodeProgress(-- String itemId, String episodeId) async {++ String itemId,++ String episodeId,++ ) async {try {final resp = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId/$episodeId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -1906,7 -2037,7 +2253,8 @@@'progress': duration > 0 ? currentTime / duration : 0,'isFinished': isFinished,}),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );} catch (e) {debugPrint('[API] updateEpisodeProgress error: $e');}@@@ -1917,7 -2048,7 +2265,8 @@@try {final resp = await _authDelete(Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId/$episodeId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return resp.statusCode >= 200 && resp.statusCode < 300;} catch (e) {debugPrint('[API] deleteEpisodeProgress error: $e');@@@ -1927,14 -2058,14 +2276,21 @@@/// Get recent podcast episodes for a library./// GET /api/libraries/:id/recent-episodes-- Future<List<dynamic>> getRecentEpisodes(String libraryId, {int limit = 25, int page = 0}) async {++ Future<List<dynamic>> getRecentEpisodes(++ String libraryId, {++ int limit = 25,++ int page = 0,++ }) async {try {final resp = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/recent-episodes?limit=$limit&page=$page'),++ Uri.parse(++ '$_cleanBaseUrl/api/libraries/$libraryId/recent-episodes?limit=$limit&page=$page',++ ),);if (resp.statusCode == 200) {final data = jsonDecode(resp.body);-- if (data is Map && data['episodes'] is List) return data['episodes'] as List<dynamic>;++ if (data is Map && data['episodes'] is List)++ return data['episodes'] as List<dynamic>;if (data is List) return data;}} catch (e) {@@@ -1947,7 -2078,7 +2303,9 @@@Future<Map<String, dynamic>?> getLibraryItem(String itemId) async {try {final response = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/items/$itemId?expanded=1&include=progress'),++ Uri.parse(++ '$_cleanBaseUrl/api/items/$itemId?expanded=1&include=progress',++ ),);if (response.statusCode == 200) {@@@ -1966,7 -2097,7 +2324,8 @@@try {final response = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/bookmarks/$itemId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;return (data['bookmarks'] as List<dynamic>? ?? const [])@@@ -1987,33 -2118,33 +2346,47 @@@}}return [];-- } catch (e) { debugPrint('getServerBookmarks error: $e'); }++ } catch (e) {++ debugPrint('getServerBookmarks error: $e');++ }return null;}/// Create a bookmark on the server./// POST /api/me/item/:id/bookmark body: { time, title }-- Future<bool> createBookmark(String itemId, {required double time, required String title}) async {++ Future<bool> createBookmark(++ String itemId, {++ required double time,++ required String title,++ }) async {try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/me/item/$itemId/bookmark'),body: jsonEncode({'time': time, 'title': title}),);return r.statusCode == 200;-- } catch (e) { debugPrint('createBookmark error: $e'); }++ } catch (e) {++ debugPrint('createBookmark error: $e');++ }return false;}/// Update a bookmark on the server./// PATCH /api/me/item/:id/bookmark body: { time, title }-- Future<bool> updateBookmark(String itemId, {required double time, required String title}) async {++ Future<bool> updateBookmark(++ String itemId, {++ required double time,++ required String title,++ }) async {try {final r = await _authPatch(Uri.parse('$_cleanBaseUrl/api/me/item/$itemId/bookmark'),body: jsonEncode({'time': time, 'title': title}),);return r.statusCode == 200;-- } catch (e) { debugPrint('updateBookmark error: $e'); }++ } catch (e) {++ debugPrint('updateBookmark error: $e');++ }return false;}@@@ -2025,7 -2156,7 +2398,9 @@@Uri.parse('$_cleanBaseUrl/api/me/item/$itemId/bookmark/$time'),);return r.statusCode == 200;-- } catch (e) { debugPrint('deleteBookmark error: $e'); }++ } catch (e) {++ debugPrint('deleteBookmark error: $e');++ }return false;}@@@ -2040,10 -2171,10 +2415,15 @@@try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/emails/send-ebook-to-device'),-- body: jsonEncode({'libraryItemId': libraryItemId, 'deviceName': deviceName}),++ body: jsonEncode({++ 'libraryItemId': libraryItemId,++ 'deviceName': deviceName,++ }),);return r.statusCode == 200;-- } catch (e) { debugPrint('[API] sendEBookToDevice error: $e'); }++ } catch (e) {++ debugPrint('[API] sendEBookToDevice error: $e');++ }return false;}@@@ -2060,7 -2191,7 +2440,9 @@@return body;}return null;-- } catch (e) { debugPrint('[API] getEmailSettings error: $e'); }++ } catch (e) {++ debugPrint('[API] getEmailSettings error: $e');++ }return null;}@@@ -2072,7 -2203,7 +2454,9 @@@body: jsonEncode(patch),);return r.statusCode == 200;-- } catch (e) { debugPrint('[API] updateEmailSettings error: $e'); }++ } catch (e) {++ debugPrint('[API] updateEmailSettings error: $e');++ }return false;}@@@ -2081,7 -2212,7 +2465,9 @@@try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/emails/test'));return r.statusCode == 200;-- } catch (e) { debugPrint('[API] sendTestEmail error: $e'); }++ } catch (e) {++ debugPrint('[API] sendTestEmail error: $e');++ }return false;}@@@ -2094,14 -2225,42 +2480,49 @@@body: jsonEncode({'ereaderDevices': devices}),);return r.statusCode == 200;-- } catch (e) { debugPrint('[API] updateEReaderDevices error: $e'); }++ } catch (e) {++ debugPrint('[API] updateEReaderDevices error: $e');++ }return false;}/// Get a single series with its books (paginated)./// If [onPageLoaded] is provided, it's called after each page with the/// cumulative results and total so the UI can show books as they arrive.- Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId, void Function(List<dynamic> books, int total, {double? totalDuration})? onPageLoaded}) async {+ /// Series metadata only, for ids stored without a name. Tries the direct+ /// series endpoint first and falls back to the per-library one for servers+ /// that don't expose it.+ Future<Map<String, dynamic>?> getSeriesInfo(+ String seriesId, {+ List<String> libraryIds = const [],+ }) async {+ try {+ final resp = await _authGet(+ Uri.parse('$_cleanBaseUrl/api/series/$seriesId'),+ );+ if (resp.statusCode == 200) {+ return jsonDecode(resp.body) as Map<String, dynamic>;+ }+ } catch (_) {}+ for (final libraryId in libraryIds) {+ try {+ final resp = await _authGet(+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),+ );+ if (resp.statusCode == 200) {+ return jsonDecode(resp.body) as Map<String, dynamic>;+ }+ } catch (_) {}+ }+ return null;+ }+- Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId, void Function(List<dynamic> books, int total, {double? totalDuration})? onPageLoaded}) async {++ Future<Map<String, dynamic>?> getSeries(++ String seriesId, {++ String? libraryId,++ void Function(List<dynamic> books, int total, {double? totalDuration})?++ onPageLoaded,++ }) async {try {Map<String, dynamic>? seriesMeta;@@@ -2109,7 -2268,7 +2530,8 @@@if (libraryId != null) {final metaResp = await _authGet(Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),-- timeout: const Duration(seconds: 30));++ timeout: const Duration(seconds: 30),++ );if (metaResp.statusCode == 200) {seriesMeta = jsonDecode(metaResp.body) as Map<String, dynamic>;}@@@ -2124,19 -2283,19 +2546,27 @@@int total = 0;int page = 0;while (true) {-- final url = '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=media.metadata.series.sequence&limit=$pageSize&page=$page&collapseseries=0';++ final url =++ '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=media.metadata.series.sequence&limit=$pageSize&page=$page&collapseseries=0';final itemsResp = await _authGet(Uri.parse(url),-- timeout: const Duration(seconds: 30));++ timeout: const Duration(seconds: 30),++ );if (itemsResp.statusCode != 200) {-- debugPrint('[API] getSeries items page $page failed: ${itemsResp.statusCode}');++ debugPrint(++ '[API] getSeries items page $page failed: ${itemsResp.statusCode}',++ );break;}final data = jsonDecode(itemsResp.body) as Map<String, dynamic>;final results = data['results'] as List<dynamic>? ?? [];total = (data['total'] as num?)?.toInt() ?? results.length;allResults.addAll(results);-- onPageLoaded?.call(allResults, total, totalDuration: (seriesMeta?['totalDuration'] as num?)?.toDouble());++ onPageLoaded?.call(++ allResults,++ total,++ totalDuration: (seriesMeta?['totalDuration'] as num?)?.toDouble(),++ );if (allResults.length >= total || results.isEmpty) break;page++;}@@@ -2146,28 -2305,28 +2576,37 @@@'name': seriesMeta?['name'] ?? '','books': allResults,'total': total,-- if (seriesMeta != null) 'totalDuration': seriesMeta['totalDuration'],++ if (seriesMeta != null)++ 'totalDuration': seriesMeta['totalDuration'],};}}-- } catch (_) {-- }++ } catch (_) {}return null;}/// Get books in a series with collapseseries=1 to detect sub-series./// Returns items where books sharing another series are collapsed into/// a single entry with a 'collapsedSeries' object.-- Future<List<dynamic>> getSeriesCollapsed(String seriesId, {required String libraryId}) async {++ Future<List<dynamic>> getSeriesCollapsed(++ String seriesId, {++ required String libraryId,++ }) async {try {final filterValue = base64Encode(utf8.encode(seriesId));final allResults = <dynamic>[];int page = 0;while (true) {-- final url = '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=addedAt&limit=100&page=$page&collapseseries=1';-- final resp = await _authGet(Uri.parse(url), timeout: const Duration(seconds: 60));++ final url =++ '$_cleanBaseUrl/api/libraries/$libraryId/items?filter=series.$filterValue&sort=addedAt&limit=100&page=$page&collapseseries=1';++ final resp = await _authGet(++ Uri.parse(url),++ timeout: const Duration(seconds: 60),++ );if (resp.statusCode != 200) {-- debugPrint('[API] getSeriesCollapsed page $page failed: ${resp.statusCode}');++ debugPrint(++ '[API] getSeriesCollapsed page $page failed: ${resp.statusCode}',++ );break;}final data = jsonDecode(resp.body) as Map<String, dynamic>;@@@ -2178,7 -2337,7 +2617,9 @@@page++;}return allResults;-- } catch (e) { debugPrint('[API] getSeriesCollapsed error: $e'); }++ } catch (e) {++ debugPrint('[API] getSeriesCollapsed error: $e');++ }return [];}@@@ -2223,14 -2382,14 +2664,15 @@@if (author != null && author.isNotEmpty) {params['author'] = author;}-- final uri = Uri.parse('$_cleanBaseUrl/api/search/books')-- .replace(queryParameters: params);++ final uri = Uri.parse(++ '$_cleanBaseUrl/api/search/books',++ ).replace(queryParameters: params);debugPrint('[API] searchBooks: $uri');-- final response = await _authGet(-- uri,-- );++ final response = await _authGet(uri);-- debugPrint('[API] searchBooks status=${response.statusCode} bodyLen=${response.body.length}');++ debugPrint(++ '[API] searchBooks status=${response.statusCode} bodyLen=${response.body.length}',++ );if (response.statusCode == 200) {final data = jsonDecode(response.body);@@@ -2243,7 -2402,7 +2685,9 @@@// Some providers may return a Map with results nested under a keyif (data is Map<String, dynamic>) {-- debugPrint('[API] searchBooks: got Map with keys: ${data.keys.join(', ')}');++ debugPrint(++ '[API] searchBooks: got Map with keys: ${data.keys.join(', ')}',++ );// Try common nesting patternsfor (final key in ['results', 'items', 'books', 'matches']) {final nested = data[key];@@@ -2257,7 -2416,7 +2701,9 @@@}}-- debugPrint('[API] searchBooks: unexpected response type: ${data.runtimeType}');++ debugPrint(++ '[API] searchBooks: unexpected response type: ${data.runtimeType}',++ );}} catch (e) {debugPrint('[API] searchBooks error: $e');@@@ -2269,18 -2428,18 +2715,19 @@@/// Returns { rating, asin } or null.static Future<Map<String, dynamic>?> getAudibleRating(String asin) async {try {-- final response = await http.get(-- Uri.parse('https://api.audnex.us/books/$asin?region=$_region&update=1'),-- ).timeout(const Duration(seconds: 10));++ final response = await http++ .get(++ Uri.parse(++ 'https://api.audnex.us/books/$asin?region=$_region&update=1',++ ),++ )++ .timeout(const Duration(seconds: 10));if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;final rating = data['rating'] as String?;if (rating != null) {-- return {-- 'rating': double.tryParse(rating) ?? 0.0,-- 'asin': asin,-- };++ return {'rating': double.tryParse(rating) ?? 0.0, 'asin': asin};}}} catch (e) {@@@ -2293,7 -2452,7 +2740,9 @@@/// library item id. Used so the rating shows immediately on book detail/// open even when Audnexus is slow or unreachable, and so a transient/// network failure doesn't make a known rating disappear.-- static Future<Map<String, dynamic>?> getCachedAudibleRating(String itemId) async {++ static Future<Map<String, dynamic>?> getCachedAudibleRating(++ String itemId,++ ) async {try {final prefs = await SharedPreferences.getInstance();final raw = prefs.getString('audible_rating_$itemId');@@@ -2301,10 -2460,10 +2750,7 @@@final data = jsonDecode(raw) as Map<String, dynamic>;final rating = (data['rating'] as num?)?.toDouble();if (rating == null || rating <= 0) return null;-- return {-- 'rating': rating,-- 'asin': data['asin'] as String?,-- };++ return {'rating': rating, 'asin': data['asin'] as String?};} catch (_) {return null;}@@@ -2313,15 -2472,15 +2759,21 @@@/// Persist a fresh Audible rating so subsequent book detail opens render/// the stars instantly without waiting on Audnexus.static Future<void> setCachedAudibleRating(-- String itemId, double rating, String? asin) async {++ String itemId,++ double rating,++ String? asin,++ ) async {if (rating <= 0) return;try {final prefs = await SharedPreferences.getInstance();-- await prefs.setString('audible_rating_$itemId', jsonEncode({-- 'rating': rating,-- 'asin': asin,-- 'fetchedAt': DateTime.now().millisecondsSinceEpoch,-- }));++ await prefs.setString(++ 'audible_rating_$itemId',++ jsonEncode({++ 'rating': rating,++ 'asin': asin,++ 'fetchedAt': DateTime.now().millisecondsSinceEpoch,++ }),++ );} catch (_) {}}@@@ -2329,7 -2488,7 +2781,9 @@@/// then fetch the rating from Audnexus. Used as a fallback when the book's/// stored ASIN returns no rating.Future<Map<String, dynamic>?> searchAudibleRating(-- String title, String? author) async {++ String title,++ String? author,++ ) async {try {// Use the ABS server's search endpoint to query Audible for the book.final response = await _authGet(@@@ -2378,9 -2537,9 +2832,18 @@@/// Map region code to Audible API TLD.static String _audibleTldFor(String region) {const tlds = {-- 'us': '.com', 'uk': '.co.uk', 'gb': '.co.uk', 'au': '.com.au',-- 'ca': '.ca', 'de': '.de', 'fr': '.fr', 'it': '.it', 'es': '.es',-- 'jp': '.co.jp', 'in': '.in', 'br': '.com.br',++ 'us': '.com',++ 'uk': '.co.uk',++ 'gb': '.co.uk',++ 'au': '.com.au',++ 'ca': '.ca',++ 'de': '.de',++ 'fr': '.fr',++ 'it': '.it',++ 'es': '.es',++ 'jp': '.co.jp',++ 'in': '.in',++ 'br': '.com.br',};return tlds[region] ?? '.com';}@@@ -2390,12 -2549,12 +2853,15 @@@/// Fetch full book metadata from Audnexus by ASIN./// Returns the raw Audnexus response including seriesPrimary, releaseDate, etc./// If [region] is provided, it overrides the device locale region.-- static Future<Map<String, dynamic>?> getAudnexusBook(String asin, {String? region}) async {++ static Future<Map<String, dynamic>?> getAudnexusBook(++ String asin, {++ String? region,++ }) async {try {final r = region ?? _region;-- final response = await http.get(-- Uri.parse('https://api.audnex.us/books/$asin?region=$r'),-- ).timeout(const Duration(seconds: 10));++ final response = await http++ .get(Uri.parse('https://api.audnex.us/books/$asin?region=$r'))++ .timeout(const Duration(seconds: 10));if (response.statusCode == 200) {return jsonDecode(response.body) as Map<String, dynamic>;}@@@ -2407,13 -2566,13 +2873,18 @@@/// Get all book ASINs in an Audible series using the catalog relationships endpoint./// Returns a list of { asin, sequence, sort } maps.-- static Future<List<Map<String, dynamic>>> getAudibleSeriesBooks(String seriesAsin, {String? region}) async {++ static Future<List<Map<String, dynamic>>> getAudibleSeriesBooks(++ String seriesAsin, {++ String? region,++ }) async {try {final tld = region != null ? _audibleTldFor(region) : _audibleTld;-- final url = 'https://api.audible$tld/1.0/catalog/products/$seriesAsin'++ final url =++ 'https://api.audible$tld/1.0/catalog/products/$seriesAsin''?response_groups=relationships';debugPrint('[API] getAudibleSeriesBooks: $url');-- final response = await http.get(Uri.parse(url))++ final response = await http++ .get(Uri.parse(url)).timeout(const Duration(seconds: 15));if (response.statusCode == 200) {@@@ -2443,12 -2602,12 +2914,17 @@@/// Fetch details for a single book from the Audible catalog API./// Returns title, authors, narrators, release_date, runtime, rating, cover, etc.-- static Future<Map<String, dynamic>?> getAudibleBookDetails(String asin, {String? region}) async {++ static Future<Map<String, dynamic>?> getAudibleBookDetails(++ String asin, {++ String? region,++ }) async {try {final tld = region != null ? _audibleTldFor(region) : _audibleTld;-- final url = 'https://api.audible$tld/1.0/catalog/products/$asin'++ final url =++ 'https://api.audible$tld/1.0/catalog/products/$asin''?response_groups=product_attrs,product_desc,product_details,series,rating,media';-- final response = await http.get(Uri.parse(url))++ final response = await http++ .get(Uri.parse(url)).timeout(const Duration(seconds: 10));if (response.statusCode == 200) {@@@ -2474,7 -2633,7 +2950,10 @@@String? region,bool newestOnly = false,}) async {-- final relationships = await getAudibleSeriesBooks(seriesAsin, region: region);++ final relationships = await getAudibleSeriesBooks(++ seriesAsin,++ region: region,++ );if (relationships.isEmpty) return [];final bySequence = <String, List<Map<String, dynamic>>>{};@@@ -2502,7 -2661,7 +2981,9 @@@final seqB = double.tryParse(b['sequence']?.toString() ?? '') ?? 999999;return seqB.compareTo(seqA); // descending});-- debugPrint('[API] discoverAudibleSeries: capping ${uniqueBooks.length} books to newest 50');++ debugPrint(++ '[API] discoverAudibleSeries: capping ${uniqueBooks.length} books to newest 50',++ );uniqueBooks = uniqueBooks.take(50).toList();}@@@ -2515,9 -2674,9 +2996,11 @@@if (details == null) return null;final authors = (details['authors'] as List<dynamic>? ?? [])-- .map((a) => (a as Map<String, dynamic>)['name'] ?? '').join(', ');++ .map((a) => (a as Map<String, dynamic>)['name'] ?? '')++ .join(', ');final narrators = (details['narrators'] as List<dynamic>? ?? [])-- .map((n) => (n as Map<String, dynamic>)['name'] ?? '').join(', ');++ .map((n) => (n as Map<String, dynamic>)['name'] ?? '')++ .join(', ');final rating = details['rating'] as Map<String, dynamic>?;return <String, dynamic>{@@@ -2528,9 -2687,9 +3011,13 @@@'narrators': narrators,'releaseDate': details['release_date'] ?? '','runtimeMinutes': details['runtime_length_min'] ?? 0,-- 'rating': rating?['overall_distribution']?['display_average_rating'] ?? 0.0,++ 'rating':++ rating?['overall_distribution']?['display_average_rating'] ?? 0.0,'numRatings': rating?['overall_distribution']?['num_ratings'] ?? 0,-- 'coverUrl': details['product_images']?['500'] ?? details['product_images']?['1024'] ?? '',++ 'coverUrl':++ details['product_images']?['500'] ??++ details['product_images']?['1024'] ??++ '','sequence': book['sequence'] ?? '','sort': book['sort'] ?? '0','publisherSummary': details['publisher_summary'] ?? '',@@@ -2555,8 -2714,8 +3042,10 @@@/// Get all users (admin only)Future<List<dynamic>> getUsers() async {try {-- final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/users'), headers: _headers)-- ;++ final r = await _authGet(++ Uri.parse('$_cleanBaseUrl/api/users'),++ headers: _headers,++ );if (r.statusCode == 200) {final data = jsonDecode(r.body);if (data is List) return data;@@@ -2569,22 -2728,22 +3058,30 @@@}}}-- } catch (e) { debugPrint('getUsers error: $e'); }++ } catch (e) {++ debugPrint('getUsers error: $e');++ }return [];}/// Get online users (admin only)Future<List<dynamic>> getOnlineUsers() async {try {-- final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/users/online'), headers: _headers)-- ;++ final r = await _authGet(++ Uri.parse('$_cleanBaseUrl/api/users/online'),++ headers: _headers,++ );if (r.statusCode == 200) {final data = jsonDecode(r.body);-- if (data is Map && data['usersOnline'] is List) return data['usersOnline'] as List<dynamic>;-- if (data is Map && data['openSessions'] is List) return data['openSessions'] as List<dynamic>;++ if (data is Map && data['usersOnline'] is List)++ return data['usersOnline'] as List<dynamic>;++ if (data is Map && data['openSessions'] is List)++ return data['openSessions'] as List<dynamic>;if (data is List) return data;}-- } catch (e) { debugPrint('getOnlineUsers error: $e'); }++ } catch (e) {++ debugPrint('getOnlineUsers error: $e');++ }return [];}@@@ -2598,7 -2757,7 +3095,9 @@@final data = jsonDecode(r.body);return (data['sessions'] as List<dynamic>?) ?? [];}-- } catch (e) { debugPrint('getAllSessions error: $e'); }++ } catch (e) {++ debugPrint('getAllSessions error: $e');++ }return [];}@@@ -2620,8 -2779,8 +3119,9 @@@'desc': desc ? '1' : '0',if (userId != null && userId.isNotEmpty) 'user': userId,};-- final uri = Uri.parse('$_cleanBaseUrl/api/sessions')-- .replace(queryParameters: params);++ final uri = Uri.parse(++ '$_cleanBaseUrl/api/sessions',++ ).replace(queryParameters: params);final r = await _authGet(uri, timeout: const Duration(seconds: 15));if (r.statusCode == 200) {return jsonDecode(r.body) as Map<String, dynamic>;@@@ -2635,13 -2794,13 +3135,17 @@@/// Get all backups (admin only)Future<List<dynamic>> getBackups() async {try {-- final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/backups'), headers: _headers)-- ;++ final r = await _authGet(++ Uri.parse('$_cleanBaseUrl/api/backups'),++ headers: _headers,++ );if (r.statusCode == 200) {final data = jsonDecode(r.body);return (data['backups'] as List<dynamic>?) ?? [];}-- } catch (e) { debugPrint('getBackups error: $e'); }++ } catch (e) {++ debugPrint('getBackups error: $e');++ }return [];}@@@ -2676,10 -2835,10 +3180,7 @@@try {final response = await _authPost(Uri.parse('$_cleanBaseUrl/api/filesystem/pathexists'),-- body: jsonEncode({-- 'directory': directory,-- 'folderPath': folderPath,-- }),++ body: jsonEncode({'directory': directory, 'folderPath': folderPath}),timeout: const Duration(seconds: 20),);if (response.statusCode == 200) {@@@ -2738,30 -2897,30 +3239,31 @@@onProgress?.call(sentBytes, totalBytes);return chunk;});-- request.files.add(http.MultipartFile(-- '$i',-- tracked,-- file.size > 0 ? file.size : file.bytes!.length,-- filename: file.name,-- ));++ request.files.add(++ http.MultipartFile(++ '$i',++ tracked,++ file.size > 0 ? file.size : file.bytes!.length,++ filename: file.name,++ ),++ );} else if (file.path != null && file.path!.isNotEmpty) {-- request.files.add(await http.MultipartFile.fromPath(-- '$i',-- file.path!,-- filename: file.name,-- ));++ request.files.add(++ await http.MultipartFile.fromPath(++ '$i',++ file.path!,++ filename: file.name,++ ),++ );} else if (file.readStream != null) {final tracked = file.readStream!.map((chunk) {sentBytes += chunk.length;onProgress?.call(sentBytes, totalBytes);return chunk;});-- request.files.add(http.MultipartFile(-- '$i',-- tracked,-- file.size,-- filename: file.name,-- ));++ request.files.add(++ http.MultipartFile('$i', tracked, file.size, filename: file.name),++ );} else {return MediaUploadResult(success: false,@@@ -2791,20 -2950,20 +3293,55 @@@/// Create a backup (admin only)Future<bool> createBackup() async {try {-- final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/backups'), timeout: const Duration(seconds: 60));++ final r = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/backups'),++ timeout: const Duration(seconds: 60),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('createBackup error: $e'); }++ } catch (e) {++ debugPrint('createBackup error: $e');++ }return false;}++ /// Get the server's current daily log entries (admin only).++ ///++ /// GET /api/logger-data returns `{ currentDailyLogs: [...] }`. A nullable++ /// result distinguishes a request failure from a valid empty log file.++ Future<List<Map<String, dynamic>>?> getServerLogs() async {++ try {++ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/logger-data'));++ if (r.statusCode != 200) {++ debugPrint('[API] getServerLogs failed: ${r.statusCode}');++ return null;++ }++ final decoded = jsonDecode(r.body);++ if (decoded is! Map) return const <Map<String, dynamic>>[];++ final rawLogs = decoded['currentDailyLogs'];++ if (rawLogs is! List) return const <Map<String, dynamic>>[];++ return rawLogs++ .whereType<Map>()++ .map(++ (log) => log.map((key, value) => MapEntry(key.toString(), value)),++ )++ .toList(growable: false);++ } catch (e) {++ debugPrint('[API] getServerLogs error: $e');++ return null;++ }++ }++/// Scan a library's folders (admin only)Future<bool> scanLibrary(String libraryId) async {try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/scan'),-- timeout: const Duration(seconds: 30));++ timeout: const Duration(seconds: 30),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('scanLibrary error: $e'); }++ } catch (e) {++ debugPrint('scanLibrary error: $e');++ }return false;}@@@ -2813,9 -2972,9 +3350,12 @@@try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/match'),-- timeout: const Duration(seconds: 30));++ timeout: const Duration(seconds: 30),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('matchLibrary error: $e'); }++ } catch (e) {++ debugPrint('matchLibrary error: $e');++ }return false;}@@@ -2825,17 -2984,17 +3365,25 @@@final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/stats'),);-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('getLibraryStats error: $e'); }++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('getLibraryStats error: $e');++ }return null;}/// Purge server cache (admin only)Future<bool> purgeCache() async {try {-- final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/cache/purge'), timeout: const Duration(seconds: 30));++ final r = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/cache/purge'),++ timeout: const Duration(seconds: 30),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('purgeCache error: $e'); }++ } catch (e) {++ debugPrint('purgeCache error: $e');++ }return false;}@@@ -2844,11 -3003,11 +3392,15 @@@/// Returns { posix: bool, directories: [{path, dirname, level}] }.Future<Map<String, dynamic>?> getFilesystemPaths({String? path}) async {try {-- final uri = Uri.parse('$_cleanBaseUrl/api/filesystem')-- .replace(queryParameters: path != null ? {'path': path} : null);++ final uri = Uri.parse(++ '$_cleanBaseUrl/api/filesystem',++ ).replace(queryParameters: path != null ? {'path': path} : null);final r = await _authGet(uri, timeout: const Duration(seconds: 20));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('[API] getFilesystemPaths error: $e'); }++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('[API] getFilesystemPaths error: $e');++ }return null;}@@@ -2857,11 -3016,11 +3409,17 @@@/// provider, settings. Returns the new library object on success.Future<Map<String, dynamic>?> createLibrary(Map<String, dynamic> body) async {try {-- final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/libraries'),-- body: jsonEncode(body), timeout: const Duration(seconds: 30));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;++ final r = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/libraries'),++ body: jsonEncode(body),++ timeout: const Duration(seconds: 30),++ );++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;debugPrint('[API] createLibrary failed: ${r.statusCode}');-- } catch (e) { debugPrint('[API] createLibrary error: $e'); }++ } catch (e) {++ debugPrint('[API] createLibrary error: $e');++ }return null;}@@@ -2870,30 -3029,30 +3428,43 @@@/// new ones as {fullPath}; omitting a folder DELETES it (cascades on server).Future<bool> updateLibrary(String id, Map<String, dynamic> body) async {try {-- final r = await _authPatch(Uri.parse('$_cleanBaseUrl/api/libraries/$id'),-- body: jsonEncode(body), timeout: const Duration(seconds: 30));++ final r = await _authPatch(++ Uri.parse('$_cleanBaseUrl/api/libraries/$id'),++ body: jsonEncode(body),++ timeout: const Duration(seconds: 30),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('[API] updateLibrary error: $e'); }++ } catch (e) {++ debugPrint('[API] updateLibrary error: $e');++ }return false;}/// DELETE /api/libraries/:id — removes the library and all its items (admin only).Future<bool> deleteLibrary(String id) async {try {-- final r = await _authDelete(Uri.parse('$_cleanBaseUrl/api/libraries/$id'),-- timeout: const Duration(seconds: 30));++ final r = await _authDelete(++ Uri.parse('$_cleanBaseUrl/api/libraries/$id'),++ timeout: const Duration(seconds: 30),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('[API] deleteLibrary error: $e'); }++ } catch (e) {++ debugPrint('[API] deleteLibrary error: $e');++ }return false;}/// POST /api/libraries/order — body is a raw array [{id, newOrder}] (admin only).Future<bool> reorderLibraries(List<Map<String, dynamic>> order) async {try {-- final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/libraries/order'),-- body: jsonEncode(order));++ final r = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/libraries/order'),++ body: jsonEncode(order),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('[API] reorderLibraries error: $e'); }++ } catch (e) {++ debugPrint('[API] reorderLibraries error: $e');++ }return false;}@@@ -2902,7 -3061,7 +3473,9 @@@/// Returns book + podcast provider values (deduped); falls back to built-ins.Future<List<String>> getMetadataProviders() async {try {-- final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/search/providers'));++ final r = await _authGet(++ Uri.parse('$_cleanBaseUrl/api/search/providers'),++ );if (r.statusCode == 200) {final data = jsonDecode(r.body);final out = <String>[];@@@ -2914,36 -3073,36 +3487,57 @@@}if (out.isNotEmpty) return out;}-- } catch (e) { debugPrint('[API] getMetadataProviders error: $e'); }-- return const ['google', 'audible', 'openlibrary', 'itunes', 'audnexus', 'fantlab'];++ } catch (e) {++ debugPrint('[API] getMetadataProviders error: $e');++ }++ return const [++ 'google',++ 'audible',++ 'openlibrary',++ 'itunes',++ 'audnexus',++ 'fantlab',++ ];}/// PATCH /api/settings — update server settings (admin only)./// There is no GET; read current values from AuthProvider.serverSettings./// Returns the fresh serverSettings map so the caller can re-cache it.-- Future<Map<String, dynamic>?> updateServerSettings(Map<String, dynamic> patch) async {++ Future<Map<String, dynamic>?> updateServerSettings(++ Map<String, dynamic> patch,++ ) async {try {-- final r = await _authPatch(Uri.parse('$_cleanBaseUrl/api/settings'),-- body: jsonEncode(patch));++ final r = await _authPatch(++ Uri.parse('$_cleanBaseUrl/api/settings'),++ body: jsonEncode(patch),++ );if (r.statusCode == 200) {return jsonDecode(r.body)['serverSettings'] as Map<String, dynamic>?;}debugPrint('[API] updateServerSettings failed: ${r.statusCode}');-- } catch (e) { debugPrint('[API] updateServerSettings error: $e'); }++ } catch (e) {++ debugPrint('[API] updateServerSettings error: $e');++ }return null;}/// PATCH /api/sorting-prefixes — body { sortingPrefixes: [..] } (admin only)./// Returns the fresh serverSettings map (the response also has rowsUpdated).-- Future<Map<String, dynamic>?> updateSortingPrefixes(List<String> prefixes) async {++ Future<Map<String, dynamic>?> updateSortingPrefixes(++ List<String> prefixes,++ ) async {try {-- final r = await _authPatch(Uri.parse('$_cleanBaseUrl/api/sorting-prefixes'),-- body: jsonEncode({'sortingPrefixes': prefixes}),-- timeout: const Duration(seconds: 30));++ final r = await _authPatch(++ Uri.parse('$_cleanBaseUrl/api/sorting-prefixes'),++ body: jsonEncode({'sortingPrefixes': prefixes}),++ timeout: const Duration(seconds: 30),++ );if (r.statusCode == 200) {return jsonDecode(r.body)['serverSettings'] as Map<String, dynamic>?;}-- } catch (e) { debugPrint('[API] updateSortingPrefixes error: $e'); }++ } catch (e) {++ debugPrint('[API] updateSortingPrefixes error: $e');++ }return null;}@@@ -2951,28 -3110,28 +3545,41 @@@Future<Map<String, dynamic>?> getServerStats() async {try {final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/stats/server'));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('[API] getServerStats error: $e'); }++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('[API] getServerStats error: $e');++ }return null;}/// GET /api/stats/year/:year — admin year-in-review stats (admin only).Future<Map<String, dynamic>?> getServerYearStats(int year) async {try {-- final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/stats/year/$year'),-- timeout: const Duration(seconds: 30));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('[API] getServerYearStats error: $e'); }++ final r = await _authGet(++ Uri.parse('$_cleanBaseUrl/api/stats/year/$year'),++ timeout: const Duration(seconds: 30),++ );++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('[API] getServerYearStats error: $e');++ }return null;}/// GET /api/me/stats/year/:year — the signed-in user's year-in-review stats.Future<Map<String, dynamic>?> getMyYearStats(int year) async {try {-- final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/stats/year/$year'),-- timeout: const Duration(seconds: 30));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('[API] getMyYearStats error: $e'); }++ final r = await _authGet(++ Uri.parse('$_cleanBaseUrl/api/me/stats/year/$year'),++ timeout: const Duration(seconds: 30),++ );++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('[API] getMyYearStats error: $e');++ }return null;}@@@ -2993,24 -3152,24 +3600,29 @@@'isActive': isActive,};if (permissions != null) body['permissions'] = permissions;-- if (librariesAccessible != null) body['librariesAccessible'] = librariesAccessible;++ if (librariesAccessible != null)++ body['librariesAccessible'] = librariesAccessible;final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/users'),body: jsonEncode(body),);-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('createUser error: $e'); }++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('createUser error: $e');++ }return null;}/// Get a single user with full details including mediaProgress (admin only)Future<Map<String, dynamic>?> getUser(String userId) async {try {-- final r = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/users/$userId'),-- );-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('getUser error: $e'); }++ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/users/$userId'));++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('getUser error: $e');++ }return null;}@@@ -3022,7 -3181,7 +3634,9 @@@body: jsonEncode(updates),);return r.statusCode == 200;-- } catch (e) { debugPrint('updateUser error: $e'); }++ } catch (e) {++ debugPrint('updateUser error: $e');++ }return false;}@@@ -3033,7 -3192,7 +3647,9 @@@Uri.parse('$_cleanBaseUrl/api/users/$userId'),);return r.statusCode == 200;-- } catch (e) { debugPrint('deleteUser error: $e'); }++ } catch (e) {++ debugPrint('deleteUser error: $e');++ }return false;}@@@ -3046,7 -3205,7 +3662,9 @@@Uri.parse('$_cleanBaseUrl/api/users/$userId/openid-unlink'),);return r.statusCode == 200;-- } catch (e) { debugPrint('unlinkOpenID error: $e'); }++ } catch (e) {++ debugPrint('unlinkOpenID error: $e');++ }return false;}@@@ -3058,10 -3217,10 +3676,13 @@@final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/api-keys'));if (r.statusCode == 200) {final data = jsonDecode(r.body);-- if (data is Map && data['apiKeys'] is List) return data['apiKeys'] as List<dynamic>;++ if (data is Map && data['apiKeys'] is List)++ return data['apiKeys'] as List<dynamic>;if (data is List) return data;}-- } catch (e) { debugPrint('getApiKeys error: $e'); }++ } catch (e) {++ debugPrint('getApiKeys error: $e');++ }return [];}@@@ -3075,7 -3234,7 +3696,11 @@@bool isActive = true,}) async {try {-- final body = <String, dynamic>{'name': name, 'userId': userId, 'isActive': isActive};++ final body = <String, dynamic>{++ 'name': name,++ 'userId': userId,++ 'isActive': isActive,++ };if (expiresIn != null) body['expiresIn'] = expiresIn;final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/api-keys'),@@@ -3083,15 -3242,15 +3708,22 @@@);if (r.statusCode == 200) {final data = jsonDecode(r.body);-- if (data is Map && data['apiKey'] is Map) return Map<String, dynamic>.from(data['apiKey'] as Map);++ if (data is Map && data['apiKey'] is Map)++ return Map<String, dynamic>.from(data['apiKey'] as Map);}-- } catch (e) { debugPrint('createApiKey error: $e'); }++ } catch (e) {++ debugPrint('createApiKey error: $e');++ }return null;}/// Update an API key (admin only). Only `isActive` and `userId` are mutable/// server-side (name and expiry are baked into the JWT).-- Future<bool> updateApiKey(String keyId, {bool? isActive, String? userId}) async {++ Future<bool> updateApiKey(++ String keyId, {++ bool? isActive,++ String? userId,++ }) async {try {final body = <String, dynamic>{};if (isActive != null) body['isActive'] = isActive;@@@ -3101,16 -3260,16 +3733,22 @@@body: jsonEncode(body),);return r.statusCode == 200;-- } catch (e) { debugPrint('updateApiKey error: $e'); }++ } catch (e) {++ debugPrint('updateApiKey error: $e');++ }return false;}/// Delete (revoke) an API key (admin only).Future<bool> deleteApiKey(String keyId) async {try {-- final r = await _authDelete(Uri.parse('$_cleanBaseUrl/api/api-keys/$keyId'));++ final r = await _authDelete(++ Uri.parse('$_cleanBaseUrl/api/api-keys/$keyId'),++ );return r.statusCode == 200;-- } catch (e) { debugPrint('deleteApiKey error: $e'); }++ } catch (e) {++ debugPrint('deleteApiKey error: $e');++ }return false;}@@@ -3132,7 -3291,7 +3770,9 @@@);debugPrint('[API] updateItemMedia $itemId -> ${r.statusCode}: ${r.body}');return r.statusCode == 200;-- } catch (e) { debugPrint('updateItemMedia error: $e'); }++ } catch (e) {++ debugPrint('updateItemMedia error: $e');++ }return false;}@@@ -3142,10 -3301,10 +3782,15 @@@final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/items/$itemId/cover'),body: jsonEncode({'url': url}),-- timeout: const Duration(seconds: 30));-- debugPrint('[API] updateItemCoverUrl $itemId -> ${r.statusCode}: ${r.body}');++ timeout: const Duration(seconds: 30),++ );++ debugPrint(++ '[API] updateItemCoverUrl $itemId -> ${r.statusCode}: ${r.body}',++ );return r.statusCode == 200;-- } catch (e) { debugPrint('updateItemCoverUrl error: $e'); }++ } catch (e) {++ debugPrint('updateItemCoverUrl error: $e');++ }return false;}@@@ -3160,20 -3319,20 +3805,28 @@@req.files.add(await http.MultipartFile.fromPath('cover', filePath));final res = await req.send().timeout(const Duration(seconds: 60));return res.statusCode == 200;-- } catch (e) { debugPrint('uploadItemCover error: $e'); }++ } catch (e) {++ debugPrint('uploadItemCover error: $e');++ }return false;}/// Search provider cover images for a book./// GET /api/search/covers?title=&author=&provider= -> { results: [url, ...] }-- Future<List<String>> searchCovers(String title,-- {String? author, String provider = 'google'}) async {++ Future<List<String>> searchCovers(++ String title, {++ String? author,++ String provider = 'google',++ }) async {try {-- final uri = Uri.parse('$_cleanBaseUrl/api/search/covers').replace(queryParameters: {-- 'title': title,-- if (author != null && author.trim().isNotEmpty) 'author': author.trim(),-- 'provider': provider,-- });++ final uri = Uri.parse('$_cleanBaseUrl/api/search/covers').replace(++ queryParameters: {++ 'title': title,++ if (author != null && author.trim().isNotEmpty)++ 'author': author.trim(),++ 'provider': provider,++ },++ );final r = await _authGet(uri, timeout: const Duration(seconds: 25));if (r.statusCode == 200) {final data = jsonDecode(r.body);@@@ -3203,19 -3362,19 +3856,24 @@@Future<List<dynamic>> searchPodcasts(String query) async {try {final r = await _authGet(-- Uri.parse('$_cleanBaseUrl/api/search/podcast?term=${Uri.encodeComponent(query)}'),++ Uri.parse(++ '$_cleanBaseUrl/api/search/podcast?term=${Uri.encodeComponent(query)}',++ ),);if (r.statusCode == 200) {final data = jsonDecode(r.body);if (data is List) return data;if (data is Map) {-- if (data['podcasts'] is List) return data['podcasts'] as List<dynamic>;++ if (data['podcasts'] is List)++ return data['podcasts'] as List<dynamic>;for (final key in data.keys) {if (data[key] is List) return data[key] as List<dynamic>;}}}-- } catch (e) { debugPrint('searchPodcasts error: $e'); }++ } catch (e) {++ debugPrint('searchPodcasts error: $e');++ }return [];}@@@ -3238,10 -3397,10 +3896,16 @@@String podcastPath = '';try {final libs = await getLibraries();-- final lib = libs.firstWhere((l) => l['id'] == libraryId, orElse: () => <String, dynamic>{});++ final lib = libs.firstWhere(++ (l) => l['id'] == libraryId,++ orElse: () => <String, dynamic>{},++ );final folders = lib['folders'] as List?;if (folders != null && folders.isNotEmpty) {-- final folder = folders.firstWhere((f) => f['id'] == folderId, orElse: () => folders.first);++ final folder = folders.firstWhere(++ (f) => f['id'] == folderId,++ orElse: () => folders.first,++ );final folderPath = folder['fullPath'] as String? ?? '';if (folderPath.isNotEmpty) {final cleanTitle = title.replaceAll(RegExp(r'[\\/:*?"<>|]'), '');@@@ -3258,7 -3417,7 +3922,10 @@@'metadata': {'title': title,'author': podcastData['artistName'] ?? '',-- 'description': podcastData['description'] ?? podcastData['descriptionPlain'] ?? '',++ 'description':++ podcastData['description'] ??++ podcastData['descriptionPlain'] ??++ '','releaseDate': podcastData['releaseDate'] ?? '','genres': podcastData['genres'] ?? [],'feedUrl': feedUrl,@@@ -3277,9 -3436,9 +3944,13 @@@final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/podcasts'),body: bodyJson,-- timeout: const Duration(seconds: 30));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('createPodcast error: $e'); }++ timeout: const Duration(seconds: 30),++ );++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('createPodcast error: $e');++ }return null;}@@@ -3290,12 -3449,12 +3961,15 @@@final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/podcasts/feed'),body: jsonEncode({'rssFeed': rssFeedUrl}),-- timeout: const Duration(seconds: 20));++ timeout: const Duration(seconds: 20),++ );if (r.statusCode == 200) {final data = jsonDecode(r.body);if (data is Map<String, dynamic>) return data;}-- } catch (e) { debugPrint('getPodcastFeed error: $e'); }++ } catch (e) {++ debugPrint('getPodcastFeed error: $e');++ }return null;}@@@ -3304,22 -3463,22 +3978,33 @@@try {final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/episode-downloads'),-- timeout: const Duration(seconds: 10));-- if (r.statusCode == 200) return jsonDecode(r.body) as Map<String, dynamic>;-- } catch (e) { debugPrint('getEpisodeDownloads error: $e'); }++ timeout: const Duration(seconds: 10),++ );++ if (r.statusCode == 200)++ return jsonDecode(r.body) as Map<String, dynamic>;++ } catch (e) {++ debugPrint('getEpisodeDownloads error: $e');++ }return null;}/// Download specific podcast episodes-- Future<bool> downloadPodcastEpisodes(String libraryItemId, List<Map<String, dynamic>> episodes) async {++ Future<bool> downloadPodcastEpisodes(++ String libraryItemId,++ List<Map<String, dynamic>> episodes,++ ) async {try {final r = await _authPost(-- Uri.parse('$_cleanBaseUrl/api/podcasts/$libraryItemId/download-episodes'),++ Uri.parse(++ '$_cleanBaseUrl/api/podcasts/$libraryItemId/download-episodes',++ ),body: jsonEncode(episodes),timeout: const Duration(seconds: 30),);return r.statusCode == 200;-- } catch (e) { debugPrint('downloadPodcastEpisodes error: $e'); }++ } catch (e) {++ debugPrint('downloadPodcastEpisodes error: $e');++ }return false;}@@@ -3341,19 -3500,19 +4026,25 @@@try {final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/podcasts/$id/checknew'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (r.statusCode == 200) success++;} catch (_) {}}return success > 0;-- } catch (e) { debugPrint('checkNewEpisodes error: $e'); }++ } catch (e) {++ debugPrint('checkNewEpisodes error: $e');++ }return false;}/// Check a single podcast for new episodes from its RSS feed/// GET /api/podcasts/:id/checknew?limit=N/// Returns the list of new episodes found, or null on failure.-- Future<List<dynamic>?> checkNewPodcastEpisodes(String podcastId, {int? limit}) async {++ Future<List<dynamic>?> checkNewPodcastEpisodes(++ String podcastId, {++ int? limit,++ }) async {try {final limitParam = limit != null ? '?limit=$limit' : '';final r = await _authGet(@@@ -3363,7 -3522,7 +4054,9 @@@final data = jsonDecode(r.body);return (data['episodes'] as List<dynamic>?) ?? [];}-- } catch (e) { debugPrint('checkNewPodcastEpisodes error: $e'); }++ } catch (e) {++ debugPrint('checkNewPodcastEpisodes error: $e');++ }return null;}@@@ -3394,15 -3553,15 +4087,122 @@@if (r.statusCode == 200) {return jsonDecode(r.body) as Map<String, dynamic>;}-- } catch (e) { debugPrint('matchLibraryItem error: $e'); }++ } catch (e) {++ debugPrint('matchLibraryItem error: $e');++ }return null;}++ /// Delete several library items in one server operation.++ /// Returns the HTTP status code so callers can distinguish a missing++ /// `delete` permission (403) from other failures. Zero means no request was++ /// made or the request threw.++ Future<int> deleteLibraryItems(++ List<String> itemIds, {++ bool hard = false,++ }) async {++ if (itemIds.isEmpty) return 0;++ try {++ final response = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/items/batch/delete?hard=${hard ? 1 : 0}'),++ body: jsonEncode({'libraryItemIds': itemIds}),++ timeout: const Duration(seconds: 60),++ );++ return response.statusCode;++ } catch (e) {++ debugPrint('deleteLibraryItems error: $e');++ return 0;++ }++ }++++ /// Quick-match several items using Audiobookshelf's native batch endpoint.++ Future<bool> quickMatchLibraryItems(++ List<String> itemIds, {++ required String provider,++ bool overrideCover = false,++ bool overrideDetails = false,++ }) async {++ if (itemIds.isEmpty) return false;++ try {++ final response = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/items/batch/quickmatch'),++ body: jsonEncode({++ 'options': {++ 'provider': provider,++ 'overrideCover': overrideCover,++ 'overrideDetails': overrideDetails,++ },++ 'libraryItemIds': itemIds,++ }),++ timeout: const Duration(seconds: 60),++ );++ return response.statusCode == 200;++ } catch (e) {++ debugPrint('quickMatchLibraryItems error: $e');++ return false;++ }++ }++++ /// Mark several library items finished or unfinished in one request.++ Future<bool> updateLibraryItemsFinished(++ List<String> itemIds, {++ required bool isFinished,++ }) async {++ if (itemIds.isEmpty) return false;++ try {++ final response = await _authPatch(++ Uri.parse('$_cleanBaseUrl/api/me/progress/batch/update'),++ body: jsonEncode([++ for (final itemId in itemIds)++ {'libraryItemId': itemId, 'isFinished': isFinished},++ ]),++ );++ return response.statusCode == 200;++ } catch (e) {++ debugPrint('updateLibraryItemsFinished error: $e');++ return false;++ }++ }++++ /// Scan only the selected library items.++ Future<bool> scanLibraryItems(List<String> itemIds) async {++ if (itemIds.isEmpty) return false;++ try {++ final response = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/items/batch/scan'),++ body: jsonEncode({'libraryItemIds': itemIds}),++ timeout: const Duration(seconds: 60),++ );++ return response.statusCode == 200;++ } catch (e) {++ debugPrint('scanLibraryItems error: $e');++ return false;++ }++ }++++ /// Start embedding metadata into the selected items' audio files.++ Future<bool> embedLibraryItemsMetadata(List<String> itemIds) async {++ if (itemIds.isEmpty) return false;++ try {++ final response = await _authPost(++ Uri.parse('$_cleanBaseUrl/api/tools/batch/embed-metadata'),++ body: jsonEncode({'libraryItemIds': itemIds}),++ timeout: const Duration(seconds: 60),++ );++ return response.statusCode == 200;++ } catch (e) {++ debugPrint('embedLibraryItemsMetadata error: $e');++ return false;++ }++ }++/// Update a book's chapters. POST /api/items/:id/chapters/// [chapters] is the full ordered list of {id, start, end, title}. Pass an/// empty list to clear all chapters. Returns true on a 200 response.Future<bool> updateChapters(-- String itemId, List<Map<String, dynamic>> chapters) async {++ String itemId,++ List<Map<String, dynamic>> chapters,++ ) async {try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/items/$itemId/chapters'),@@@ -3423,10 -3582,10 +4223,14 @@@/// GET /api/search/chapters?asin=®ion=/// Returns the raw result map on 200 (chapters + runtime + brand-intro/outro/// durations, or {error, stringKey} when the lookup fails), else null.-- Future<Map<String, dynamic>?> searchChapters(String asin, String region) async {++ Future<Map<String, dynamic>?> searchChapters(++ String asin,++ String region,++ ) async {try {-- final uri = Uri.parse('$_cleanBaseUrl/api/search/chapters')-- .replace(queryParameters: {'asin': asin, 'region': region});++ final uri = Uri.parse(++ '$_cleanBaseUrl/api/search/chapters',++ ).replace(queryParameters: {'asin': asin, 'region': region});final r = await _authGet(uri, timeout: const Duration(seconds: 20));if (r.statusCode == 200) {final data = jsonDecode(r.body);@@@ -3444,8 -3603,8 +4248,9 @@@/// files. POST /api/tools/item/:id/embed-metadata?backup=0|1 (admin)Future<bool> embedMetadata(String itemId, {bool backup = true}) async {try {-- final uri = Uri.parse('$_cleanBaseUrl/api/tools/item/$itemId/embed-metadata')-- .replace(queryParameters: {'backup': backup ? '1' : '0'});++ final uri = Uri.parse(++ '$_cleanBaseUrl/api/tools/item/$itemId/embed-metadata',++ ).replace(queryParameters: {'backup': backup ? '1' : '0'});final r = await _authPost(uri);return r.statusCode == 200;} catch (e) {@@@ -3464,11 -3623,11 +4269,13 @@@}) async {try {final uri = Uri.parse('$_cleanBaseUrl/api/tools/item/$itemId/encode-m4b')-- .replace(queryParameters: {-- 'codec': codec,-- 'bitrate': bitrate,-- 'channels': '$channels',-- });++ .replace(++ queryParameters: {++ 'codec': codec,++ 'bitrate': bitrate,++ 'channels': '$channels',++ },++ );final r = await _authPost(uri);return r.statusCode == 200;} catch (e) {@@@ -3479,14 -3638,14 +4286,19 @@@/// Update podcast media settings (auto-download, etc.)/// PATCH /api/items/:id/media body: mediaUpdates at the media level-- Future<bool> updatePodcastMedia(String itemId, Map<String, dynamic> mediaUpdates) async {++ Future<bool> updatePodcastMedia(++ String itemId,++ Map<String, dynamic> mediaUpdates,++ ) async {try {final r = await _authPatch(Uri.parse('$_cleanBaseUrl/api/items/$itemId/media'),body: jsonEncode(mediaUpdates),);return r.statusCode == 200;-- } catch (e) { debugPrint('updatePodcastMedia error: $e'); }++ } catch (e) {++ debugPrint('updatePodcastMedia error: $e');++ }return false;}@@@ -3494,24 -3653,29 +4306,39 @@@/// Returns the HTTP status code (0 on exception). 200 = success;/// 403 = caller lacks the `delete` permission flag on the server. Callers/// should surface 403 with a "needs delete permission" message.- Future<int> deletePodcastEpisode(String podcastId, String episodeId) async {+ /// [hard] true also deletes the episode's audio file from the server's disk;+ /// false leaves the file and only drops the episode from the database.- Future<int> deletePodcastEpisode(String podcastId, String episodeId, {bool hard = false}) async {++ Future<int> deletePodcastEpisode(++ String podcastId,++ String episodeId, {++ bool hard = false,++ }) async {try {final r = await _authDelete(- Uri.parse('$_cleanBaseUrl/api/podcasts/$podcastId/episode/$episodeId'),- Uri.parse('$_cleanBaseUrl/api/podcasts/$podcastId/episode/$episodeId?hard=${hard ? 1 : 0}'),++ Uri.parse(++ '$_cleanBaseUrl/api/podcasts/$podcastId/episode/$episodeId?hard=${hard ? 1 : 0}',++ ),);return r.statusCode;-- } catch (e) { debugPrint('deletePodcastEpisode error: $e'); }++ } catch (e) {++ debugPrint('deletePodcastEpisode error: $e');++ }return 0;}/// Delete a library item (e.g. remove a podcast show). See [deletePodcastEpisode] for status semantics.- Future<int> deleteLibraryItem(String itemId) async {+ ///+ /// [hard] true deletes the item's folder from the server's disk as well;+ /// false keeps the files, so a later library scan can pick the item back up.+ Future<int> deleteLibraryItem(String itemId, {bool hard = false}) async {try {final r = await _authDelete(- Uri.parse('$_cleanBaseUrl/api/items/$itemId'),+ Uri.parse('$_cleanBaseUrl/api/items/$itemId?hard=${hard ? 1 : 0}'),);return r.statusCode;-- } catch (e) { debugPrint('deleteLibraryItem error: $e'); }++ } catch (e) {++ debugPrint('deleteLibraryItem error: $e');++ }return 0;}@@@ -3536,7 -3700,7 +4363,8 @@@try {final resp = await _authGet(Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3558,7 -3722,7 +4386,8 @@@'name': name,'items': items,}),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3579,7 -3743,7 +4408,8 @@@final resp = await _authPatch(Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId'),body: jsonEncode(body),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3592,7 -3756,7 +4422,8 @@@try {final resp = await _authDelete(Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return resp.statusCode == 200;} catch (_) {}return false;@@@ -3610,7 -3774,7 +4441,8 @@@final resp = await _authPost(Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId/item'),body: jsonEncode(body),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3629,7 -3793,7 +4461,8 @@@if (episodeId != null) path += '/$episodeId';final resp = await _authDelete(Uri.parse(path),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3658,7 -3822,7 +4491,8 @@@try {final resp = await _authGet(Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3683,7 -3847,7 +4517,8 @@@final resp = await _authPost(Uri.parse('$_cleanBaseUrl/api/collections'),body: jsonEncode(body),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3706,7 -3870,7 +4541,8 @@@final resp = await _authPatch(Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),body: jsonEncode(body),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3721,7 -3885,7 +4557,8 @@@try {final resp = await _authDelete(Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );return resp.statusCode;} catch (_) {}return 0;@@@ -3736,7 -3900,7 +4573,8 @@@final resp = await _authPost(Uri.parse('$_cleanBaseUrl/api/collections/$collectionId/book'),body: jsonEncode({'id': libraryItemId}),-- timeout: const Duration(seconds: 10));++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}@@@ -3751,8 -3915,8 +4589,11 @@@) async {try {final resp = await _authDelete(-- Uri.parse('$_cleanBaseUrl/api/collections/$collectionId/book/$libraryItemId'),-- timeout: const Duration(seconds: 10));++ Uri.parse(++ '$_cleanBaseUrl/api/collections/$collectionId/book/$libraryItemId',++ ),++ timeout: const Duration(seconds: 10),++ );if (resp.statusCode == 200) {return jsonDecode(resp.body) as Map<String, dynamic>;}diff --cc lib/services/audio_player_service.dartindex c3803ad8,57ab9884..5c9b9689--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@@ -1766,10 -1788,11 +1789,11 @@@ class AudioPlayerService extends Change}_preloadedNextBook = next;debugPrint(- '[PreBuffer] Pre-loaded next item: ${next['title']} ($nextItemId)',+ '[PreBuffer] Pre-loaded next item: ${next['title']} ($nextItemId) '+ 'start=${startS.toStringAsFixed(1)}s',);- if (Platform.isIOS) {+ if (AppPlatform.isIOS) {// Legacy native queue advancer kick (flag-off path).unawaited(_primeNativeQueueAdvancer(@@@ -1899,8 -1929,10 +1930,10 @@@),);- if (Platform.isIOS) {+ if (AppPlatform.isIOS) {unawaited(_iosAutoAdvanceKick());+ } else {+ unawaited(_finalizeAndroidAutoAdvance(oldTrackCount, startS));}// Notify LibraryProvider via auto-queue-specific callback (skipAutoAdvancediff --cc lib/services/audiobookshelf_update_service.dartindex 4d01f4e6,4d01f4e6..28de4cef--- a/lib/services/audiobookshelf_update_service.dart+++ b/lib/services/audiobookshelf_update_service.dart@@@ -73,6 -73,6 +73,45 @@@ class AudiobookshelfUpdateService}}++class AudiobookshelfUpdateController extends ChangeNotifier {++ AudiobookshelfUpdateController._();++++ static final AudiobookshelfUpdateController instance =++ AudiobookshelfUpdateController._();++++ AudiobookshelfServerUpdate? _update;++ String? _checkedFor;++ bool _isChecking = false;++++ AudiobookshelfServerUpdate? get update => _update;++ String? get checkedFor => _checkedFor;++ bool get isChecking => _isChecking;++++ bool shouldCheck(String currentVersion) {++ final version = currentVersion.trim();++ return version.isNotEmpty && _checkedFor != version;++ }++++ Future<void> check({required String currentVersion}) async {++ final version = currentVersion.trim();++ if (version.isEmpty || !shouldCheck(version)) return;++++ _checkedFor = version;++ _isChecking = true;++ _update = null;++ notifyListeners();++++ final update = await AudiobookshelfUpdateService.check(++ currentVersion: version,++ );++ if (_checkedFor != version) return;++++ _update = update;++ _isChecking = false;++ notifyListeners();++ }++}++class _ReleaseVersion {final _ServerVersion version;final String releaseUrl;diff --cc lib/services/player_settings.dartindex 3edd930c,0e715770..612e06aa--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@@ -10,9 -20,9 +20,12 @@@ class AutoRewindSettingsfinal bool enabled;final double minRewind;final double maxRewind;-- final double activationDelay; // seconds — how long pause must be before rewind kicks in-- final bool chapterBarrier; // don't rewind past the start of the current chapter-- final bool sessionStartRewind; // rewind by maxRewind when starting a new session++ final double++ activationDelay; // seconds — how long pause must be before rewind kicks in++ final bool++ chapterBarrier; // don't rewind past the start of the current chapter++ final bool++ sessionStartRewind; // rewind by maxRewind when starting a new sessionconst AutoRewindSettings({this.enabled = true,@@@ -29,8 -39,8 +42,10 @@@minRewind: await ScopedPrefs.getDouble('autoRewind_min') ?? 1.0,maxRewind: await ScopedPrefs.getDouble('autoRewind_max') ?? 30.0,activationDelay: await ScopedPrefs.getDouble('autoRewind_delay') ?? 0.0,-- chapterBarrier: await ScopedPrefs.getBool('autoRewind_chapterBarrier') ?? false,-- sessionStartRewind: await ScopedPrefs.getBool('autoRewind_sessionStart') ?? false,++ chapterBarrier:++ await ScopedPrefs.getBool('autoRewind_chapterBarrier') ?? false,++ sessionStartRewind:++ await ScopedPrefs.getBool('autoRewind_sessionStart') ?? false,);}@@@ -72,6 -82,6 +87,7 @@@ class PlayerSettings// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_membersettingsChanged.notifyListeners();}++/// Public trigger for external callers that save settings directly.static void notifySettingsChanged() => _notify();@@@ -92,7 -102,7 +108,11 @@@return defaultValue;}-- static Future<void> _set<T>(String key, T value, {bool notify = false}) async {++ static Future<void> _set<T>(++ String key,++ T value, {++ bool notify = false,++ }) async {if (value is bool) {await ScopedPrefs.setBool(key, value);} else if (value is int) {@@@ -108,9 -118,9 +128,18 @@@// ── General settings ──static Future<double> getDefaultSpeed() => _get('defaultSpeed', 1.0);-- static Future<void> setDefaultSpeed(double speed) => _set('defaultSpeed', speed);---- static const List<double> defaultSpeedPresets = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5];++ static Future<void> setDefaultSpeed(double speed) =>++ _set('defaultSpeed', speed);++++ static const List<double> defaultSpeedPresets = [++ 0.75,++ 1.0,++ 1.25,++ 1.5,++ 1.75,++ 2.0,++ 2.5,++ ];static Future<List<double>> getSpeedPresets() async {final raw = await _get('speedPresets', '');@@@ -127,7 -137,7 +156,11 @@@static Future<void> setSpeedPresets(List<double> presets) async {final sorted = [...presets]..sort();-- await _set('speedPresets', sorted.map((s) => s.toStringAsFixed(2)).join(','), notify: true);++ await _set(++ 'speedPresets',++ sorted.map((s) => s.toStringAsFixed(2)).join(','),++ notify: true,++ );}static Future<void> resetSpeedPresets() async {@@@ -137,79 -147,174 +170,275 @@@/// Audible region override for Find Missing Books (e.g. "us", "uk", "de")./// Empty string means use device locale.static Future<String> getAudibleRegion() => _get('audibleRegion', '');-- static Future<void> setAudibleRegion(String value) => _set('audibleRegion', value);++ static Future<void> setAudibleRegion(String value) =>++ _set('audibleRegion', value);/// Font-size multiplier for the elapsed/remaining/percent text on the player/// card (GH #230, accessibility). 1.0 = default.-- static Future<double> getProgressTextScale() => _get('progressTextScale', 1.0);++ static Future<double> getProgressTextScale() =>++ _get('progressTextScale', 1.0);static Future<void> setProgressTextScale(double v) =>_set('progressTextScale', v, notify: true);-- static Future<bool> getUpcomingReleasesSortByDate() => _get('upcomingReleasesSortByDate', false);-- static Future<void> setUpcomingReleasesSortByDate(bool value) => _set('upcomingReleasesSortByDate', value);-- static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);- static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);-- static Future<int> getRollingDownloadCount() => _get('rollingDownloadCount', 3);- static Future<void> setRollingDownloadCount(int value) => _set('rollingDownloadCount', value);-- static Future<bool> getRollingDownloadDeleteFinished() => _get('rollingDownloadDeleteFinished', false);- static Future<void> setRollingDownloadDeleteFinished(bool value) => _set('rollingDownloadDeleteFinished', value);-- static Future<bool> getQueueAutoDownload() => _get('queueAutoDownload', false);- static Future<void> setQueueAutoDownload(bool value) => _set('queueAutoDownload', value);-- static Future<bool> getAutoDownloadOnStream() => _get('autoDownloadOnStream', false);- static Future<void> setAutoDownloadOnStream(bool value) => _set('autoDownloadOnStream', value);++ static Future<bool> getUpcomingReleasesSortByDate() =>++ _get('upcomingReleasesSortByDate', false);++ static Future<void> setUpcomingReleasesSortByDate(bool value) =>++ _set('upcomingReleasesSortByDate', value);++ /// Last state of the "delete files from the server" checkbox in the delete+ /// confirm. Starts ticked and remembers what you picked, same as the web UI+ /// (which keeps `softDeleteDefault` in localStorage).- static Future<bool> getDeleteFromFileSystem() => _get('deleteFromFileSystem', true);- static Future<void> setDeleteFromFileSystem(bool value) => _set('deleteFromFileSystem', value);-- static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);- static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);-- static Future<int> getRollingDownloadCount() => _get('rollingDownloadCount', 3);- static Future<void> setRollingDownloadCount(int value) => _set('rollingDownloadCount', value);-- static Future<bool> getRollingDownloadDeleteFinished() => _get('rollingDownloadDeleteFinished', false);- static Future<void> setRollingDownloadDeleteFinished(bool value) => _set('rollingDownloadDeleteFinished', value);-- static Future<bool> getQueueAutoDownload() => _get('queueAutoDownload', false);- static Future<void> setQueueAutoDownload(bool value) => _set('queueAutoDownload', value);-- static Future<bool> getAutoDownloadOnStream() => _get('autoDownloadOnStream', false);- static Future<void> setAutoDownloadOnStream(bool value) => _set('autoDownloadOnStream', value);++ static Future<bool> getDeleteFromFileSystem() =>++ _get('deleteFromFileSystem', true);++ static Future<void> setDeleteFromFileSystem(bool value) =>++ _set('deleteFromFileSystem', value);++++ static Future<bool> getWifiOnlyDownloads() =>++ _get('wifiOnlyDownloads', false);++ static Future<void> setWifiOnlyDownloads(bool value) =>++ _set('wifiOnlyDownloads', value);++++ static Future<int> getRollingDownloadCount() =>++ _get('rollingDownloadCount', 3);++ static Future<void> setRollingDownloadCount(int value) =>++ _set('rollingDownloadCount', value);++++ static Future<bool> getRollingDownloadDeleteFinished() =>++ _get('rollingDownloadDeleteFinished', false);++ static Future<void> setRollingDownloadDeleteFinished(bool value) =>++ _set('rollingDownloadDeleteFinished', value);++++ static Future<bool> getQueueAutoDownload() =>++ _get('queueAutoDownload', false);++ static Future<void> setQueueAutoDownload(bool value) =>++ _set('queueAutoDownload', value);++++ static Future<bool> getAutoDownloadOnStream() =>++ _get('autoDownloadOnStream', false);++ static Future<void> setAutoDownloadOnStream(bool value) =>++ _set('autoDownloadOnStream', value);/// When on, starting a book that's part of a series automatically turns on/// series auto-download for that series (the same per-series toggle shown in/// the series sheet). Default off.-- static Future<bool> getAutoSeriesDownloadDefault() => _get('autoSeriesDownloadDefault', false);-- static Future<void> setAutoSeriesDownloadDefault(bool value) => _set('autoSeriesDownloadDefault', value);++ static Future<bool> getAutoSeriesDownloadDefault() =>++ _get('autoSeriesDownloadDefault', false);++ static Future<void> setAutoSeriesDownloadDefault(bool value) =>++ _set('autoSeriesDownloadDefault', value);/// Bookmark sort: 'newest' (default) or 'position'static Future<String> getBookmarkSort() => _get('bookmarkSort', 'newest');-- static Future<void> setBookmarkSort(String value) => _set('bookmarkSort', value);++ static Future<void> setBookmarkSort(String value) =>++ _set('bookmarkSort', value);// The dedicated Podcasts tab implies merged behavior: playback must survive// the tab-driven library flips and the Absorbing tab must keep showing the// playing item from either tab.static Future<bool> getMergeAbsorbingLibraries() async =>-- await _get('mergeAbsorbingLibraries', false) || await getPodcastTabEnabled();++ await _get('mergeAbsorbingLibraries', false) ||++ await getPodcastTabEnabled();++/// The stored toggle value, without the Podcasts-tab implication. For the/// settings UI and backups - exporting the effective value would bake/// merge=true into a restore permanently.-- static Future<bool> getMergeAbsorbingLibrariesRaw() => _get('mergeAbsorbingLibraries', false);-- static Future<void> setMergeAbsorbingLibraries(bool value) => _set('mergeAbsorbingLibraries', value);++ static Future<bool> getMergeAbsorbingLibrariesRaw() =>++ _get('mergeAbsorbingLibraries', false);++ static Future<void> setMergeAbsorbingLibraries(bool value) =>++ _set('mergeAbsorbingLibraries', value);// Dedicated bottom-nav Podcasts tab (pinned to one podcast library).-- static Future<bool> getPodcastTabEnabled() => _get('podcastTabEnabled', false);-- static Future<void> setPodcastTabEnabled(bool value) => _set('podcastTabEnabled', value, notify: true);-- static Future<String> getPodcastTabLibraryId() => _get('podcastTabLibraryId', '');-- static Future<void> setPodcastTabLibraryId(String value) => _set('podcastTabLibraryId', value, notify: true);++ static Future<bool> getPodcastTabEnabled() =>++ _get('podcastTabEnabled', false);++ static Future<void> setPodcastTabEnabled(bool value) =>++ _set('podcastTabEnabled', value, notify: true);++ static Future<String> getPodcastTabLibraryId() =>++ _get('podcastTabLibraryId', '');++ static Future<void> setPodcastTabLibraryId(String value) =>++ _set('podcastTabLibraryId', value, notify: true);// Background new-episode notification checks, in minutes (0 = off).// WorkManager's floor for periodic jobs is 15 minutes.-- static Future<int> getEpisodeNotifIntervalMinutes() => _get('episodeNotifIntervalMinutes', 0);-- static Future<void> setEpisodeNotifIntervalMinutes(int value) => _set('episodeNotifIntervalMinutes', value, notify: true);++ static Future<int> getEpisodeNotifIntervalMinutes() =>++ _get('episodeNotifIntervalMinutes', 0);++ static Future<void> setEpisodeNotifIntervalMinutes(int value) =>++ _set('episodeNotifIntervalMinutes', value, notify: true);-- static Future<int> getMaxConcurrentDownloads() => _get('maxConcurrentDownloads', 1);-- static Future<void> setMaxConcurrentDownloads(int value) => _set('maxConcurrentDownloads', value);++ static Future<int> getMaxConcurrentDownloads() =>++ _get('maxConcurrentDownloads', 1);++ static Future<void> setMaxConcurrentDownloads(int value) =>++ _set('maxConcurrentDownloads', value);// ── Stats page ──- // Goal period shown on the stats page: 'off' | 'daily' | 'weekly' | 'monthly'.- static Future<String> getStatsGoalType() => _get('stats_goal_type', 'off');- static Future<void> setStatsGoalType(String value) => _set('stats_goal_type', value, notify: true);+ /// Listening goal periods, in the order they're shown.+ static const statsGoalPeriods = ['daily', 'weekly', 'monthly'];++ static String _statsGoalKey(String period) => 'stats_goal_${period}_minutes';+ static String _statsGoalOnKey(String period) => 'stats_goal_${period}_on';++ /// Target used when a period is first switched on, so the goal card starts+ /// somewhere sensible instead of at 0%.+ static int defaultStatsGoalMinutes(String period) => switch (period) {- 'weekly' => 7 * 60,- 'monthly' => 30 * 60,- _ => 60,- };++ 'weekly' => 7 * 60,++ 'monthly' => 30 * 60,++ _ => 60,++ };++ /// The most a period's target can be: all the time that period holds. These+ /// match the rolling windows the stats page actually sums (7 and 30 days+ /// back from today), not calendar weeks or months.+ static int maxStatsGoalMinutes(String period) => switch (period) {- 'weekly' => 7 * 24 * 60,- 'monthly' => 30 * 24 * 60,- _ => 24 * 60,- };++ 'weekly' => 7 * 24 * 60,++ 'monthly' => 30 * 24 * 60,++ _ => 24 * 60,++ };++ /// Target listening minutes for one goal period, or 0 when that goal is+ /// switched off. All three periods can be on at once. The target survives+ /// being switched off, so turning a goal back on restores the number you+ /// set instead of dropping back to the default.+ static Future<int> getStatsGoalMinutesFor(String period) async {+ await _migrateStatsGoals();+ if (!await _get(_statsGoalOnKey(period), false)) return 0;+ return _get(_statsGoalKey(period), defaultStatsGoalMinutes(period));+ }++ static Future<void> setStatsGoalMinutesFor(String period, int minutes) async {+ await _migrateStatsGoals();+ if (minutes <= 0) {+ await _set(_statsGoalOnKey(period), false, notify: true);+ return;+ }- await _set(_statsGoalKey(period), minutes.clamp(1, maxStatsGoalMinutes(period)));++ await _set(++ _statsGoalKey(period),++ minutes.clamp(1, maxStatsGoalMinutes(period)),++ );+ await _set(_statsGoalOnKey(period), true, notify: true);+ }- /// Target listening minutes for the active goal period.- static Future<int> getStatsGoalMinutes() => _get('stats_goal_minutes', 30);- static Future<void> setStatsGoalMinutes(int value) => _set('stats_goal_minutes', value, notify: true);+ /// Switch a period's goal on or off without disturbing its target.+ static Future<void> setStatsGoalEnabled(String period, bool on) async {+ await _migrateStatsGoals();+ await _set(_statsGoalOnKey(period), on, notify: true);+ }++ /// One-time migration from the single active-period goal to per-period+ /// targets, so an existing goal survives the upgrade. Runs per account,+ /// which is why it hangs off the getters instead of app start.+ static Future<void> _migrateStatsGoals() async {+ if (await ScopedPrefs.containsKey('stats_goal_migrated')) return;+ final oldPeriod = await _get('stats_goal_type', 'off');+ if (statsGoalPeriods.contains(oldPeriod)) {+ final oldMinutes = await _get('stats_goal_minutes', 30);- await _set(_statsGoalKey(oldPeriod),- oldMinutes.clamp(1, maxStatsGoalMinutes(oldPeriod)));++ await _set(++ _statsGoalKey(oldPeriod),++ oldMinutes.clamp(1, maxStatsGoalMinutes(oldPeriod)),++ );+ await _set(_statsGoalOnKey(oldPeriod), true);+ }+ await _set('stats_goal_migrated', true);+ }++ /// Territories that start the week on Sunday or Saturday, from CLDR.+ /// Everywhere else starts on Monday, which is most of the world.+ static const _sundayFirstCountries = {- 'AG', 'AS', 'BD', 'BR', 'BS', 'BT', 'BW', 'BZ', 'CA', 'CN', 'CO', 'DM',- 'DO', 'ET', 'GT', 'GU', 'HK', 'HN', 'ID', 'IL', 'IN', 'JM', 'JP', 'KE',- 'KH', 'KR', 'LA', 'MH', 'MM', 'MO', 'MT', 'MX', 'MZ', 'NI', 'NP', 'PA',- 'PE', 'PH', 'PK', 'PR', 'PY', 'SA', 'SG', 'SV', 'TH', 'TT', 'TW', 'UM',- 'US', 'VE', 'VI', 'WS', 'YE', 'ZA', 'ZW',++ 'AG',++ 'AS',++ 'BD',++ 'BR',++ 'BS',++ 'BT',++ 'BW',++ 'BZ',++ 'CA',++ 'CN',++ 'CO',++ 'DM',++ 'DO',++ 'ET',++ 'GT',++ 'GU',++ 'HK',++ 'HN',++ 'ID',++ 'IL',++ 'IN',++ 'JM',++ 'JP',++ 'KE',++ 'KH',++ 'KR',++ 'LA',++ 'MH',++ 'MM',++ 'MO',++ 'MT',++ 'MX',++ 'MZ',++ 'NI',++ 'NP',++ 'PA',++ 'PE',++ 'PH',++ 'PK',++ 'PR',++ 'PY',++ 'SA',++ 'SG',++ 'SV',++ 'TH',++ 'TT',++ 'TW',++ 'UM',++ 'US',++ 'VE',++ 'VI',++ 'WS',++ 'YE',++ 'ZA',++ 'ZW',+ };+ static const _saturdayFirstCountries = {- 'AE', 'AF', 'BH', 'DJ', 'DZ', 'EG', 'IQ', 'IR', 'JO', 'KW', 'LY', 'OM',- 'QA', 'SD', 'SY',++ 'AE',++ 'AF',++ 'BH',++ 'DJ',++ 'DZ',++ 'EG',++ 'IQ',++ 'IR',++ 'JO',++ 'KW',++ 'LY',++ 'OM',++ 'QA',++ 'SD',++ 'SY',+ };++ /// Day the stats week starts on: 0 = Sunday, 1 = Monday, 6 = Saturday. Same+ /// numbering as `MaterialLocalizations.firstDayOfWeekIndex`.+ ///+ /// Defaults from the DEVICE locale's country rather than the app's language+ /// setting - the language picker stores a bare language code with no region,+ /// so an English UI would otherwise report Sunday for the whole world.+ static int defaultStatsWeekStart() {- final country = ui.PlatformDispatcher.instance.locale.countryCode?.toUpperCase();++ final country = ui.PlatformDispatcher.instance.locale.countryCode++ ?.toUpperCase();+ if (country == null) return 1;+ if (_sundayFirstCountries.contains(country)) return 0;+ if (_saturdayFirstCountries.contains(country)) return 6;+ return 1;+ }++ static Future<int> getStatsWeekStart() async =>+ await ScopedPrefs.getInt('stats_week_start') ?? defaultStatsWeekStart();+ static Future<void> setStatsWeekStart(int day) =>+ _set('stats_week_start', day, notify: true);/// Yearly book-challenge target. 0 = off.static Future<int> getStatsBookGoal() => _get('stats_book_goal', 0);-- static Future<void> setStatsBookGoal(int value) => _set('stats_book_goal', value, notify: true);++ static Future<void> setStatsBookGoal(int value) =>++ _set('stats_book_goal', value, notify: true);/// Wall-clock seconds saved by listening above 1x. Banked live by the/// player as listening time accrues; read-only here.@@@ -237,20 -342,20 +466,25 @@@final v = await _get('stats_chart_style', 'bar');return v == 'heatmap' ? 'bar' : v;}-- static Future<void> setStatsChartStyle(String value) => _set('stats_chart_style', value, notify: true);++++ static Future<void> setStatsChartStyle(String value) =>++ _set('stats_chart_style', value, notify: true);/// Days covered by the bar/line chart: 7 or 30. The heatmap is always a year.static Future<int> getStatsChartRange() => _get('stats_chart_range', 7);-- static Future<void> setStatsChartRange(int value) => _set('stats_chart_range', value, notify: true);++ static Future<void> setStatsChartRange(int value) =>++ _set('stats_chart_range', value, notify: true);/// Stats page section layout (ids ordered / hidden), per account.-- static Future<List<String>> getStatsSectionOrder() => ScopedPrefs.getStringList('stats_section_order');++ static Future<List<String>> getStatsSectionOrder() =>++ ScopedPrefs.getStringList('stats_section_order');static Future<void> setStatsSectionOrder(List<String> order) async {await ScopedPrefs.setStringList('stats_section_order', order);_notify();}-- static Future<List<String>> getStatsHiddenSections() => ScopedPrefs.getStringList('stats_hidden_sections');++ static Future<List<String>> getStatsHiddenSections() =>++ ScopedPrefs.getStringList('stats_hidden_sections');static Future<void> setStatsHiddenSections(List<String> hidden) async {await ScopedPrefs.setStringList('stats_hidden_sections', hidden);_notify();@@@ -265,6 -370,6 +499,7 @@@final value = await ScopedPrefs.getString('bookQueueMode');return value ?? await getQueueMode();}++static Future<void> setBookQueueMode(String value) =>_serializeQueueModeMutation(() => _set('bookQueueMode', value, notify: true),@@@ -278,6 -383,6 +513,7 @@@final value = await ScopedPrefs.getString('podcastQueueMode');return value ?? await getQueueMode();}++static Future<void> setPodcastQueueMode(String value) =>_serializeQueueModeMutation(() => _set('podcastQueueMode', value, notify: true),@@@ -290,6 -395,6 +526,7 @@@final prefs = await SharedPreferences.getInstance();return prefs.getString('podcast_advance_dir_$showId') ?? 'oldest_first';}++static Future<void> setPodcastAdvanceDir(String showId, String value) async {final prefs = await SharedPreferences.getInstance();await prefs.setString('podcast_advance_dir_$showId', value);@@@ -303,7 -408,7 +540,11 @@@final prefs = await SharedPreferences.getInstance();return prefs.getString('podcast_new_ep_pos_$showId') ?? 'start';}-- static Future<void> setPodcastNewEpisodePosition(String showId, String value) async {++++ static Future<void> setPodcastNewEpisodePosition(++ String showId,++ String value,++ ) async {final prefs = await SharedPreferences.getInstance();await prefs.setString('podcast_new_ep_pos_$showId', value);_notify();@@@ -314,6 -419,6 +555,7 @@@final s = await ScopedPrefs.getString('queuePlaylistId');return (s == null || s.isEmpty) ? null : s;}++static Future<void> setQueuePlaylistId(String? id) =>_serializeQueueModeMutation(() async {if (id == null || id.isEmpty) {@@@ -371,18 -476,18 +613,20 @@@static Future<String?> getQueueCollectionName() =>ScopedPrefs.getString('queueCollectionName');-- static Future<void> setQueueModeCollection(String collectionId, String name) =>-- _serializeQueueModeMutation(() async {-- await ScopedPrefs.setString('bookQueueMode', 'collection');-- await ScopedPrefs.setString('queueCollectionId', collectionId);-- await ScopedPrefs.setString('queueCollectionName', name);-- // Collection mode replaces any active playlist queue.-- await ScopedPrefs.remove('queuePlaylistId');-- if ((await ScopedPrefs.getString('podcastQueueMode')) == 'playlist') {-- await ScopedPrefs.setString('podcastQueueMode', 'off');-- }-- _notify();-- });++ static Future<void> setQueueModeCollection(++ String collectionId,++ String name,++ ) => _serializeQueueModeMutation(() async {++ await ScopedPrefs.setString('bookQueueMode', 'collection');++ await ScopedPrefs.setString('queueCollectionId', collectionId);++ await ScopedPrefs.setString('queueCollectionName', name);++ // Collection mode replaces any active playlist queue.++ await ScopedPrefs.remove('queuePlaylistId');++ if ((await ScopedPrefs.getString('podcastQueueMode')) == 'playlist') {++ await ScopedPrefs.setString('podcastQueueMode', 'off');++ }++ _notify();++ });static Future<void> clearQueueModeCollection() =>_serializeQueueModeMutation(() async {@@@ -405,12 -510,60 +649,65 @@@return true;});+ /// Snapshot of the queue-mode settings, taken before a play activates a+ /// playlist/collection queue so a failed play can put them back.+ static Future<QueueModeSnapshot> queueModeSnapshot() async => (- bookMode: await getBookQueueMode(),- podcastMode: await getPodcastQueueMode(),- playlistId: await ScopedPrefs.getString('queuePlaylistId'),- collectionId: await ScopedPrefs.getString('queueCollectionId'),- collectionName: await ScopedPrefs.getString('queueCollectionName'),- );++ bookMode: await getBookQueueMode(),++ podcastMode: await getPodcastQueueMode(),++ playlistId: await ScopedPrefs.getString('queuePlaylistId'),++ collectionId: await ScopedPrefs.getString('queueCollectionId'),++ collectionName: await ScopedPrefs.getString('queueCollectionName'),++ );++ /// Restore a [queueModeSnapshot] if the given playlist queue is still the+ /// active one - same guard as [clearQueueModePlaylistIfActive], so a mode+ /// the user changed again in the meantime is left alone.+ static Future<bool> restoreQueueModeIfPlaylistActive(- String playlistId, QueueModeSnapshot snapshot) =>- _serializeQueueModeMutation(() async {- if (await getBookQueueMode() != 'playlist' ||- await getPodcastQueueMode() != 'playlist' ||- await getQueuePlaylistId() != playlistId) {- return false;- }- await _applyQueueModeSnapshot(snapshot);- return true;- });++ String playlistId,++ QueueModeSnapshot snapshot,++ ) => _serializeQueueModeMutation(() async {++ if (await getBookQueueMode() != 'playlist' ||++ await getPodcastQueueMode() != 'playlist' ||++ await getQueuePlaylistId() != playlistId) {++ return false;++ }++ await _applyQueueModeSnapshot(snapshot);++ return true;++ });++ static Future<bool> restoreQueueModeIfCollectionActive(- String collectionId, QueueModeSnapshot snapshot) =>- _serializeQueueModeMutation(() async {- if (await getBookQueueMode() != 'collection' ||- await getQueueCollectionId() != collectionId) {- return false;- }- await _applyQueueModeSnapshot(snapshot);- return true;- });++ String collectionId,++ QueueModeSnapshot snapshot,++ ) => _serializeQueueModeMutation(() async {++ if (await getBookQueueMode() != 'collection' ||++ await getQueueCollectionId() != collectionId) {++ return false;++ }++ await _applyQueueModeSnapshot(snapshot);++ return true;++ });++ static Future<void> _applyQueueModeSnapshot(QueueModeSnapshot s) async {+ Future<void> put(String key, String? value) => value == null+ ? ScopedPrefs.remove(key)+ : ScopedPrefs.setString(key, value);+ await put('bookQueueMode', s.bookMode);+ await put('podcastQueueMode', s.podcastMode);+ await put('queuePlaylistId', s.playlistId);+ await put('queueCollectionId', s.collectionId);+ await put('queueCollectionName', s.collectionName);+ _notify();+ }+/// One-time migration from the old boolean auto-play settings to queueMode.static Future<void> migrateQueueMode() async {if (await ScopedPrefs.containsKey('queueMode')) return;final autoBook = await ScopedPrefs.getBool('autoPlayNextBook') ?? false;final autoPod = await ScopedPrefs.getBool('autoPlayNextPodcast') ?? false;-- await ScopedPrefs.setString('queueMode', (autoBook || autoPod) ? 'auto_next' : 'off');++ await ScopedPrefs.setString(++ 'queueMode',++ (autoBook || autoPod) ? 'auto_next' : 'off',++ );}/// One-time migration from the unified queueMode to per-type book/podcast modes.@@@ -423,13 -576,13 +720,18 @@@// Legacy getters kept for backup service compatibilitystatic Future<bool> getAutoPlayNextBook() => _get('autoPlayNextBook', false);-- static Future<void> setAutoPlayNextBook(bool value) => _set('autoPlayNextBook', value);++ static Future<void> setAutoPlayNextBook(bool value) =>++ _set('autoPlayNextBook', value);-- static Future<bool> getAutoPlayNextPodcast() => _get('autoPlayNextPodcast', false);-- static Future<void> setAutoPlayNextPodcast(bool value) => _set('autoPlayNextPodcast', value);++ static Future<bool> getAutoPlayNextPodcast() =>++ _get('autoPlayNextPodcast', false);++ static Future<void> setAutoPlayNextPodcast(bool value) =>++ _set('autoPlayNextPodcast', value);-- static Future<String> getWhenFinished() => _get('whenFinished', 'auto_remove');-- static Future<void> setWhenFinished(String value) => _set('whenFinished', value);++ static Future<String> getWhenFinished() =>++ _get('whenFinished', 'auto_remove');++ static Future<void> setWhenFinished(String value) =>++ _set('whenFinished', value);// ── Player UI settings (notify listeners on change) ──@@@ -439,9 -592,9 +741,7 @@@if (mode.name == stored) return mode;}final legacyBookSlider = await _get('showBookSlider', false);-- return legacyBookSlider-- ? CardScrubberMode.both-- : CardScrubberMode.chapter;++ return legacyBookSlider ? CardScrubberMode.both : CardScrubberMode.chapter;}static Future<void> setCardScrubberMode(CardScrubberMode mode) async {@@@ -453,31 -606,31 +753,42 @@@static Future<bool> getShowBookSlider() async =>await getCardScrubberMode() == CardScrubberMode.both;static Future<void> setShowBookSlider(bool value) => setCardScrubberMode(-- value ? CardScrubberMode.both : CardScrubberMode.chapter,-- );++ value ? CardScrubberMode.both : CardScrubberMode.chapter,++ );static Future<bool> getSpeedAdjustedTime() => _get('speedAdjustedTime', true);-- static Future<void> setSpeedAdjustedTime(bool value) => _set('speedAdjustedTime', value, notify: true);++ static Future<void> setSpeedAdjustedTime(bool value) =>++ _set('speedAdjustedTime', value, notify: true);static Future<int> getForwardSkip() => _get('forwardSkip', 30);-- static Future<void> setForwardSkip(int seconds) => _set('forwardSkip', seconds, notify: true);++ static Future<void> setForwardSkip(int seconds) =>++ _set('forwardSkip', seconds, notify: true);static Future<int> getBackSkip() => _get('backSkip', 10);-- static Future<void> setBackSkip(int seconds) => _set('backSkip', seconds, notify: true);-- static Future<bool> getSkipChapterBarrier() => _get('skipChapterBarrier', true);-- static Future<void> setSkipChapterBarrier(bool value) => _set('skipChapterBarrier', value);++ static Future<void> setBackSkip(int seconds) =>++ _set('backSkip', seconds, notify: true);++ static Future<bool> getSkipChapterBarrier() =>++ _get('skipChapterBarrier', true);++ static Future<void> setSkipChapterBarrier(bool value) =>++ _set('skipChapterBarrier', value);/// Per-library skip override: a library (podcast or book) can use its own/// forward/back amounts instead of the global ones. Both are set together;/// null = no override for that library.-- static Future<({int forward, int back})?> getSkipOverride(String libraryId) async {++ static Future<({int forward, int back})?> getSkipOverride(++ String libraryId,++ ) async {final fwd = await ScopedPrefs.getInt('skipOverrideForward_$libraryId');final back = await ScopedPrefs.getInt('skipOverrideBack_$libraryId');if (fwd == null || back == null) return null;return (forward: fwd, back: back);}-- static Future<void> setSkipOverride(String libraryId, {int? forward, int? back}) async {++ static Future<void> setSkipOverride(++ String libraryId, {++ int? forward,++ int? back,++ }) async {if (forward == null || back == null) {await ScopedPrefs.remove('skipOverrideForward_$libraryId');await ScopedPrefs.remove('skipOverrideBack_$libraryId');@@@ -507,11 -660,11 +818,14 @@@// Optional second, bigger skip pair on the player card (GH #242).static Future<bool> getLongSkipButtons() => _get('longSkipButtons', false);-- static Future<void> setLongSkipButtons(bool value) => _set('longSkipButtons', value, notify: true);++ static Future<void> setLongSkipButtons(bool value) =>++ _set('longSkipButtons', value, notify: true);static Future<int> getLongForwardSkip() => _get('longForwardSkip', 60);-- static Future<void> setLongForwardSkip(int seconds) => _set('longForwardSkip', seconds, notify: true);++ static Future<void> setLongForwardSkip(int seconds) =>++ _set('longForwardSkip', seconds, notify: true);static Future<int> getLongBackSkip() => _get('longBackSkip', 60);-- static Future<void> setLongBackSkip(int seconds) => _set('longBackSkip', seconds, notify: true);++ static Future<void> setLongBackSkip(int seconds) =>++ _set('longBackSkip', seconds, notify: true);/// Cached value for synchronous access in widget build methods.static bool showExplicitBadge = true;@@@ -529,18 -682,18 +843,23 @@@await _set('mp3IndexSeeking', value);}-- static Future<bool> getNotificationChapterProgress() => _get('notificationChapterProgress', false);-- static Future<void> setNotificationChapterProgress(bool value) => _set('notificationChapterProgress', value, notify: true);++ static Future<bool> getNotificationChapterProgress() =>++ _get('notificationChapterProgress', false);++ static Future<void> setNotificationChapterProgress(bool value) =>++ _set('notificationChapterProgress', value, notify: true);// Android only: when true, the phone media controls show speed + bookmark in// the two extra slots instead of chapter skip. Android Auto shows all of them// either way; this just reorders which pair the phone "borrows".-- static Future<bool> getMediaControlsSpeedBookmark() => _get('mediaControlsSpeedBookmark', false);-- static Future<void> setMediaControlsSpeedBookmark(bool value) => _set('mediaControlsSpeedBookmark', value, notify: true);++ static Future<bool> getMediaControlsSpeedBookmark() =>++ _get('mediaControlsSpeedBookmark', false);++ static Future<void> setMediaControlsSpeedBookmark(bool value) =>++ _set('mediaControlsSpeedBookmark', value, notify: true);// Android only: lower the volume for brief focus interruptions instead of// pausing. Pausing remains the default.-- static Future<bool> getDuckBriefInterruptions() => _get('duckBriefInterruptions', false);++ static Future<bool> getDuckBriefInterruptions() =>++ _get('duckBriefInterruptions', false);static Future<void> setDuckBriefInterruptions(bool value) =>_set('duckBriefInterruptions', value, notify: true);@@@ -550,7 -703,7 +869,8 @@@// action from the playback state (Android ACTION_SEEK_TO / iOS// changePlaybackPositionCommand). Default off.static Future<bool> getLockSeekBar() => _get('lockSeekBar', false);-- static Future<void> setLockSeekBar(bool value) => _set('lockSeekBar', value, notify: true);++ static Future<void> setLockSeekBar(bool value) =>++ _set('lockSeekBar', value, notify: true);// ── Sleep timer settings ──@@@ -559,65 -712,65 +879,89 @@@static Future<void> setShakeMode(String value) => _set('shakeMode', value);static Future<int> getShakeAddMinutes() => _get('shakeAddMinutes', 5);-- static Future<void> setShakeAddMinutes(int minutes) => _set('shakeAddMinutes', minutes);++ static Future<void> setShakeAddMinutes(int minutes) =>++ _set('shakeAddMinutes', minutes);// 'veryLow', 'low', 'medium', 'high', 'veryHigh'-- static Future<String> getShakeSensitivity() => _get('shakeSensitivity', 'medium');-- static Future<void> setShakeSensitivity(String value) => _set('shakeSensitivity', value);++ static Future<String> getShakeSensitivity() =>++ _get('shakeSensitivity', 'medium');++ static Future<void> setShakeSensitivity(String value) =>++ _set('shakeSensitivity', value);/// Linear-acceleration threshold (m/s², gravity excluded) that a shake must/// exceed to be registered. Lower = more sensitive.static double shakeThresholdFor(String sensitivity) {switch (sensitivity) {-- case 'veryHigh': return 8.0;-- case 'high': return 13.0;-- case 'low': return 23.0;-- case 'veryLow': return 28.0;++ case 'veryHigh':++ return 8.0;++ case 'high':++ return 13.0;++ case 'low':++ return 23.0;++ case 'veryLow':++ return 28.0;case 'medium':-- default: return 18.0;++ default:++ return 18.0;}}static Future<int> getSleepTimerMinutes() => _get('sleepTimerMinutes', 30);-- static Future<void> setSleepTimerMinutes(int minutes) => _set('sleepTimerMinutes', minutes);++ static Future<void> setSleepTimerMinutes(int minutes) =>++ _set('sleepTimerMinutes', minutes);static Future<int> getSleepTimerChapters() => _get('sleepTimerChapters', 1);-- static Future<void> setSleepTimerChapters(int chapters) => _set('sleepTimerChapters', chapters);++ static Future<void> setSleepTimerChapters(int chapters) =>++ _set('sleepTimerChapters', chapters);-- static Future<bool> getResetSleepOnPause() => _get('resetSleepOnPause', false);-- static Future<void> setResetSleepOnPause(bool value) => _set('resetSleepOnPause', value);++ static Future<bool> getResetSleepOnPause() =>++ _get('resetSleepOnPause', false);++ static Future<void> setResetSleepOnPause(bool value) =>++ _set('resetSleepOnPause', value);static Future<bool> getSleepFadeOut() => _get('sleepFadeOut', true);-- static Future<void> setSleepFadeOut(bool value) => _set('sleepFadeOut', value);++ static Future<void> setSleepFadeOut(bool value) =>++ _set('sleepFadeOut', value);static Future<int> getSleepFadeDuration() => _get('sleepFadeDuration', 30);-- static Future<void> setSleepFadeDuration(int seconds) => _set('sleepFadeDuration', seconds);++ static Future<void> setSleepFadeDuration(int seconds) =>++ _set('sleepFadeDuration', seconds);static Future<bool> getSleepChime() => _get('sleepChime', false);static Future<void> setSleepChime(bool value) => _set('sleepChime', value);static Future<double> getSleepChimeVolume() => _get('sleepChimeVolume', 2.0);-- static Future<void> setSleepChimeVolume(double value) => _set('sleepChimeVolume', value);++ static Future<void> setSleepChimeVolume(double value) =>++ _set('sleepChimeVolume', value);static Future<int> getSleepRewindSeconds() => _get('sleepRewindSeconds', 0);-- static Future<void> setSleepRewindSeconds(int seconds) => _set('sleepRewindSeconds', seconds);++ static Future<void> setSleepRewindSeconds(int seconds) =>++ _set('sleepRewindSeconds', seconds);static Future<int> getSleepTimerTab() => _get('sleepTimerTab', 0);static Future<void> setSleepTimerTab(int tab) => _set('sleepTimerTab', tab);static Future<bool> getSheetGridView() => _get('sheetGridView', false);-- static Future<void> setSheetGridView(bool value) => _set('sheetGridView', value);-- static Future<bool> getSheetCollapseSeries() => _get('sheetCollapseSeries', true);-- static Future<void> setSheetCollapseSeries(bool value) => _set('sheetCollapseSeries', value);-- static Future<bool> getCollapseBookSeries() => _get('collapseBookSeries', false);-- static Future<void> setCollapseBookSeries(bool value) => _set('collapseBookSeries', value);++ static Future<void> setSheetGridView(bool value) =>++ _set('sheetGridView', value);++ static Future<bool> getSheetCollapseSeries() =>++ _get('sheetCollapseSeries', true);++ static Future<void> setSheetCollapseSeries(bool value) =>++ _set('sheetCollapseSeries', value);++ static Future<bool> getCollapseBookSeries() =>++ _get('collapseBookSeries', false);++ static Future<void> setCollapseBookSeries(bool value) =>++ _set('collapseBookSeries', value);static Future<bool> getHideEbookOnly() => _get('hideEbookOnly', false);-- static Future<void> setHideEbookOnly(bool value) => _set('hideEbookOnly', value, notify: true);++ static Future<void> setHideEbookOnly(bool value) =>++ _set('hideEbookOnly', value, notify: true);static Future<bool> getCollapseSeries() => _get('collapseSeries', false);-- static Future<void> setCollapseSeries(bool value) => _set('collapseSeries', value, notify: true);++ static Future<void> setCollapseSeries(bool value) =>++ _set('collapseSeries', value, notify: true);// ── Streaming cache ──/// 0 = disabled, > 0 = cache size in MB (LRU eviction)-- static Future<int> getStreamingCacheSizeMb() => _get('streamingCacheSizeMb', 256);++ static Future<int> getStreamingCacheSizeMb() =>++ _get('streamingCacheSizeMb', 256);static Future<void> setStreamingCacheSizeMb(int value) async {debugPrint('[Settings] Streaming cache set to: $value MB');await _set('streamingCacheSizeMb', value);@@@ -632,20 -785,20 +976,57 @@@// ── Library sort/filter persistence ──-- static Future<String> getLibrarySort() => _get('librarySort', 'recentlyAdded');-- static Future<void> setLibrarySort(String value) => _set('librarySort', value);++ static const List<int> bookshelfCoverSizes = [++ 60,++ 80,++ 100,++ 120,++ 140,++ 160,++ 180,++ 200,++ 220,++ ];++++ static int _snapBookshelfCoverSize(int value) {++ var closest = bookshelfCoverSizes.first;++ for (final size in bookshelfCoverSizes.skip(1)) {++ if ((size - value).abs() < (closest - value).abs()) {++ closest = size;++ }++ }++ return closest;++ }++++ static Future<int> getBookshelfCoverSize() async {++ final value = await _get('bookshelfCoverSize', 120);++ return _snapBookshelfCoverSize(value);++ }++++ static Future<void> setBookshelfCoverSize(int value) =>++ _set('bookshelfCoverSize', _snapBookshelfCoverSize(value), notify: true);++++ static Future<String> getLibrarySort() =>++ _get('librarySort', 'recentlyAdded');++ static Future<void> setLibrarySort(String value) =>++ _set('librarySort', value);static Future<bool> getLibrarySortAsc() => _get('librarySortAsc', false);-- static Future<void> setLibrarySortAsc(bool value) => _set('librarySortAsc', value);++ static Future<void> setLibrarySortAsc(bool value) =>++ _set('librarySortAsc', value);static Future<String> getLibraryFilter() => _get('libraryFilter', 'none');-- static Future<void> setLibraryFilter(String value) => _set('libraryFilter', value);++ static Future<void> setLibraryFilter(String value) =>++ _set('libraryFilter', value);-- static Future<String> getLibraryGenreFilter() => _get('libraryGenreFilter', '');-- static Future<void> setLibraryGenreFilter(String? value) => _set('libraryGenreFilter', value ?? '');++ static Future<String> getLibraryGenreFilter() =>++ _get('libraryGenreFilter', '');++ static Future<void> setLibraryGenreFilter(String? value) =>++ _set('libraryGenreFilter', value ?? '');static Future<String> getLibraryTagFilter() => _get('libraryTagFilter', '');-- static Future<void> setLibraryTagFilter(String? value) => _set('libraryTagFilter', value ?? '');++ static Future<void> setLibraryTagFilter(String? value) =>++ _set('libraryTagFilter', value ?? '');static Future<String> getLibraryMissingMetadataFilter() =>_get('libraryMissingMetadataFilter', '');@@@ -661,8 -814,8 +1042,10 @@@static Future<void> setLibraryFilterValueLabel(String? value) =>_set('libraryFilterValueLabel', value ?? '');-- static Future<String> getLibrarySeriesFilter() => _get('librarySeriesFilter', 'none');-- static Future<void> setLibrarySeriesFilter(String value) => _set('librarySeriesFilter', value);++ static Future<String> getLibrarySeriesFilter() =>++ _get('librarySeriesFilter', 'none');++ static Future<void> setLibrarySeriesFilter(String value) =>++ _set('librarySeriesFilter', value);static Future<int> getLibraryTab() => _get('libraryTab', 0);static Future<void> setLibraryTab(int value) => _set('libraryTab', value);@@@ -673,11 -826,11 +1056,14 @@@// ── Podcast library sort persistence ──-- static Future<String> getPodcastSort() => _get('podcastSort', 'recentlyAdded');-- static Future<void> setPodcastSort(String value) => _set('podcastSort', value);++ static Future<String> getPodcastSort() =>++ _get('podcastSort', 'recentlyAdded');++ static Future<void> setPodcastSort(String value) =>++ _set('podcastSort', value);static Future<bool> getPodcastSortAsc() => _get('podcastSortAsc', false);-- static Future<void> setPodcastSortAsc(bool value) => _set('podcastSortAsc', value);++ static Future<void> setPodcastSortAsc(bool value) =>++ _set('podcastSortAsc', value);static Future<String> getPodcastFilter() => _get('podcastFilter', 'none');static Future<void> setPodcastFilter(String value) =>@@@ -686,8 -839,8 +1072,7 @@@_get('podcastGenreFilter', '');static Future<void> setPodcastGenreFilter(String? value) =>_set('podcastGenreFilter', value ?? '');-- static Future<String> getPodcastTagFilter() =>-- _get('podcastTagFilter', '');++ static Future<String> getPodcastTagFilter() => _get('podcastTagFilter', '');static Future<void> setPodcastTagFilter(String? value) =>_set('podcastTagFilter', value ?? '');static Future<String> getPodcastFilterValue() =>@@@ -703,63 -856,63 +1088,82 @@@static Future<void> setSeriesSort(String value) => _set('seriesSort', value);static Future<bool> getSeriesSortAsc() => _get('seriesSortAsc', true);-- static Future<void> setSeriesSortAsc(bool value) => _set('seriesSortAsc', value);++ static Future<void> setSeriesSortAsc(bool value) =>++ _set('seriesSortAsc', value);static Future<String> getListsSort() => _get('listsSort', 'alphabetical');static Future<void> setListsSort(String value) => _set('listsSort', value);static Future<bool> getListsSortAsc() => _get('listsSortAsc', true);-- static Future<void> setListsSortAsc(bool value) => _set('listsSortAsc', value);++ static Future<void> setListsSortAsc(bool value) =>++ _set('listsSortAsc', value);static Future<String> getAuthorSort() => _get('authorSort', 'alphabetical');static Future<void> setAuthorSort(String value) => _set('authorSort', value);static Future<bool> getAuthorSortAsc() => _get('authorSortAsc', true);-- static Future<void> setAuthorSortAsc(bool value) => _set('authorSortAsc', value);++ static Future<void> setAuthorSortAsc(bool value) =>++ _set('authorSortAsc', value);-- static Future<String> getNarratorSort() => _get('narratorSort', 'alphabetical');-- static Future<void> setNarratorSort(String value) => _set('narratorSort', value);++ static Future<String> getNarratorSort() =>++ _get('narratorSort', 'alphabetical');++ static Future<void> setNarratorSort(String value) =>++ _set('narratorSort', value);static Future<bool> getNarratorSortAsc() => _get('narratorSortAsc', true);-- static Future<void> setNarratorSortAsc(bool value) => _set('narratorSortAsc', value);++ static Future<void> setNarratorSortAsc(bool value) =>++ _set('narratorSortAsc', value);-- static Future<bool> getShowGoodreadsButton() => _get('showGoodreadsButton', false);-- static Future<void> setShowGoodreadsButton(bool value) => _set('showGoodreadsButton', value);++ static Future<bool> getShowGoodreadsButton() =>++ _get('showGoodreadsButton', false);++ static Future<void> setShowGoodreadsButton(bool value) =>++ _set('showGoodreadsButton', value);static Future<bool> getLoggingEnabled() async {final prefs = await SharedPreferences.getInstance();return prefs.getBool('loggingEnabled') ?? false;}++static Future<void> setLoggingEnabled(bool value) async {final prefs = await SharedPreferences.getInstance();await prefs.setBool('loggingEnabled', value);}static Future<bool> getFullScreenPlayer() => _get('fullScreenPlayer', false);-- static Future<void> setFullScreenPlayer(bool value) => _set('fullScreenPlayer', value);++ static Future<void> setFullScreenPlayer(bool value) =>++ _set('fullScreenPlayer', value);// Ebook reader: turn pages with the volume keys. 'off' | 'normal'// (up = previous page, down = next, matching the ABS app) | 'mirrored'.-- static Future<String> getEreaderVolumeNav() => _get('ereaderVolumeNav', 'off');-- static Future<void> setEreaderVolumeNav(String value) => _set('ereaderVolumeNav', value, notify: true);++ static Future<String> getEreaderVolumeNav() =>++ _get('ereaderVolumeNav', 'off');++ static Future<void> setEreaderVolumeNav(String value) =>++ _set('ereaderVolumeNav', value, notify: true);// Keep turning pages with the volume keys even while audio is playing// (off = playing audio gives the keys back to system volume).-- static Future<bool> getEreaderVolumeNavWhilePlaying() => _get('ereaderVolumeNavWhilePlaying', false);-- static Future<void> setEreaderVolumeNavWhilePlaying(bool value) => _set('ereaderVolumeNavWhilePlaying', value, notify: true);++ static Future<bool> getEreaderVolumeNavWhilePlaying() =>++ _get('ereaderVolumeNavWhilePlaying', false);++ static Future<void> setEreaderVolumeNavWhilePlaying(bool value) =>++ _set('ereaderVolumeNavWhilePlaying', value, notify: true);/// When on, the screen is locked to portrait (rotation disabled). Default off/// keeps the current behaviour where all orientations are allowed.static Future<bool> getLockPortrait() => _get('lockPortrait', false);-- static Future<void> setLockPortrait(bool value) => _set('lockPortrait', value);++ static Future<void> setLockPortrait(bool value) =>++ _set('lockPortrait', value);-- static Future<bool> getSnappyTransitions() => _get('snappyTransitions', false);-- static Future<void> setSnappyTransitions(bool value) => _set('snappyTransitions', value);++ static Future<bool> getSnappyTransitions() =>++ _get('snappyTransitions', false);++ static Future<void> setSnappyTransitions(bool value) =>++ _set('snappyTransitions', value);static Future<bool> getClassicWording() => _get('classicWording', false);-- static Future<void> setClassicWording(bool value) => _set('classicWording', value);++ static Future<void> setClassicWording(bool value) =>++ _set('classicWording', value);static Future<bool> getRectangleCovers() => _get('rectangleCovers', false);-- static Future<void> setRectangleCovers(bool value) => _set('rectangleCovers', value, notify: true);++ static Future<void> setRectangleCovers(bool value) =>++ _set('rectangleCovers', value, notify: true);/// Per-library cover-shape override: 'rect', 'square', or null (= follow/// the global toggle). Lets an ebook library run tall covers while the@@@ -769,7 -922,7 +1173,10 @@@return (v == 'rect' || v == 'square') ? v : null;}-- static Future<void> setRectangleCoversOverride(String libraryId, String? value) async {++ static Future<void> setRectangleCoversOverride(++ String libraryId,++ String? value,++ ) async {if (value == null) {await ScopedPrefs.remove('rectangleCovers_$libraryId');} else {@@@ -788,15 -941,15 +1195,19 @@@}static Future<bool> getSectionGridView() => _get('sectionGridView', false);-- static Future<void> setSectionGridView(bool value) => _set('sectionGridView', value);++ static Future<void> setSectionGridView(bool value) =>++ _set('sectionGridView', value);static Future<bool> getCoverPlayButton() => _get('coverPlayButton', false);-- static Future<void> setCoverPlayButton(bool value) => _set('coverPlayButton', value, notify: true);++ static Future<void> setCoverPlayButton(bool value) =>++ _set('coverPlayButton', value, notify: true);/// Absorbing-card background style: 'blurred' (cover blur, default), 'gradient'/// (gradient from the extracted cover colors), or 'off' (plain theme surface).-- static Future<String> getCardBackground() => _get('cardBackground', 'blurred');-- static Future<void> setCardBackground(String value) => _set('cardBackground', value, notify: true);++ static Future<String> getCardBackground() =>++ _get('cardBackground', 'blurred');++ static Future<void> setCardBackground(String value) =>++ _set('cardBackground', value, notify: true);// ── Self-signed certificates (global, not per-user) ──@@@ -804,6 -957,6 +1215,7 @@@final prefs = await SharedPreferences.getInstance();return prefs.getBool('trustAllCerts') ?? false;}++static Future<void> setTrustAllCerts(bool value) async {final prefs = await SharedPreferences.getInstance();await prefs.setBool('trustAllCerts', value);@@@ -815,6 -968,6 +1227,7 @@@final prefs = await SharedPreferences.getInstance();return prefs.getBool('includePreReleases') ?? false;}++static Future<void> setIncludePreReleases(bool value) async {final prefs = await SharedPreferences.getInstance();await prefs.setBool('includePreReleases', value);@@@ -822,15 -975,15 +1235,33 @@@// ── Local server ──-- static Future<bool> getLocalServerEnabled() => _get('localServerEnabled', false);-- static Future<void> setLocalServerEnabled(bool value) => _set('localServerEnabled', value);++ static Future<bool> getLocalServerEnabled() =>++ _get('localServerEnabled', false);++ static Future<void> setLocalServerEnabled(bool value) =>++ _set('localServerEnabled', value);static Future<String> getLocalServerUrl() => _get('localServerUrl', '');-- static Future<void> setLocalServerUrl(String value) => _set('localServerUrl', value);++ static Future<void> setLocalServerUrl(String value) =>++ _set('localServerUrl', value);// ── Card button order ──-- static const defaultButtonOrder = ['chapters', 'speed', 'sleep', 'bookmarks', 'details', 'ebook', 'equalizer', 'cast', 'airplay', 'history', 'remove', 'car', 'notes', 'download'];++ static const defaultButtonOrder = [++ 'chapters',++ 'speed',++ 'sleep',++ 'bookmarks',++ 'details',++ 'ebook',++ 'equalizer',++ 'cast',++ 'airplay',++ 'history',++ 'remove',++ 'car',++ 'notes',++ 'download',++ ];static Future<List<String>> getCardButtonOrder() async {final stored = await ScopedPrefs.getStringList('card_button_order');@@@ -840,7 -993,7 +1271,9 @@@}// Append any new buttons that were added since the user last saved their orderfinal knownIds = allCardButtons.map((b) => b.id).toSet();-- final result = stored.where((id) => knownIds.contains(id) || id == '_more').toList();++ final result = stored++ .where((id) => knownIds.contains(id) || id == '_more')++ .toList();for (final b in allCardButtons) {if (!result.contains(b.id)) result.add(b.id);}@@@ -877,23 -1030,23 +1310,38 @@@static int _layoutToCount(String layout) {switch (layout) {-- case 'compact': return 3;-- case 'standard': return 4;-- case 'row': return 5;-- case 'expanded': return 6;-- case 'full': return 9;-- default: return 4;++ case 'compact':++ return 3;++ case 'standard':++ return 4;++ case 'row':++ return 5;++ case 'expanded':++ return 6;++ case 'full':++ return 9;++ default:++ return 4;}}static Future<bool> getCardIconsOnly() => _get('card_icons_only', false);-- static Future<void> setCardIconsOnly(bool v) async { await _set('card_icons_only', v); _notify(); }++ static Future<void> setCardIconsOnly(bool v) async {++ await _set('card_icons_only', v);++ _notify();++ }static Future<bool> getCardSingleRow() => _get('card_single_row', false);-- static Future<void> setCardSingleRow(bool v) async { await _set('card_single_row', v); _notify(); }++ static Future<void> setCardSingleRow(bool v) async {++ await _set('card_single_row', v);++ _notify();++ }static Future<bool> getCardMoreInline() => _get('card_more_inline', false);-- static Future<void> setCardMoreInline(bool v) async { await _set('card_more_inline', v); _notify(); }++ static Future<void> setCardMoreInline(bool v) async {++ await _set('card_more_inline', v);++ _notify();++ }// ── Appearance ──@@@ -908,6 -1061,6 +1356,7 @@@final prefs = await SharedPreferences.getInstance();return prefs.getString('language') ?? '';}++static Future<void> setLanguage(String value) async {final prefs = await SharedPreferences.getInstance();await prefs.setString('language', value);@@@ -917,7 -1070,7 +1366,8 @@@/// 'manual' pins the app to [getManualSeedColor]. (Legacy values fall through/// to dynamic since only 'manual' is special-cased.)static Future<String> getColorSource() => _get('colorSource', 'dynamic');-- static Future<void> setColorSource(String value) => _set('colorSource', value);++ static Future<void> setColorSource(String value) =>++ _set('colorSource', value);/// Whether the background gradient is removed (flat). In dark mode this also/// switches surfaces to pure black (OLED); in light mode to flat white.@@@ -925,17 -1078,17 +1375,22 @@@static Future<void> setFlatBackground(bool v) => _set('flatBackground', v);/// Seed color (ARGB int) used when [getColorSource] is 'manual'.-- static Future<int> getManualSeedColor() => _get('manualSeedColor', 0xFF7C6FBF);++ static Future<int> getManualSeedColor() =>++ _get('manualSeedColor', 0xFF7C6FBF);static Future<void> setManualSeedColor(int v) => _set('manualSeedColor', v);/// Strength of the primary-tinted background gradient (top alpha, 0 = flat).-- static Future<double> getGradientIntensity() => _get('gradientIntensity', 0.06);-- static Future<void> setGradientIntensity(double v) => _set('gradientIntensity', v);++ static Future<double> getGradientIntensity() =>++ _get('gradientIntensity', 0.06);++ static Future<void> setGradientIntensity(double v) =>++ _set('gradientIntensity', v);/// When manual color is on, also apply it to per-book surfaces (detail sheets,/// absorbing card background) instead of each book's cover color.-- static Future<bool> getUseColorEverywhere() => _get('useColorEverywhere', false);-- static Future<void> setUseColorEverywhere(bool v) => _set('useColorEverywhere', v);++ static Future<bool> getUseColorEverywhere() =>++ _get('useColorEverywhere', false);++ static Future<void> setUseColorEverywhere(bool v) =>++ _set('useColorEverywhere', v);/// Default start screen tab index: 0=Home, 1=Library, 2=Absorbing, 3=Stats, 4=Settingsstatic Future<int> getStartScreen() => _get('startScreen', 2);@@@ -943,8 -1096,8 +1398,10 @@@/// Cached seed color from the last cover-art derivation, so we can show/// the correct color immediately on restart without waiting for the image.-- static Future<int?> getCoverSeedColor() async => await ScopedPrefs.getInt('coverSeedColor');-- static Future<void> setCoverSeedColor(int value) => _set('coverSeedColor', value);++ static Future<int?> getCoverSeedColor() async =>++ await ScopedPrefs.getInt('coverSeedColor');++ static Future<void> setCoverSeedColor(int value) =>++ _set('coverSeedColor', value);/// Check if an item has no audio content./// For minified responses (library list), duration == 0 means no audio files.@@@ -961,7 -1114,7 +1418,8 @@@final numAudioFiles = (media['numAudioFiles'] as num?)?.toInt() ?? 0;if ((audioFiles != null && audioFiles.isNotEmpty) ||(tracks != null && tracks.isNotEmpty) ||-- numAudioFiles > 0) return false;++ numAudioFiles > 0)++ return false;return true; // No audio by any measure}diff --cc lib/services/server_log_export_service.dartindex 00000000,00000000..98318769new file mode 100644--- /dev/null+++ b/lib/services/server_log_export_service.dart@@@ -1,0 -1,0 +1,33 @@@++import 'dart:convert';++import 'dart:ui';++++import 'package:flutter/foundation.dart';++import 'package:share_plus/share_plus.dart';++++import '../utils/text_file_download.dart';++++class ServerLogExportService {++ const ServerLogExportService._();++++ static Future<void> exportText({++ required String fileName,++ required String content,++ Rect? sharePositionOrigin,++ }) async {++ if (kIsWeb) {++ await downloadTextFile(fileName: fileName, content: content);++ return;++ }++++ final file = XFile.fromData(++ Uint8List.fromList(utf8.encode(content)),++ name: fileName,++ mimeType: 'text/plain',++ );++ await Share.shareXFiles(++ [file],++ subject: 'Audiobookshelf server logs',++ sharePositionOrigin: sharePositionOrigin,++ );++ }++}diff --cc lib/services/socket_service.dartindex 531a79f0,531a79f0..b74da0f1--- a/lib/services/socket_service.dart+++ b/lib/services/socket_service.dart@@@ -133,6 -133,6 +133,71 @@@ class SocketService}}++ // Server log fan-out. Each consumer keeps its own minimum level so opening++ // another log surface later cannot steal or disable an existing listener.++ // The server is subscribed at the lowest requested threshold and entries++ // are filtered again before delivery to each consumer.++ final Map<void Function(Map<String, dynamic>), int> _serverLogListeners = {};++++ void addServerLogListener(++ void Function(Map<String, dynamic>) fn, {++ required int level,++ }) {++ _serverLogListeners[fn] = _validLogLevel(level);++ _syncServerLogSubscription();++ }++++ void updateServerLogListenerLevel(++ void Function(Map<String, dynamic>) fn,++ int level,++ ) {++ if (!_serverLogListeners.containsKey(fn)) return;++ _serverLogListeners[fn] = _validLogLevel(level);++ _syncServerLogSubscription();++ }++++ void removeServerLogListener(void Function(Map<String, dynamic>) fn) {++ if (_serverLogListeners.remove(fn) == null) return;++ _syncServerLogSubscription();++ }++++ int _validLogLevel(int level) => level.clamp(0, 6).toInt();++++ int? get _lowestRequestedLogLevel {++ if (_serverLogListeners.isEmpty) return null;++ var lowest = _serverLogListeners.values.first;++ for (final level in _serverLogListeners.values.skip(1)) {++ if (level < lowest) lowest = level;++ }++ return lowest;++ }++++ void _syncServerLogSubscription() {++ if (_socket?.connected != true) return;++ final level = _lowestRequestedLogLevel;++ if (level == null) {++ _socket!.emit('remove_log_listener');++ } else {++ _socket!.emit('set_log_listener', level);++ }++ }++++ void _handleServerLog(dynamic data) {++ final log = normalizeSocketMap(data);++ if (log == null) return;++ final rawLevel = log['level'];++ final level = rawLevel is num++ ? rawLevel.toInt()++ : int.tryParse(rawLevel?.toString() ?? '') ?? 0;++ for (final listener in Map.of(_serverLogListeners).entries) {++ if (level >= listener.value) listener.key(log);++ }++ }++++ void _registerServerLogEvents() {++ _socket!.on('log', _handleServerLog);++ }++@visibleForTestingstatic Map<String, dynamic>? normalizeSocketMap(Object? data) {if (data is Map<String, dynamic>) return data;@@@ -276,6 -276,6 +341,7 @@@_socket!.on('init', (_) {debugPrint('[Socket] Authenticated - user is online');++ _syncServerLogSubscription();});_socket!.on('auth_failed', (_) {@@@ -383,6 -383,6 +449,8 @@@_socket!.on('task_progress', _handleTaskProgress);_socket!.on('task_finished', _handleTaskFinished);++ _registerServerLogEvents();++// Ereader device list changed (admin-wide or per-user). Payload carries// the list already filtered for this connection's user._socket!.on('ereader-devices-updated', (data) {@@@ -478,6 -478,6 +546,7 @@@_socket!.on('init', (_) {debugPrint('[Socket] Authenticated - user is online');++ _syncServerLogSubscription();});_socket!.on('auth_failed', (_) {@@@ -540,6 -540,6 +609,8 @@@_socket!.on('task_progress', _handleTaskProgress);_socket!.on('task_finished', _handleTaskFinished);++ _registerServerLogEvents();++_socket!.on('ereader-devices-updated', (data) {if (data is! Map) return;final raw = data['ereaderDevices'] as List<dynamic>?;diff --cc lib/widgets/book_card.dartindex 02ac2dee,e14aabeb..89ac0797--- a/lib/widgets/book_card.dart+++ b/lib/widgets/book_card.dart@@@ -23,6 -20,6 +23,9 @@@ class BookCard extends StatelessWidgetfinal String? sourcePlaylistEpisodeId;final String? sourceCollectionId;final String? sourceCollectionName;++ final bool selectionMode;++ final bool selected;++ final VoidCallback? onSelectionToggle;const BookCard({super.key,@@@ -34,6 -31,6 +37,9 @@@this.sourcePlaylistEpisodeId,this.sourceCollectionId,this.sourceCollectionName,++ this.selectionMode = false,++ this.selected = false,++ this.onSelectionToggle,});@override@@@ -53,31 -51,22 +59,72 @@@// Progress from LibraryProvider (fetched via /api/me, same source as book detail)final progress = lib.getProgress(itemId);final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;-- final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;++ final isExplicit =++ PlayerSettings.showExplicitBadge && metadata['explicit'] == true;final isDownloaded = DownloadService().isDownloaded(itemId ?? '');// Only compute for podcast shows that aren't being rendered as an episode// (an episode card shows the recentEpisode payload, not show-level info).-- final unfinishedCount = (lib.isPodcastLibrary && item['recentEpisode'] == null)++ final unfinishedCount =++ (lib.isPodcastLibrary && item['recentEpisode'] == null)? lib.getUnfinishedEpisodeCount(item): 0;final headers = lib.mediaHeaders;- if (isWide) {- return _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit);+ final card = isWide- ? _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit)- : _buildCompactCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount);++ ? _buildWideCard(++ context,++ cs,++ tt,++ l,++ title,++ authorName,++ coverUrl,++ progress,++ headers,++ isExplicit: isExplicit,++ )++ : _buildCompactCard(++ context,++ cs,++ tt,++ l,++ title,++ authorName,++ coverUrl,++ progress,++ headers,++ isFinished: isFinished,++ isDownloaded: isDownloaded,++ isExplicit: isExplicit,++ unfinishedCount: unfinishedCount,++ );+- final canEdit = itemId != null &&++ final canEdit =++ itemId != null &&+ !lib.isPodcastLibrary &&+ !lib.isOffline &&+ context.watch<AuthProvider>().canUpdateMetadata;+ return HoverCoverActions(- onMenu: itemId == null ? null : () => _onLongPress(context),- editItemId: canEdit ? itemId : null,++ onMenu: itemId == null || selectionMode++ ? null++ : () => _onLongPress(context),++ editItemId: canEdit && !selectionMode ? itemId : null,++ selectionMode: selectionMode,++ selected: selected,++ onSelectionToggle: onSelectionToggle,+ child: card,+ );+ }+++ void _handleTap(BuildContext context) {++ if (selectionMode && onSelectionToggle != null) {++ onSelectionToggle!();++ return;+ }- return _buildCompactCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount);++ _navigateToDetail(context);+ }+void _navigateToDetail(BuildContext context) {final itemId = item['id'] as String?;if (itemId == null) return;@@@ -160,8 -149,8 +207,10 @@@shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),clipBehavior: Clip.antiAlias,child: InkWell(-- onTap: () => _navigateToDetail(context),- onLongPress: AppPlatform.isWeb ? null : () => _onLongPress(context),- onLongPress: () => _onLongPress(context),++ onTap: () => _handleTap(context),++ onLongPress: AppPlatform.isWeb || selectionMode++ ? null++ : () => _onLongPress(context),borderRadius: BorderRadius.circular(16),child: Row(children: [@@@ -171,23 -160,23 +220,51 @@@height: 120,child: Stack(children: [-- _CoverImage(coverUrl: coverUrl, cs: cs, fit: BoxFit.contain, httpHeaders: headers),++ _CoverImage(++ coverUrl: coverUrl,++ cs: cs,++ fit: BoxFit.contain,++ httpHeaders: headers,++ ),if (isExplicit)Positioned(-- top: 4, right: DownloadService().isDownloaded(item['id'] as String? ?? '') ? 30 : 4,++ top: 4,++ right:++ DownloadService().isDownloaded(++ item['id'] as String? ?? '',++ )++ ? 30++ : 4,child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),++ padding: const EdgeInsets.symmetric(++ horizontal: 4,++ vertical: 1,++ ),decoration: BoxDecoration(color: Colors.red.withValues(alpha: 0.85),borderRadius: BorderRadius.circular(4),),-- child: Text(l.bookCardExplicitBadge, style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w800)),++ child: Text(++ l.bookCardExplicitBadge,++ style: const TextStyle(++ color: Colors.white,++ fontSize: 9,++ fontWeight: FontWeight.w800,++ ),++ ),),),-- if (DownloadService().isDownloaded(item['id'] as String? ?? ''))++ if (DownloadService().isDownloaded(++ item['id'] as String? ?? '',++ ))const Positioned(-- left: 0, right: 0, bottom: 0,-- child: CoverStateBadges(isDownloaded: true, isFinished: false),++ left: 0,++ right: 0,++ bottom: 0,++ child: CoverStateBadges(++ isDownloaded: true,++ isFinished: false,++ ),),],),@@@ -195,7 -184,7 +272,10 @@@// Info sectionExpanded(child: Padding(-- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),++ padding: const EdgeInsets.symmetric(++ horizontal: 12,++ vertical: 10,++ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,mainAxisAlignment: MainAxisAlignment.center,@@@ -280,8 -269,8 +360,10 @@@AspectRatio(aspectRatio: coverAspectRatio,child: _PressableCard(-- onTap: () => _navigateToDetail(context),- onLongPress: AppPlatform.isWeb ? null : () => _onLongPress(context),- onLongPress: () => _onLongPress(context),++ onTap: () => _handleTap(context),++ onLongPress: AppPlatform.isWeb || selectionMode++ ? null++ : () => _onLongPress(context),borderRadius: 12,child: Card(elevation: 0,@@@ -294,7 -283,7 +376,12 @@@child: Stack(fit: StackFit.expand,children: [-- _CoverImage(coverUrl: coverUrl, cs: cs, httpHeaders: headers, coverAspectRatio: coverAspectRatio),++ _CoverImage(++ coverUrl: coverUrl,++ cs: cs,++ httpHeaders: headers,++ coverAspectRatio: coverAspectRatio,++ ),if (progress > 0 && !isFinished)Positioned(left: 0,@@@ -317,12 -306,12 +404,22 @@@top: unfinishedCount > 0 ? 26 : 4,right: 4,child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),++ padding: const EdgeInsets.symmetric(++ horizontal: 4,++ vertical: 1,++ ),decoration: BoxDecoration(color: Colors.red.withValues(alpha: 0.85),borderRadius: BorderRadius.circular(4),),-- child: Text(l.bookCardExplicitBadge, style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w800)),++ child: Text(++ l.bookCardExplicitBadge,++ style: const TextStyle(++ color: Colors.white,++ fontSize: 9,++ fontWeight: FontWeight.w800,++ ),++ ),),),if (unfinishedCount > 0)@@@ -331,7 -320,7 +428,9 @@@right: 4,child: Container(padding: const EdgeInsets.symmetric(-- horizontal: 6, vertical: 2),++ horizontal: 6,++ vertical: 2,++ ),decoration: BoxDecoration(color: cs.primary,borderRadius: BorderRadius.circular(10),@@@ -348,11 -337,11 +447,15 @@@),if (isFinished || isDownloaded)Positioned(-- left: 0, right: 0, bottom: 0,++ left: 0,++ right: 0,++ bottom: 0,child: CoverStateBadges(isDownloaded: isDownloaded,isFinished: isFinished,-- borderRadius: const BorderRadius.vertical(bottom: Radius.circular(12)),++ borderRadius: const BorderRadius.vertical(++ bottom: Radius.circular(12),++ ),),),],@@@ -381,9 -370,9 +484,7 @@@authorName,maxLines: 1,overflow: TextOverflow.ellipsis,-- style: tt.labelSmall?.copyWith(-- color: cs.onSurfaceVariant,-- ),++ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),),),],@@@ -399,7 -388,7 +500,13 @@@ class _CoverImage extends StatelessWidgfinal Map<String, String> httpHeaders;final double coverAspectRatio;-- const _CoverImage({required this.coverUrl, required this.cs, this.fit = BoxFit.cover, this.httpHeaders = const {}, this.coverAspectRatio = 1.0});++ const _CoverImage({++ required this.coverUrl,++ required this.cs,++ this.fit = BoxFit.cover,++ this.httpHeaders = const {},++ this.coverAspectRatio = 1.0,++ });@overrideWidget build(BuildContext context) {@@@ -416,8 -405,8 +523,16 @@@if (file.existsSync()) {return BlurPaddedCover(enabled: isSquare,-- blurChild: Image.file(file, fit: BoxFit.cover, errorBuilder: (_, __, ___) => const SizedBox.shrink()),-- child: Image.file(file, fit: effectiveFit, errorBuilder: (_, __, ___) => _placeholder()),++ blurChild: Image.file(++ file,++ fit: BoxFit.cover,++ errorBuilder: (_, __, ___) => const SizedBox.shrink(),++ ),++ child: Image.file(++ file,++ fit: effectiveFit,++ errorBuilder: (_, __, ___) => _placeholder(),++ ),);}return _placeholder();@@@ -486,9 -475,9 +601,10 @@@ class _PressableCardState extends Stateduration: const Duration(milliseconds: 100),reverseDuration: const Duration(milliseconds: 200),);-- _scale = Tween<double>(begin: 1.0, end: 0.96).animate(-- CurvedAnimation(parent: _controller, curve: Curves.easeInOut),-- );++ _scale = Tween<double>(++ begin: 1.0,++ end: 0.96,++ ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));}@override@@@ -512,10 -501,10 +628,7 @@@_controller.reverse();widget.onLongPress!();},-- child: ScaleTransition(-- scale: _scale,-- child: widget.child,-- ),++ child: ScaleTransition(scale: _scale, child: widget.child),);}}diff --cc lib/widgets/book_detail_sheet.dartindex 36c297bd,6284baff..1244718d--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@@ -46,8 -43,8 +46,9 @@@ import 'html_description.dart'import 'metadata_lookup_sheet.dart';import 'playlist_picker_sheet.dart';import 'collection_picker_sheet.dart';+ import 'delete_confirm_dialog.dart';import 'absorb_wave_icon.dart';+import 'adaptive_modal.dart';import 'stackable_sheet.dart';import 'ebook_router.dart';import '../utils/duration_format.dart';@@@ -1123,14 -1140,17 +1155,19 @@@ class _BookDetailSheetContentState exteif (!lib.isOffline && !lib.isPodcastLibrary && auth.isAdmin) {add(Icons.collections_bookmark_rounded, l.addToCollection, () => CollectionPickerSheet.show(context, widget.itemId));}- if (ebookFile != null && canReadEbook(ebookFile)) {+ if (!AppPlatform.isWeb && ebookFile != null && canReadEbook(ebookFile)) {add(Icons.menu_book_rounded, l.readEbook, () => _openEbookReader(context, auth, ebookFile, title));}- if (!AppPlatform.isWeb && ebookFile != null) {+ // Save/Send push the file elsewhere, which needs the server's own file+ // entry (with ino) - the cache-synthesized fallback can't serve them.+ final serverEbookFile = resolveEbookFile(_item);- if (serverEbookFile != null) {++ if (!AppPlatform.isWeb && serverEbookFile != null) {add(_ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded,- l.ebookSaveToDevice, () => _saveEbook(context, auth, ebookFile, title));+ l.ebookSaveToDevice, () => _saveEbook(context, auth, serverEbookFile, title));}- if (!AppPlatform.isWeb && ebookFile != null && auth.ereaderDevices.isNotEmpty) {- if (serverEbookFile != null && auth.ereaderDevices.isNotEmpty) {++ if (!AppPlatform.isWeb &&++ serverEbookFile != null &&++ auth.ereaderDevices.isNotEmpty) {add(Icons.send_to_mobile_rounded, l.sendToEreader, () => _sendToEreader(context, auth));}if (progress > 0 || isFinished) {diff --cc lib/widgets/card_progress_bar.dartindex a4d281f1,1555ee70..a34c8d05--- a/lib/widgets/card_progress_bar.dart+++ b/lib/widgets/card_progress_bar.dart@@@ -356,45 -344,22 +356,45 @@@ class _CardDualProgressBarState extendchild: CustomPaint(size: Size(w, 32), painter: AbsorbProgressPainter(progress: p, accent: widget.accent.withValues(alpha: 0.5), isDragging: _bookDragValue != null)),);})),- Padding(padding: const EdgeInsets.only(top: 2, bottom: 6), child: Row(- mainAxisAlignment: MainAxisAlignment.spaceBetween,- children: [- Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur / speedDiv : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),- if (_bookDragValue != null && _bookScrubSpeed < 1.0) Text(_scrubSpeedLabel(l, _bookScrubSpeed), style: tt.labelSmall?.copyWith(color: widget.accent, fontSize: 11, fontWeight: FontWeight.w500)),- Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur / speedDiv : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),- ],- )),+ Padding(+ padding: const EdgeInsets.only(top: 2, bottom: 6),+ child: Stack(+ alignment: Alignment.center,+ children: [+ Row(+ children: [- Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),++ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur / speedDiv : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),+ const Spacer(),- Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),++ Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur / speedDiv : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),+ ],+ ),+ if (_bookDragValue != null && _bookScrubSpeed < 1.0)+ Text(_scrubSpeedLabel(l, _bookScrubSpeed), style: tt.labelSmall?.copyWith(color: widget.accent, fontSize: 11, fontWeight: FontWeight.w500))+ else if (widget.showBookPercentage)+ Text(+ bookPercentageLabel,+ key: const ValueKey('desktop-current-percent'),+ style: bookPercentageStyle,+ ),+ ],+ ),+ ),] else ...[Row(children: [- Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11 * _progressTextScale, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),+ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur / speedDiv : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11 * _progressTextScale, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),const SizedBox(width: 8),Expanded(child: ClipRRect(borderRadius: BorderRadius.circular(4),child: LinearProgressIndicator(value: bookProgress, minHeight: 3, backgroundColor: cs.onSurface.withValues(alpha: 0.08), valueColor: AlwaysStoppedAnimation(widget.accent.withValues(alpha: 0.5))))),+ if (widget.showBookPercentage) ...[+ const SizedBox(width: 8),+ Text(+ bookPercentageLabel,+ key: const ValueKey('desktop-current-percent'),+ style: bookPercentageStyle,+ ),+ ],const SizedBox(width: 8),- Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11 * _progressTextScale, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),+ Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur / speedDiv : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11 * _progressTextScale, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),]),SizedBox(height: widget.compact ? 4 : 10),],diff --cc lib/widgets/desktop_batch_actions.dartindex 00000000,00000000..eb514082new file mode 100644--- /dev/null+++ b/lib/widgets/desktop_batch_actions.dart@@@ -1,0 -1,0 +1,357 @@@++import 'package:flutter/material.dart';++import 'package:provider/provider.dart';++++import '../l10n/app_localizations.dart';++import '../providers/auth_provider.dart';++import '../providers/library_provider.dart';++import '../services/audio_player_service.dart';++import 'delete_confirm_dialog.dart';++import 'overlay_toast.dart';++++class DesktopQuickMatchOptions {++ final String provider;++ final bool overrideCover;++ final bool overrideDetails;++++ const DesktopQuickMatchOptions({++ required this.provider,++ required this.overrideCover,++ required this.overrideDetails,++ });++}++++Future<DesktopQuickMatchOptions?> showDesktopQuickMatchDialog(++ BuildContext context, {++ required List<String> providers,++ required String initialProvider,++}) {++ final availableProviders = providers.isEmpty++ ? <String>[initialProvider]++ : providers.toSet().toList();++ var provider = availableProviders.contains(initialProvider)++ ? initialProvider++ : availableProviders.first;++ var overrideCover = true;++ var overrideDetails = true;++ final l = AppLocalizations.of(context)!;++++ return showDialog<DesktopQuickMatchOptions>(++ context: context,++ builder: (dialogContext) => StatefulBuilder(++ builder: (context, setLocalState) => AlertDialog(++ title: Text(l.quickMatch),++ content: SizedBox(++ width: 360,++ child: Column(++ mainAxisSize: MainAxisSize.min,++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ DropdownButtonFormField<String>(++ initialValue: provider,++ decoration: InputDecoration(labelText: l.libProvider),++ items: [++ for (final value in availableProviders)++ DropdownMenuItem(value: value, child: Text(value)),++ ],++ onChanged: (value) {++ if (value != null) {++ setLocalState(() => provider = value);++ }++ },++ ),++ const SizedBox(height: 12),++ CheckboxListTile(++ contentPadding: EdgeInsets.zero,++ title: const Text('Replace covers'),++ value: overrideCover,++ onChanged: (value) =>++ setLocalState(() => overrideCover = value ?? false),++ ),++ CheckboxListTile(++ contentPadding: EdgeInsets.zero,++ title: const Text('Replace details'),++ value: overrideDetails,++ onChanged: (value) =>++ setLocalState(() => overrideDetails = value ?? false),++ ),++ ],++ ),++ ),++ actions: [++ TextButton(++ onPressed: () => Navigator.pop(dialogContext),++ child: Text(l.cancel),++ ),++ FilledButton(++ onPressed: () => Navigator.pop(++ dialogContext,++ DesktopQuickMatchOptions(++ provider: provider,++ overrideCover: overrideCover,++ overrideDetails: overrideDetails,++ ),++ ),++ child: Text(l.quickMatch),++ ),++ ],++ ),++ ),++ );++}++++class DesktopBatchActions {++ const DesktopBatchActions._();++++ static Future<bool?> quickMatch(++ BuildContext context,++ List<String> itemIds,++ ) async {++ if (itemIds.isEmpty) return null;++ final auth = context.read<AuthProvider>();++ final lib = context.read<LibraryProvider>();++ final api = auth.apiService;++ if (api == null) return false;++++ final libraryProvider =++ lib.selectedLibrary?['provider']?.toString().trim() ?? '';++ final providers = await api.getMetadataProviders();++ if (!context.mounted) return null;++ final initialProvider = libraryProvider.isNotEmpty++ ? libraryProvider++ : (providers.isNotEmpty ? providers.first : 'audible');++ final options = await showDesktopQuickMatchDialog(++ context,++ providers: providers,++ initialProvider: initialProvider,++ );++ if (options == null || !context.mounted) return null;++++ final success = await api.quickMatchLibraryItems(++ itemIds,++ provider: options.provider,++ overrideCover: options.overrideCover,++ overrideDetails: options.overrideDetails,++ );++ if (!context.mounted) return success;++ final l = AppLocalizations.of(context)!;++ showOverlayToast(++ context,++ success++ ? l.adminMatchingStarted(l.selectedCount(itemIds.length))++ : l.failedToUpdateMetadata,++ icon: success++ ? Icons.check_circle_outline_rounded++ : Icons.error_outline_rounded,++ );++ return success;++ }++++ static Future<bool> setFinished(++ BuildContext context,++ List<String> itemIds, {++ required bool isFinished,++ }) async {++ if (itemIds.isEmpty) return false;++ final auth = context.read<AuthProvider>();++ final lib = context.read<LibraryProvider>();++ final api = auth.apiService;++ if (api == null) return false;++ final success = await api.updateLibraryItemsFinished(++ itemIds,++ isFinished: isFinished,++ );++ if (!context.mounted) return success;++ final l = AppLocalizations.of(context)!;++ if (success) await lib.refresh();++ if (!context.mounted) return success;++ showOverlayToast(++ context,++ success++ ? (isFinished++ ? l.playlistDetailItemsMarkedFinished(itemIds.length)++ : l.playlistDetailItemsMarkedUnfinished(itemIds.length))++ : l.failedToUpdateCheckConnection,++ icon: success++ ? (isFinished++ ? Icons.check_circle_outline_rounded++ : Icons.radio_button_unchecked_rounded)++ : Icons.error_outline_rounded,++ );++ return success;++ }++++ static Future<bool?> delete(++ BuildContext context,++ List<String> itemIds,++ ) async {++ if (itemIds.isEmpty) return null;++ final l = AppLocalizations.of(context)!;++ final choice = await showDeleteConfirmDialog(++ context,++ title: l.deleteFromServerTitle,++ message: l.selectedCount(itemIds.length),++ );++ if (choice == null || !context.mounted) return null;++++ final auth = context.read<AuthProvider>();++ final lib = context.read<LibraryProvider>();++ final api = auth.apiService;++ if (api == null) return false;++ final status = await api.deleteLibraryItems(++ itemIds,++ hard: choice.hardDelete,++ );++ if (!context.mounted) return status == 200;++ if (status == 200) {++ final player = AudioPlayerService();++ if (itemIds.contains(player.currentItemId)) {++ await player.stopWithoutSaving();++ }++ for (final itemId in itemIds) {++ await lib.removeFromAbsorbing(itemId);++ }++ await lib.refresh();++ if (!context.mounted) return true;++ showOverlayToast(++ context,++ l.deletedFromServer(l.selectedCount(itemIds.length)),++ icon: Icons.delete_outline_rounded,++ );++ return true;++ }++ showOverlayToast(++ context,++ status == 403 ? l.deletePermissionRequired : l.deleteFromServerFailed,++ icon: status == 403++ ? Icons.lock_outline_rounded++ : Icons.error_outline_rounded,++ );++ return false;++ }++}++++class DesktopBatchActionBar extends StatelessWidget {++ final int selectedCount;++ final int selectableCount;++ final bool busy;++ final bool canQuickMatch;++ final bool canMarkProgress;++ final bool canDelete;++ final VoidCallback onSelectAll;++ final VoidCallback onClear;++ final VoidCallback onQuickMatch;++ final VoidCallback onMarkFinished;++ final VoidCallback onMarkUnfinished;++ final VoidCallback onDelete;++++ const DesktopBatchActionBar({++ super.key,++ required this.selectedCount,++ required this.selectableCount,++ required this.busy,++ required this.canQuickMatch,++ this.canMarkProgress = true,++ required this.canDelete,++ required this.onSelectAll,++ required this.onClear,++ required this.onQuickMatch,++ required this.onMarkFinished,++ required this.onMarkUnfinished,++ required this.onDelete,++ });++++ @override++ Widget build(BuildContext context) {++ final cs = Theme.of(context).colorScheme;++ final l = AppLocalizations.of(context)!;++ final hasSelection = selectedCount > 0;++ final allSelected = selectableCount > 0 && selectedCount >= selectableCount;++++ return Material(++ elevation: 10,++ color: cs.surfaceContainerHigh,++ shadowColor: Colors.black.withValues(alpha: 0.35),++ borderRadius: BorderRadius.circular(28),++ clipBehavior: Clip.antiAlias,++ child: ConstrainedBox(++ constraints: const BoxConstraints(minHeight: 52),++ child: Padding(++ padding: const EdgeInsets.symmetric(horizontal: 8),++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ if (busy)++ const Padding(++ padding: EdgeInsets.all(10),++ child: SizedBox(++ width: 20,++ height: 20,++ child: CircularProgressIndicator(strokeWidth: 2),++ ),++ )++ else++ Padding(++ padding: const EdgeInsets.symmetric(horizontal: 10),++ child: Text(++ l.selectedCount(selectedCount),++ style: const TextStyle(fontWeight: FontWeight.w700),++ ),++ ),++ Tooltip(++ message: allSelected ? l.deselectAll : l.selectAll,++ child: IconButton(++ onPressed: busy || selectableCount == 0 ? null : onSelectAll,++ icon: Icon(++ allSelected++ ? Icons.deselect_rounded++ : Icons.select_all_rounded,++ ),++ ),++ ),++ if (canQuickMatch)++ Tooltip(++ message: l.quickMatch,++ child: IconButton(++ onPressed: busy || !hasSelection ? null : onQuickMatch,++ icon: const Icon(Icons.auto_fix_high_rounded),++ ),++ ),++ if (canMarkProgress) ...[++ Tooltip(++ message: l.markFinished,++ child: IconButton(++ onPressed: busy || !hasSelection ? null : onMarkFinished,++ icon: const Icon(Icons.check_circle_outline_rounded),++ ),++ ),++ Tooltip(++ message: l.markUnfinished,++ child: IconButton(++ onPressed: busy || !hasSelection ? null : onMarkUnfinished,++ icon: const Icon(Icons.radio_button_unchecked_rounded),++ ),++ ),++ ],++ if (canDelete)++ Tooltip(++ message: l.deleteFromServerAction,++ child: IconButton(++ onPressed: busy || !hasSelection ? null : onDelete,++ color: cs.error,++ icon: const Icon(Icons.delete_outline_rounded),++ ),++ ),++ Tooltip(++ message: l.downloadsCancelSelection,++ child: IconButton(++ onPressed: busy ? null : onClear,++ icon: const Icon(Icons.close_rounded),++ ),++ ),++ ],++ ),++ ),++ ),++ );++ }++}diff --cc lib/widgets/desktop_collapsible_sidebar.dartindex 8bbd8e81,00000000..692e4bb3mode 100644,000000..100644--- a/lib/widgets/desktop_collapsible_sidebar.dart+++ b/lib/widgets/desktop_collapsible_sidebar.dart@@@ -1,204 -1,0 +1,248 @@@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++typedef DesktopSidebarBuilder =+ Widget Function(BuildContext context, bool extended);+++class DesktopSidebarBranding extends StatelessWidget {++ const DesktopSidebarBranding({++ super.key,++ required this.extended,++ required this.leading,++ required this.title,++ this.titleStyle,++ });++++ static const leadingKey = ValueKey<String>(++ 'desktop-sidebar-branding-leading',++ );++++ final bool extended;++ final Widget leading;++ final String title;++ final TextStyle? titleStyle;++++ @override++ Widget build(BuildContext context) {++ return Row(++ children: [++ SizedBox(++ key: leadingKey,++ width: 48,++ height: 48,++ child: Center(child: leading),++ ),++ if (extended) ...[++ const SizedBox(width: 12),++ Expanded(++ child: Text(++ title,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: titleStyle,++ ),++ ),++ ],++ ],++ );++ }++}+++class DesktopSidebarLayout extends StatelessWidget {+ const DesktopSidebarLayout({+ super.key,+ required this.pinned,+ required this.canPin,+ required this.onPinnedChanged,+ required this.sidebarBuilder,+ required this.child,+ });++ static const reservedSpaceKey = ValueKey<String>(+ 'desktop-sidebar-reserved-space',+ );++ final bool pinned;+ final bool canPin;+ final ValueChanged<bool> onPinnedChanged;+ final DesktopSidebarBuilder sidebarBuilder;+ final Widget child;++ @override+ Widget build(BuildContext context) {+ final reservedWidth = pinned+ ? DesktopCollapsibleSidebar.expandedWidth+ : DesktopCollapsibleSidebar.collapsedWidth;++ return Stack(+ children: [+ Row(+ children: [+ AnimatedContainer(+ key: reservedSpaceKey,+ width: reservedWidth,+ duration: const Duration(milliseconds: 160),+ curve: Curves.easeOutCubic,+ ),+ Expanded(child: child),+ ],+ ),+ Positioned(+ left: 0,+ top: 0,+ bottom: 0,+ child: DesktopCollapsibleSidebar(+ pinned: pinned,+ canPin: canPin,+ onPinnedChanged: onPinnedChanged,+ builder: sidebarBuilder,+ ),+ ),+ ],+ );+ }+}++class DesktopCollapsibleSidebar extends StatefulWidget {+ const DesktopCollapsibleSidebar({+ super.key,+ required this.pinned,+ required this.onPinnedChanged,+ required this.builder,+ this.canPin = true,+ this.pinTooltip = 'Keep sidebar expanded',+ this.unpinTooltip = 'Unpin sidebar',+ });++ static const panelKey = ValueKey<String>('desktop-collapsible-sidebar');+ static const pinButtonKey = ValueKey<String>('desktop-sidebar-pin-button');+ static const double collapsedWidth = 72;+ static const double expandedWidth = 248;++ final bool pinned;+ final ValueChanged<bool> onPinnedChanged;+ final DesktopSidebarBuilder builder;+ final bool canPin;+ final String pinTooltip;+ final String unpinTooltip;++ @override+ State<DesktopCollapsibleSidebar> createState() =>+ _DesktopCollapsibleSidebarState();+}++class _DesktopCollapsibleSidebarState extends State<DesktopCollapsibleSidebar> {+ bool _hovering = false;+ bool _focusWithin = false;+ Timer? _collapseTimer;++ void _showForPointer() {+ _collapseTimer?.cancel();+ if (!_hovering) setState(() => _hovering = true);+ }++ void _schedulePointerCollapse() {+ _collapseTimer?.cancel();+ _collapseTimer = Timer(const Duration(milliseconds: 120), () {+ if (mounted && _hovering) setState(() => _hovering = false);+ });+ }++ @override+ void dispose() {+ _collapseTimer?.cancel();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final theme = Theme.of(context);+ final cs = theme.colorScheme;+ final extended = widget.pinned || _hovering || _focusWithin;+ final width = extended+ ? DesktopCollapsibleSidebar.expandedWidth+ : DesktopCollapsibleSidebar.collapsedWidth;++ return Focus(+ canRequestFocus: false,+ onFocusChange: (focused) {+ if (focused != _focusWithin) setState(() => _focusWithin = focused);+ },+ onKeyEvent: (_, event) {+ if (!widget.pinned &&+ event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape) {+ FocusManager.instance.primaryFocus?.unfocus();+ if (_focusWithin) setState(() => _focusWithin = false);+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: MouseRegion(+ onEnter: (_) => _showForPointer(),+ onExit: (_) => _schedulePointerCollapse(),+ child: AnimatedContainer(+ key: DesktopCollapsibleSidebar.panelKey,+ width: width,+ duration: const Duration(milliseconds: 160),+ curve: Curves.easeOutCubic,+ clipBehavior: Clip.hardEdge,+ decoration: BoxDecoration(+ color: theme.scaffoldBackgroundColor,+ border: Border(+ right: BorderSide(+ color: cs.outlineVariant.withValues(alpha: 0.45),+ ),+ ),+ boxShadow: extended && !widget.pinned+ ? [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.18),+ blurRadius: 18,+ offset: const Offset(6, 0),+ ),+ ]+ : null,+ ),+ child: OverflowBox(+ alignment: Alignment.topLeft,+ minWidth: width,+ maxWidth: width,+ child: SizedBox(+ width: width,+ child: Stack(+ fit: StackFit.expand,+ children: [+ widget.builder(context, extended),+ if (extended && widget.canPin)+ Positioned(+ top: 14,+ right: 8,+ child: Tooltip(+ message: widget.pinned+ ? widget.unpinTooltip+ : widget.pinTooltip,+ child: IconButton(+ key: DesktopCollapsibleSidebar.pinButtonKey,+ onPressed: () =>+ widget.onPinnedChanged(!widget.pinned),+ icon: Icon(+ widget.pinned+ ? Icons.keyboard_double_arrow_left_rounded+ : Icons.push_pin_outlined,+ size: 20,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --cc lib/widgets/desktop_cover_size_control.dartindex 00000000,00000000..3cc25bcanew file mode 100644--- /dev/null+++ b/lib/widgets/desktop_cover_size_control.dart@@@ -1,0 -1,0 +1,72 @@@++import 'package:flutter/material.dart';++++class DesktopCoverSizeControl extends StatelessWidget {++ final int value;++ final int minimum;++ final int maximum;++ final VoidCallback? onDecrease;++ final VoidCallback? onIncrease;++++ const DesktopCoverSizeControl({++ super.key,++ required this.value,++ required this.onDecrease,++ required this.onIncrease,++ this.minimum = 60,++ this.maximum = 220,++ });++++ @override++ Widget build(BuildContext context) {++ final cs = Theme.of(context).colorScheme;++ final canDecrease = value > minimum && onDecrease != null;++ final canIncrease = value < maximum && onIncrease != null;++++ return Semantics(++ container: true,++ label: 'Cover size',++ value: '$value',++ child: Material(++ elevation: 6,++ shadowColor: Colors.black.withValues(alpha: 0.28),++ color: cs.surfaceContainerHigh.withValues(alpha: 0.96),++ shape: StadiumBorder(++ side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.55)),++ ),++ clipBehavior: Clip.antiAlias,++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ IconButton(++ onPressed: canDecrease ? onDecrease : null,++ tooltip: 'Decrease cover size',++ icon: const Icon(Icons.remove_rounded),++ iconSize: 20,++ visualDensity: VisualDensity.compact,++ ),++ Semantics(++ excludeSemantics: true,++ child: SizedBox(++ width: 42,++ child: Text(++ '$value',++ textAlign: TextAlign.center,++ style: Theme.of(++ context,++ ).textTheme.labelLarge?.copyWith(fontWeight: FontWeight.w700),++ ),++ ),++ ),++ IconButton(++ onPressed: canIncrease ? onIncrease : null,++ tooltip: 'Increase cover size',++ icon: const Icon(Icons.add_rounded),++ iconSize: 20,++ visualDensity: VisualDensity.compact,++ ),++ ],++ ),++ ),++ );++ }++}diff --cc lib/widgets/episode_list_sheet.dartindex 6182676a,d3108054..4559c674--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@@ -602,12 -601,19 +607,19 @@@ class _EpisodeListSheetState extends Stvoid _showNewEpisodePositionPicker() {final l = AppLocalizations.of(context)!;final cs = Theme.of(context).colorScheme;- final options = <String, String>{- 'start': l.episodeListPositionTop,- 'second': l.episodeListPositionSecond,- 'end': l.episodeListPositionEnd,+ // 'none' keeps everything else about the subscription - new-episode+ // detection, the notification, the download - and only skips the queue,+ // for people subscribed to enough shows that it buries the rest.+ final options = <String, ({String title, String? subtitle})>{+ 'start': (title: l.episodeListPositionTop, subtitle: null),+ 'second': (title: l.episodeListPositionSecond, subtitle: null),+ 'end': (title: l.episodeListPositionEnd, subtitle: null),+ 'none': (+ title: l.episodeListPositionNone,+ subtitle: l.episodeListPositionNoneDesc+ ),};- showModalBottomSheet(+ showAdaptiveActionMenu(context: context,backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,shape: const RoundedRectangleBorder(diff --cc lib/widgets/home_section.dartindex f0c6197e,c7e85ee4..23eab461--- a/lib/widgets/home_section.dart+++ b/lib/widgets/home_section.dart@@@ -22,6 -18,6 +22,10 @@@ class HomeSection extends StatelessWidgfinal String sectionId;final VoidCallback? onTitleTap;final double coverAspectRatio;++ final double desktopScale;++ final bool selectionMode;++ final Set<String> selectedItemIds;++ final ValueChanged<Map<String, dynamic>>? onSelectionToggle;const HomeSection({super.key,@@@ -32,6 -28,6 +36,10 @@@required this.sectionId,this.onTitleTap,this.coverAspectRatio = 1.0,++ this.desktopScale = 1.2,++ this.selectionMode = false,++ this.selectedItemIds = const {},++ this.onSelectionToggle,});@override@@@ -56,18 -52,16 +64,25 @@@: _collectionNameFromTitle(title);// Check if any entities have recentEpisode (podcast episode sections)-- final hasEpisodeEntities = !isEpisodeSection && entities.isNotEmpty &&++ final hasEpisodeEntities =++ !isEpisodeSection &&++ entities.isNotEmpty &&entities.first is Map<String, dynamic> &&(entities.first as Map<String, dynamic>)['recentEpisode'] != null;final effectiveEpisode = isEpisodeSection || hasEpisodeEntities;final bool isRectCover = coverAspectRatio < 1.0;+ final desktop = isDesktopWorkspace(context);- final scale = desktop ? 1.2 : 1.0;++ final scale = desktop ? desktopScale : 1.0;final double cardWidth =- isContinueListening ? 300 : (isAuthorSection ? 120 : 140);+ (isContinueListening ? 300 : (isAuthorSection ? 120 : 140)) * scale;final double cardHeight =- (isContinueListening ? 120 : effectiveEpisode ? 200 : (isAuthorSection ? 170 : (isRectCover ? 260 : 200))) * scale;- isContinueListening ? 120 : effectiveEpisode ? 200 : (isAuthorSection ? 170 : (isRectCover ? 260 : 200));++ (isContinueListening++ ? 120++ : effectiveEpisode++ ? 200++ : (isAuthorSection ? 170 : (isRectCover ? 260 : 200))) *++ scale;return Padding(padding: const EdgeInsets.only(top: 24),@@@ -77,12 -71,12 +92,18 @@@// Section headerGestureDetector(onTap: onTitleTap,-- behavior: onTitleTap != null ? HitTestBehavior.opaque : HitTestBehavior.deferToChild,++ behavior: onTitleTap != null++ ? HitTestBehavior.opaque++ : HitTestBehavior.deferToChild,child: Padding(padding: const EdgeInsets.symmetric(horizontal: 20),child: Row(children: [-- Icon(icon, size: 16, color: cs.primary.withValues(alpha: 0.7)),++ Icon(++ icon,++ size: 16,++ color: cs.primary.withValues(alpha: 0.7),++ ),const SizedBox(width: 8),Text(title,@@@ -94,8 -88,8 +115,11 @@@),if (onTitleTap != null) ...[const SizedBox(width: 4),-- Icon(Icons.chevron_right_rounded, size: 16,-- color: cs.onSurfaceVariant.withValues(alpha: 0.4)),++ Icon(++ Icons.chevron_right_rounded,++ size: 16,++ color: cs.onSurfaceVariant.withValues(alpha: 0.4),++ ),],const SizedBox(width: 12),Expanded(@@@ -145,7 -138,7 +169,10 @@@if (isSeriesSection) {return SizedBox(width: cardWidth,-- child: SeriesCard(series: entity, coverAspectRatio: coverAspectRatio),++ child: SeriesCard(++ series: entity,++ coverAspectRatio: coverAspectRatio,++ ),);}@@@ -179,11 -172,11 +206,23 @@@item: entity,showProgress: isContinueListening,isWide: isContinueListening,-- coverAspectRatio: isContinueListening ? 1.0 : coverAspectRatio,++ coverAspectRatio: isContinueListening++ ? 1.0++ : coverAspectRatio,sourcePlaylistId: sourcePlaylistId,sourcePlaylistEpisodeId: sourcePlaylistEpisodeId,sourceCollectionId: sourceCollectionId,sourceCollectionName: sourceCollectionName,++ selectionMode: selectionMode,++ selected:++ entity is Map<String, dynamic> &&++ selectedItemIds.contains(entity['id'] as String?),++ onSelectionToggle:++ entity is Map<String, dynamic> &&++ entity['id'] is String &&++ onSelectionToggle != null++ ? () => onSelectionToggle!(entity)++ : null,),);},@@@ -248,83 -231,11 +287,103 @@@ class SnapScrollListState extends Statesuper.dispose();}++ @override++ void didUpdateWidget(covariant SnapScrollList oldWidget) {++ super.didUpdateWidget(oldWidget);++ if (oldWidget.cardWidth == widget.cardWidth || !_controller.hasClients) {++ return;++ }++ final oldExtent = oldWidget.cardWidth + 12;++ final itemIndex = oldExtent <= 0 ? 0.0 : _controller.offset / oldExtent;++ WidgetsBinding.instance.addPostFrameCallback((_) {++ if (!mounted || !_controller.hasClients) return;++ final nextOffset = (itemIndex * _itemExtent).clamp(++ 0.0,++ _controller.position.maxScrollExtent,++ );++ _controller.jumpTo(nextOffset);++ _updateArrows();++ });++ }+++ void _updateArrows() {+ if (!widget.desktop || !_controller.hasClients) return;+ final canBack = _controller.offset > 1;+ final canForward =+ _controller.offset < _controller.position.maxScrollExtent - 1;+ if (canBack != _canPageBack || canForward != _canPageForward) {+ setState(() {+ _canPageBack = canBack;+ _canPageForward = canForward;+ });+ }+ }++ void _page(int direction) {+ if (!_controller.hasClients) return;+ final viewport = _controller.position.viewportDimension;+ final cardsPerPage = (viewport ~/ _itemExtent).clamp(1, 50);+ final step = cardsPerPage * _itemExtent;+ final raw = _controller.offset + direction * step;+ final maxExtent = _controller.position.maxScrollExtent;- var target = ((raw / _itemExtent).round() * _itemExtent)- .clamp(0.0, maxExtent);++ var target = ((raw / _itemExtent).round() * _itemExtent).clamp(++ 0.0,++ maxExtent,++ );+ if (target > maxExtent - _itemExtent) {+ target = direction > 0 ? maxExtent : target;+ }+ _controller.animateTo(+ target,+ duration: const Duration(milliseconds: 300),+ curve: Curves.easeOutCubic,+ );+ }++ Widget _arrow({required bool forward}) {+ final cs = Theme.of(context).colorScheme;- final visible =- _hovering && (forward ? _canPageForward : _canPageBack);++ final visible = _hovering && (forward ? _canPageForward : _canPageBack);+ return Positioned(+ left: forward ? null : 4,+ right: forward ? 4 : null,+ top: 0,+ bottom: 0,+ child: Center(+ child: AnimatedOpacity(+ opacity: visible ? 1 : 0,+ duration: const Duration(milliseconds: 120),+ child: IgnorePointer(+ ignoring: !visible,+ child: Material(+ color: cs.surfaceContainerHighest.withValues(alpha: 0.9),+ shape: const CircleBorder(),+ elevation: 2,+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => _page(forward ? 1 : -1),+ child: Padding(+ padding: const EdgeInsets.all(8),+ child: Icon(+ forward+ ? Icons.chevron_right_rounded+ : Icons.chevron_left_rounded,+ size: 24,+ color: cs.onSurface,+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+@overrideWidget build(BuildContext context) {- final itemExtent = widget.cardWidth + 12;+ final itemExtent = _itemExtent;- return NotificationListener<ScrollEndNotification>(+ final list = NotificationListener<ScrollEndNotification>(onNotification: (notification) {final maxExtent = _controller.position.maxScrollExtent;final offset = _controller.offset;@@@ -368,27 -277,6 +427,23 @@@itemBuilder: widget.itemBuilder,),);++ if (!widget.desktop) return list;+ // Arrow visibility depends on maxScrollExtent, which only exists after+ // the first layout; refresh once attached.+ if (!_controller.hasClients) {+ WidgetsBinding.instance.addPostFrameCallback((_) => _updateArrows());+ }+ return MouseRegion(+ onEnter: (_) {+ setState(() => _hovering = true);+ _updateArrows();+ },+ onExit: (_) => setState(() => _hovering = false),+ child: Stack(- children: [- list,- _arrow(forward: false),- _arrow(forward: true),- ],++ children: [list, _arrow(forward: false), _arrow(forward: true)],+ ),+ );}}@@@ -398,10 -286,10 +453,7 @@@ class _EpisodeCard extends StatelessWidfinal Map<String, dynamic> item;final String? sourcePlaylistId;-- const _EpisodeCard({-- required this.item,-- this.sourcePlaylistId,-- });++ const _EpisodeCard({required this.item, this.sourcePlaylistId});@overrideWidget build(BuildContext context) {@@@ -421,160 -308,150 +473,207 @@@final episode = item['recentEpisode'] as Map<String, dynamic>?;final episodeTitle = episode?['title'] as String? ?? showTitle;final episodeId = episode?['id'] as String?;-- final progress = episodeId != null ? lib.getEpisodeProgress(itemId, episodeId) : 0.0;-- final isFinished = episodeId != null && lib.getEpisodeProgressData(itemId, episodeId)?['isFinished'] == true;-- final isDownloaded = episodeId != null && DownloadService().isDownloaded('$itemId-$episodeId');-- return GestureDetector(- onTap: () {- if (episode != null) {- EpisodeDetailSheet.show(- context,- item,- episode,- sourcePlaylistId: sourcePlaylistId,- );- } else {- EpisodeListSheet.show(- context,- item,- sourcePlaylistId: sourcePlaylistId,- );- }- },- // Long-press an episode card for its quick-actions sheet (shows stay as-is).- onLongPress: episode == null ? null++ final progress = episodeId != null++ ? lib.getEpisodeProgress(itemId, episodeId)++ : 0.0;++ final isFinished =++ episodeId != null &&++ lib.getEpisodeProgressData(itemId, episodeId)?['isFinished'] == true;++ final isDownloaded =++ episodeId != null &&++ DownloadService().isDownloaded('$itemId-$episodeId');++ return HoverCoverActions(+ onMenu: episode == null+ ? null: () => EpisodeDetailSheet.showQuick(- context,- item,- episode,- sourcePlaylistId: sourcePlaylistId,- ),++ context,++ item,++ episode,++ sourcePlaylistId: sourcePlaylistId,++ ),+ child: GestureDetector(- onTap: () {- if (episode != null) {- EpisodeDetailSheet.show(- context,- item,- episode,- sourcePlaylistId: sourcePlaylistId,- );- } else {- EpisodeListSheet.show(- context,- item,- sourcePlaylistId: sourcePlaylistId,- );- }- },- // Long-press an episode card for its quick-actions sheet (shows stay as-is).- onLongPress: episode == null || !gesturePolicy.allowsLongPressShortcuts ? null- : () => EpisodeDetailSheet.showQuick(++ onTap: () {++ if (episode != null) {++ EpisodeDetailSheet.show(++ context,++ item,++ episode,++ sourcePlaylistId: sourcePlaylistId,++ );++ } else {++ EpisodeListSheet.show(++ context,++ item,++ sourcePlaylistId: sourcePlaylistId,++ );++ }++ },++ // Long-press an episode card for its quick-actions sheet (shows stay as-is).++ onLongPress: episode == null || !gesturePolicy.allowsLongPressShortcuts++ ? null++ : () => EpisodeDetailSheet.showQuick(context,item,episode,sourcePlaylistId: sourcePlaylistId,),-- child: Column(-- crossAxisAlignment: CrossAxisAlignment.start,-- mainAxisSize: MainAxisSize.min,-- children: [-- // Square cover-- AspectRatio(-- aspectRatio: 1,-- child: Card(-- elevation: 0,-- margin: EdgeInsets.zero,-- color: cs.surfaceContainerHigh,-- shape: RoundedRectangleBorder(-- borderRadius: BorderRadius.circular(12),-- ),-- clipBehavior: Clip.antiAlias,-- child: Stack(-- fit: StackFit.expand,-- children: [-- if (coverUrl != null)-- coverUrl.startsWith('/')-- ? BlurPaddedCover(-- blurChild: Image.file(File(coverUrl), fit: BoxFit.cover,-- errorBuilder: (_, __, ___) => const SizedBox.shrink()),-- child: Image.file(File(coverUrl), fit: BoxFit.contain,++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ mainAxisSize: MainAxisSize.min,++ children: [++ // Square cover++ AspectRatio(++ aspectRatio: 1,++ child: Card(++ elevation: 0,++ margin: EdgeInsets.zero,++ color: cs.surfaceContainerHigh,++ shape: RoundedRectangleBorder(++ borderRadius: BorderRadius.circular(12),++ ),++ clipBehavior: Clip.antiAlias,++ child: Stack(++ fit: StackFit.expand,++ children: [++ if (coverUrl != null)++ coverUrl.startsWith('/')++ ? BlurPaddedCover(++ blurChild: Image.file(++ File(coverUrl),++ fit: BoxFit.cover,++ errorBuilder: (_, __, ___) =>++ const SizedBox.shrink(),++ ),++ child: Image.file(++ File(coverUrl),++ fit: BoxFit.contain,errorBuilder: (_, __, ___) => Container(color: cs.surfaceContainerHigh,-- child: Icon(Icons.podcasts_rounded, size: 32,-- color: cs.onSurfaceVariant.withValues(alpha: 0.3)))))-- : BlurPaddedCover(-- blurChild: Image.network(coverUrl, fit: BoxFit.cover,++ child: Icon(++ Icons.podcasts_rounded,++ size: 32,++ color: cs.onSurfaceVariant.withValues(++ alpha: 0.3,++ ),++ ),++ ),++ ),++ )++ : BlurPaddedCover(++ blurChild: Image.network(++ coverUrl,++ fit: BoxFit.cover,headers: lib.mediaHeaders,-- errorBuilder: (_, __, ___) => const SizedBox.shrink()),-- child: Image.network(coverUrl, fit: BoxFit.contain,++ errorBuilder: (_, __, ___) =>++ const SizedBox.shrink(),++ ),++ child: Image.network(++ coverUrl,++ fit: BoxFit.contain,headers: lib.mediaHeaders,errorBuilder: (_, __, ___) => Container(color: cs.surfaceContainerHigh,-- child: Icon(Icons.podcasts_rounded, size: 32,-- color: cs.onSurfaceVariant.withValues(alpha: 0.3)))))-- else-- Container(-- color: cs.surfaceContainerHigh,-- child: Icon(Icons.podcasts_rounded, size: 32,-- color: cs.onSurfaceVariant.withValues(alpha: 0.3)),-- ),-- // Progress bar-- if (progress > 0 && !isFinished)-- Positioned(-- left: 0, right: 0, bottom: 0,-- child: ClipRRect(-- borderRadius: const BorderRadius.vertical(bottom: Radius.circular(12)),-- child: LinearProgressIndicator(-- value: progress.clamp(0, 1),-- minHeight: 3,-- backgroundColor: Colors.transparent,-- valueColor: AlwaysStoppedAnimation(cs.primary),++ child: Icon(++ Icons.podcasts_rounded,++ size: 32,++ color: cs.onSurfaceVariant.withValues(++ alpha: 0.3,++ ),++ ),++ ),++ ),++ )++ else++ Container(++ color: cs.surfaceContainerHigh,++ child: Icon(++ Icons.podcasts_rounded,++ size: 32,++ color: cs.onSurfaceVariant.withValues(alpha: 0.3),),),-- ),-- // Finished / downloaded badge-- if (isFinished || isDownloaded)-- Positioned(-- left: 0, right: 0, bottom: 0,-- child: CoverStateBadges(-- isDownloaded: isDownloaded,-- isFinished: isFinished,-- borderRadius: const BorderRadius.vertical(bottom: Radius.circular(12)),++ // Progress bar++ if (progress > 0 && !isFinished)++ Positioned(++ left: 0,++ right: 0,++ bottom: 0,++ child: ClipRRect(++ borderRadius: const BorderRadius.vertical(++ bottom: Radius.circular(12),++ ),++ child: LinearProgressIndicator(++ value: progress.clamp(0, 1),++ minHeight: 3,++ backgroundColor: Colors.transparent,++ valueColor: AlwaysStoppedAnimation(cs.primary),++ ),++ ),),-- ),-- // Subscribed bell-- if (isSubscribed)-- Positioned(-- top: 4,-- right: 4,-- child: Container(-- padding: const EdgeInsets.all(3),-- decoration: BoxDecoration(-- color: Colors.black.withValues(alpha: 0.6),-- shape: BoxShape.circle,++ // Finished / downloaded badge++ if (isFinished || isDownloaded)++ Positioned(++ left: 0,++ right: 0,++ bottom: 0,++ child: CoverStateBadges(++ isDownloaded: isDownloaded,++ isFinished: isFinished,++ borderRadius: const BorderRadius.vertical(++ bottom: Radius.circular(12),++ ),),-- child: const Icon(Icons.notifications_rounded,-- size: 11, color: Colors.white),),-- ),-- ],-- ),-- ),-- ),-- const SizedBox(height: 6),-- // Episode title-- Padding(-- padding: const EdgeInsets.symmetric(horizontal: 2),-- child: Text(-- episodeTitle,-- maxLines: 2,-- overflow: TextOverflow.ellipsis,-- style: tt.labelMedium?.copyWith(-- fontWeight: FontWeight.w500,-- color: cs.onSurface,++ // Subscribed bell++ if (isSubscribed)++ Positioned(++ top: 4,++ right: 4,++ child: Container(++ padding: const EdgeInsets.all(3),++ decoration: BoxDecoration(++ color: Colors.black.withValues(alpha: 0.6),++ shape: BoxShape.circle,++ ),++ child: const Icon(++ Icons.notifications_rounded,++ size: 11,++ color: Colors.white,++ ),++ ),++ ),++ ],++ ),),),-- ),-- // Show name-- if (showTitle.isNotEmpty && episode != null)++ const SizedBox(height: 6),++ // Episode titlePadding(padding: const EdgeInsets.symmetric(horizontal: 2),child: Text(-- showTitle,-- maxLines: 1,++ episodeTitle,++ maxLines: 2,overflow: TextOverflow.ellipsis,-- style: tt.labelSmall?.copyWith(-- color: cs.onSurfaceVariant,++ style: tt.labelMedium?.copyWith(++ fontWeight: FontWeight.w500,++ color: cs.onSurface,),),),-- ],- ),++ // Show name++ if (showTitle.isNotEmpty && episode != null)++ Padding(++ padding: const EdgeInsets.symmetric(horizontal: 2),++ child: Text(++ showTitle,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),++ ),++ ),++ ],++ ),),);}diff --cc lib/widgets/hover_cover_actions.dartindex aabeb931,00000000..fc4e6814mode 100644,000000..100644--- a/lib/widgets/hover_cover_actions.dart+++ b/lib/widgets/hover_cover_actions.dart@@@ -1,146 -1,0 +1,191 @@@+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';+import '../l10n/app_localizations.dart';+import '../providers/auth_provider.dart';+import '../screens/book_edit_screen.dart';+import '../utils/desktop_workspace.dart';++/// Desktop hover overlay for book/episode covers: a 3-dot menu opening the+/// item's quick actions and, when permitted, an edit shortcut into the book+/// editor. Returns the child untouched off the desktop workspace, so mobile+/// tiles are unaffected.+class HoverCoverActions extends StatefulWidget {+ final Widget child;+ final VoidCallback? onMenu;++ final bool selectionMode;++ final bool selected;++ final VoidCallback? onSelectionToggle;++ /// Item id to open in the book editor; null hides the edit shortcut.+ /// Callers gate this on `auth.canUpdateMetadata && !lib.isOffline`.+ final String? editItemId;++ const HoverCoverActions({+ super.key,+ required this.child,+ this.onMenu,+ this.editItemId,++ this.selectionMode = false,++ this.selected = false,++ this.onSelectionToggle,+ });++ @override+ State<HoverCoverActions> createState() => _HoverCoverActionsState();+}++class _HoverCoverActionsState extends State<HoverCoverActions> {+ bool _hovering = false;+ bool _loadingEditor = false;++ Future<void> _openEditor() async {+ final itemId = widget.editItemId;+ if (itemId == null || _loadingEditor) return;+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (api == null) return;+ setState(() => _loadingEditor = true);+ final item = await api.getLibraryItem(itemId);+ if (!mounted) return;+ setState(() => _loadingEditor = false);+ if (item == null) return;+ final media = item['media'] as Map<String, dynamic>? ?? {};+ final meta = media['metadata'] as Map<String, dynamic>? ?? {};+ final tags = ((media['tags'] as List<dynamic>?) ?? const []).cast<String>();+ final audioFiles = (media['audioFiles'] as List<dynamic>?) ?? const [];+ final libraryFiles = (item['libraryFiles'] as List<dynamic>?) ?? const [];- contentNavigator(context).push(MaterialPageRoute(- builder: (_) => BookEditScreen(- itemId: itemId,- bookTitle: meta['title'] as String? ?? '',- metadata: meta,- tags: tags,- audioFiles: audioFiles,- libraryFiles: libraryFiles,- relPath: item['relPath'] as String? ?? '',- isEbookOnly: audioFiles.isEmpty && media['ebookFile'] != null,- isAdmin: auth.isAdmin,- libraryId: item['libraryId'] as String?,++ contentNavigator(context).push(++ MaterialPageRoute(++ builder: (_) => BookEditScreen(++ itemId: itemId,++ bookTitle: meta['title'] as String? ?? '',++ metadata: meta,++ tags: tags,++ audioFiles: audioFiles,++ libraryFiles: libraryFiles,++ relPath: item['relPath'] as String? ?? '',++ isEbookOnly: audioFiles.isEmpty && media['ebookFile'] != null,++ isAdmin: auth.isAdmin,++ libraryId: item['libraryId'] as String?,++ ),+ ),- ));++ );+ }++ Widget _actionButton({+ required IconData icon,+ required String tooltip,+ required VoidCallback onTap,+ bool busy = false,+ }) {+ return Tooltip(+ message: tooltip,+ child: Material(+ color: Colors.black.withValues(alpha: 0.6),+ shape: const CircleBorder(),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onTap,+ child: Padding(+ padding: const EdgeInsets.all(6),+ child: busy+ ? const SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(- strokeWidth: 2, color: Colors.white),++ strokeWidth: 2,++ color: Colors.white,++ ),+ )+ : Icon(icon, size: 16, color: Colors.white),+ ),+ ),+ ),+ );+ }++ @override+ Widget build(BuildContext context) {+ if (!isDesktopWorkspace(context)) return widget.child;- if (widget.onMenu == null && widget.editItemId == null) {++ if (widget.onMenu == null &&++ widget.editItemId == null &&++ widget.onSelectionToggle == null) {+ return widget.child;+ }+ final l = AppLocalizations.of(context)!;++ final cs = Theme.of(context).colorScheme;++ final showSelection = widget.selectionMode || widget.selected;+ return MouseRegion(+ onEnter: (_) => setState(() => _hovering = true),+ onExit: (_) => setState(() => _hovering = false),+ child: Stack(+ fit: StackFit.passthrough,+ children: [+ widget.child,++ if (widget.selected)++ Positioned.fill(++ child: IgnorePointer(++ child: DecoratedBox(++ decoration: BoxDecoration(++ borderRadius: BorderRadius.circular(12),++ border: Border.all(color: cs.primary, width: 3),++ color: cs.primary.withValues(alpha: 0.08),++ ),++ ),++ ),++ ),++ if (widget.onSelectionToggle != null)++ Positioned(++ top: 4,++ left: 4,++ child: AnimatedOpacity(++ opacity: _hovering || showSelection ? 1 : 0,++ duration: const Duration(milliseconds: 120),++ child: IgnorePointer(++ ignoring: !_hovering && !showSelection,++ child: _actionButton(++ icon: widget.selected++ ? Icons.check_circle_rounded++ : Icons.radio_button_unchecked_rounded,++ tooltip: widget.selected ? 'Deselect' : 'Select',++ onTap: widget.onSelectionToggle!,++ ),++ ),++ ),++ ),+ Positioned(+ top: 4,+ right: 4,+ child: AnimatedOpacity(- opacity: _hovering ? 1 : 0,++ opacity: _hovering && !widget.selectionMode ? 1 : 0,+ duration: const Duration(milliseconds: 120),+ child: IgnorePointer(- ignoring: !_hovering,++ ignoring: !_hovering || widget.selectionMode,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (widget.editItemId != null) ...[+ _actionButton(+ icon: Icons.edit_rounded,+ tooltip: l.edit,+ onTap: _openEditor,+ busy: _loadingEditor,+ ),+ const SizedBox(width: 4),+ ],+ if (widget.onMenu != null)+ _actionButton(+ icon: Icons.more_horiz_rounded,+ tooltip: l.moreActions,+ onTap: widget.onMenu!,+ ),+ ],+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --cc lib/widgets/library_authors_tab.dartindex d5153f10,8d6a2de9..14af7ea0--- a/lib/widgets/library_authors_tab.dart+++ b/lib/widgets/library_authors_tab.dart@@@ -8,6 -7,6 +8,7 @@@ class LibraryAuthorsTab extends Statelefinal List<Map<String, dynamic>> authors;final bool isLoadingAuthors;final bool authorsLoaded;++ final double desktopMaxCrossAxisExtent;final Future<void> Function() onRefresh;final Widget? headerSliver;final ScrollController? scrollController;@@@ -17,6 -16,6 +18,7 @@@required this.authors,required this.isLoadingAuthors,required this.authorsLoaded,++ this.desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,required this.onRefresh,this.headerSliver,this.scrollController,@@@ -55,11 -54,11 +57,16 @@@child: Column(mainAxisSize: MainAxisSize.min,children: [-- Icon(Icons.people_outline_rounded,-- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),++ Icon(++ Icons.people_outline_rounded,++ size: 56,++ color: cs.onSurfaceVariant.withValues(alpha: 0.3),++ ),const SizedBox(height: 12),-- Text(l.libraryNoAuthorsFound,-- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),++ Text(++ l.libraryNoAuthorsFound,++ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant),++ ),],),),@@@ -73,11 -72,13 +80,17 @@@slivers: [...headers,SliverPadding(- padding: EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding(context)),- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),++ padding: EdgeInsets.fromLTRB(++ 16,++ 8,++ 16,++ libraryGridBottomPadding(context),++ ),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: responsiveGridCount(context),+ gridDelegate: libraryGridDelegate(+ context,childAspectRatio: 0.68,- crossAxisSpacing: 10,- mainAxisSpacing: 10,++ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,),delegate: SliverChildBuilderDelegate((context, index) => GridAuthorTile(author: authors[index]),diff --cc lib/widgets/library_books_tab.dartindex 14ba5f0b,6f1661ac..37d86521--- a/lib/widgets/library_books_tab.dart+++ b/lib/widgets/library_books_tab.dart@@@ -14,6 -13,6 +14,10 @@@ class LibraryBooksTab extends Statelessfinal bool isPodcastLibrary;final bool rectangleCovers;final double coverAspectRatio;++ final double desktopMaxCrossAxisExtent;++ final bool selectionMode;++ final Set<String> selectedItemIds;++ final void Function(Map<String, dynamic> item, int index)? onSelectionToggle;final Future<void> Function() onRefresh;final VoidCallback onClearFilter;@@@ -43,6 -42,6 +47,10 @@@this.isPodcastLibrary = false,required this.rectangleCovers,required this.coverAspectRatio,++ this.desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,++ this.selectionMode = false,++ this.selectedItemIds = const {},++ this.onSelectionToggle,required this.onRefresh,required this.onClearFilter,required this.onLoadMore,@@@ -75,35 -74,35 +83,39 @@@final filterMsg = isPodcastLibrary && filter != LibraryFilter.none? l.libraryNoItemsMatchingFilter: switch (filter) {-- LibraryFilter.notFinished => l.libraryNoUnfinishedBooks,-- LibraryFilter.inProgress => l.libraryNoBooksInProgress,-- LibraryFilter.finished => l.libraryNoFinishedBooks,-- LibraryFilter.notStarted => l.libraryAllBooksStarted,-- LibraryFilter.downloaded => l.libraryNoDownloadedBooks,-- LibraryFilter.subscribed => l.libraryNoItemsMatchingFilter,-- LibraryFilter.inASeries => l.libraryNoSeriesFound,-- LibraryFilter.hasEbook => l.libraryNoBooksWithEbooks,-- LibraryFilter.noEbook ||-- LibraryFilter.hasSupplementaryEbook ||-- LibraryFilter.noSupplementaryEbook ||-- LibraryFilter.series ||-- LibraryFilter.author ||-- LibraryFilter.narrator ||-- LibraryFilter.language ||-- LibraryFilter.publisher ||-- LibraryFilter.publishedDecade ||-- LibraryFilter.noTracks ||-- LibraryFilter.singleTrack ||-- LibraryFilter.multipleTracks ||-- LibraryFilter.abridged ||-- LibraryFilter.issues ||-- LibraryFilter.feedOpen ||-- LibraryFilter.explicit => l.libraryNoItemsMatchingFilter,-- LibraryFilter.missingMetadata => l.libraryNoBooksMissingMetadata,-- LibraryFilter.genre => l.libraryNoBooksInGenre(genreFilter ?? l.genre.toLowerCase()),-- LibraryFilter.tag => l.libraryNoBooksWithTag(tagFilter ?? l.tag.toLowerCase()),-- LibraryFilter.none => l.libraryNoBooks,-- };++ LibraryFilter.notFinished => l.libraryNoUnfinishedBooks,++ LibraryFilter.inProgress => l.libraryNoBooksInProgress,++ LibraryFilter.finished => l.libraryNoFinishedBooks,++ LibraryFilter.notStarted => l.libraryAllBooksStarted,++ LibraryFilter.downloaded => l.libraryNoDownloadedBooks,++ LibraryFilter.subscribed => l.libraryNoItemsMatchingFilter,++ LibraryFilter.inASeries => l.libraryNoSeriesFound,++ LibraryFilter.hasEbook => l.libraryNoBooksWithEbooks,++ LibraryFilter.noEbook ||++ LibraryFilter.hasSupplementaryEbook ||++ LibraryFilter.noSupplementaryEbook ||++ LibraryFilter.series ||++ LibraryFilter.author ||++ LibraryFilter.narrator ||++ LibraryFilter.language ||++ LibraryFilter.publisher ||++ LibraryFilter.publishedDecade ||++ LibraryFilter.noTracks ||++ LibraryFilter.singleTrack ||++ LibraryFilter.multipleTracks ||++ LibraryFilter.abridged ||++ LibraryFilter.issues ||++ LibraryFilter.feedOpen ||++ LibraryFilter.explicit => l.libraryNoItemsMatchingFilter,++ LibraryFilter.missingMetadata => l.libraryNoBooksMissingMetadata,++ LibraryFilter.genre => l.libraryNoBooksInGenre(++ genreFilter ?? l.genre.toLowerCase(),++ ),++ LibraryFilter.tag => l.libraryNoBooksWithTag(++ tagFilter ?? l.tag.toLowerCase(),++ ),++ LibraryFilter.none => l.libraryNoBooks,++ };body = CustomScrollView(controller: scrollController,physics: const AlwaysScrollableScrollPhysics(),@@@ -115,17 -114,17 +127,24 @@@child: Column(mainAxisSize: MainAxisSize.min,children: [-- Icon(Icons.library_books_outlined,-- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),++ Icon(++ Icons.library_books_outlined,++ size: 56,++ color: cs.onSurfaceVariant.withValues(alpha: 0.3),++ ),const SizedBox(height: 12),-- Text(filterMsg,-- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),++ Text(++ filterMsg,++ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant),++ ),if (filter != LibraryFilter.none) ...[const SizedBox(height: 8),GestureDetector(onTap: onClearFilter,-- child: Text(l.libraryClearFilter,-- style: tt.bodySmall?.copyWith(color: cs.primary)),++ child: Text(++ l.libraryClearFilter,++ style: tt.bodySmall?.copyWith(color: cs.primary),++ ),),],],@@@ -141,30 -140,32 +160,45 @@@slivers: [...headers,SliverPadding(- padding: EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding(context)),- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),++ padding: EdgeInsets.fromLTRB(++ 16,++ 8,++ 16,++ libraryGridBottomPadding(context),++ ),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: responsiveGridCount(context),+ gridDelegate: libraryGridDelegate(+ context,childAspectRatio: rectangleCovers ? 0.48 : 0.68,- crossAxisSpacing: 10,- mainAxisSpacing: 10,- ),- delegate: SliverChildBuilderDelegate(- (context, index) {- if (index >= items.length) {- return const Center(- child: Padding(- padding: EdgeInsets.all(16),- child: CircularProgressIndicator(strokeWidth: 2),- ),- );- }- final item = items[index];- if (item.containsKey('collapsedSeries')) {- return GridSeriesTile(item: item, coverAspectRatio: coverAspectRatio);- }- return GridBookTile(item: item, coverAspectRatio: coverAspectRatio);- },- childCount: items.length + (hasMore ? 1 : 0),++ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,),- delegate: SliverChildBuilderDelegate(- (context, index) {- if (index >= items.length) {- return const Center(- child: Padding(- padding: EdgeInsets.all(16),- child: CircularProgressIndicator(strokeWidth: 2),- ),- );- }- final item = items[index];- if (item.containsKey('collapsedSeries')) {- return GridSeriesTile(item: item, coverAspectRatio: coverAspectRatio);- }- return GridBookTile(item: item, coverAspectRatio: coverAspectRatio);- },- childCount: items.length + (hasMore ? 1 : 0),- ),++ delegate: SliverChildBuilderDelegate((context, index) {++ if (index >= items.length) {++ return const Center(++ child: Padding(++ padding: EdgeInsets.all(16),++ child: CircularProgressIndicator(strokeWidth: 2),++ ),++ );++ }++ final item = items[index];++ if (item.containsKey('collapsedSeries')) {++ return GridSeriesTile(++ item: item,++ coverAspectRatio: coverAspectRatio,++ );++ }++ final itemId = item['id'] as String?;++ return GridBookTile(++ item: item,++ coverAspectRatio: coverAspectRatio,++ selectionMode: selectionMode,++ selected: itemId != null && selectedItemIds.contains(itemId),++ onSelectionToggle: itemId == null || onSelectionToggle == null++ ? null++ : () => onSelectionToggle!(item, index),++ );++ }, childCount: items.length + (hasMore ? 1 : 0)),),),],diff --cc lib/widgets/library_grid_tiles.dartindex e96870c9,047ff39b..1907100a--- a/lib/widgets/library_grid_tiles.dart+++ b/lib/widgets/library_grid_tiles.dart@@@ -24,8 -21,8 +24,19 @@@ class GridBookTile extends StatefulWidgfinal Map<String, dynamic> item;final double coverAspectRatio;final String? sequenceBadge;++ final bool selectionMode;++ final bool selected;++ final VoidCallback? onSelectionToggle;-- const GridBookTile({super.key, required this.item, this.coverAspectRatio = 1.0, this.sequenceBadge});++ const GridBookTile({++ super.key,++ required this.item,++ this.coverAspectRatio = 1.0,++ this.sequenceBadge,++ this.selectionMode = false,++ this.selected = false,++ this.onSelectionToggle,++ });@overrideState<GridBookTile> createState() => _GridBookTileState();@@@ -65,210 -61,198 +76,293 @@@ class _GridBookTileState extends State<final author = metadata['authorName'] as String? ?? '';final coverUrl = lib.getCoverUrl(itemId);final progress = lib.getProgress(itemId);-- final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;++ final isExplicit =++ PlayerSettings.showExplicitBadge && metadata['explicit'] == true;final isDownloaded = _dl.isDownloaded(itemId);final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;-- final isSubscribed = lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);-- final unfinishedCount =-- lib.isPodcastLibrary ? lib.getUnfinishedEpisodeCount(widget.item) : 0;--- final canEdit = itemId.isNotEmpty &&- return GestureDetector(- // opaque so taps on the blank space below the title (the tile's tall- // aspect ratio leaves a gap when the Column children stop short)- // still trigger the onTap. Without this, taps in that blank strip- // miss the Column's hit test and nothing happens.- behavior: HitTestBehavior.opaque,- onTap: () {- if (itemId.isNotEmpty) {- if (lib.isPodcastLibrary) {- EpisodeListSheet.show(context, widget.item);- } else {- showBookDetailSheet(context, itemId);- }- }- },- // Long-press a book cover for the quick-actions sheet (podcasts skipped).- onLongPress: (itemId.isNotEmpty && !lib.isPodcastLibrary)- ? () => showQuickActionsSheet(context, itemId, initialItem: widget.item)++ final isSubscribed =++ lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);++ final unfinishedCount = lib.isPodcastLibrary++ ? lib.getUnfinishedEpisodeCount(widget.item)++ : 0;++++ final canEdit =++ itemId.isNotEmpty &&+ !lib.isPodcastLibrary &&+ !lib.isOffline &&+ context.watch<AuthProvider>().canUpdateMetadata;+ return HoverCoverActions(- onMenu: (itemId.isNotEmpty && !lib.isPodcastLibrary)- ? () => showQuickActionsSheet(context, itemId, initialItem: widget.item)++ onMenu:++ (!widget.selectionMode && itemId.isNotEmpty && !lib.isPodcastLibrary)++ ? () =>++ showQuickActionsSheet(context, itemId, initialItem: widget.item): null,- editItemId: canEdit ? itemId : null,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- // Cover- AspectRatio(- aspectRatio: widget.coverAspectRatio,- child: ClipRRect(- borderRadius: BorderRadius.circular(10),- child: Stack(- fit: StackFit.expand,- children: [- // Cover image- coverUrl != null- ? _blurCover(coverUrl, lib.mediaHeaders, cs, widget.coverAspectRatio, title, author)- : CoverPlaceholder(title: title, author: author),-- // Progress bar at bottom of cover- if (progress > 0 && !isFinished)- Positioned(- left: 0,- right: 0,- bottom: 0,- child: LinearProgressIndicator(- value: progress.clamp(0.0, 1.0),- minHeight: 3,- backgroundColor: Colors.black38,- valueColor: AlwaysStoppedAnimation(cs.primary),++ editItemId: canEdit && !widget.selectionMode ? itemId : null,++ selectionMode: widget.selectionMode,++ selected: widget.selected,++ onSelectionToggle: widget.onSelectionToggle,+ child: GestureDetector(- // opaque so taps on the blank space below the title (the tile's tall- // aspect ratio leaves a gap when the Column children stop short)- // still trigger the onTap. Without this, taps in that blank strip- // miss the Column's hit test and nothing happens.- behavior: HitTestBehavior.opaque,- onTap: () {- if (itemId.isNotEmpty) {- if (lib.isPodcastLibrary) {- EpisodeListSheet.show(context, widget.item);- } else {- showBookDetailSheet(context, itemId);++ // opaque so taps on the blank space below the title (the tile's tall++ // aspect ratio leaves a gap when the Column children stop short)++ // still trigger the onTap. Without this, taps in that blank strip++ // miss the Column's hit test and nothing happens.++ behavior: HitTestBehavior.opaque,++ onTap: () {++ if (widget.selectionMode && widget.onSelectionToggle != null) {++ widget.onSelectionToggle!();++ return;+ }- }- },- // Long-press a book cover for the quick-actions sheet (podcasts skipped).- onLongPress: (gesturePolicy.allowsLongPressShortcuts &&- itemId.isNotEmpty &&- !lib.isPodcastLibrary)- ? () => showQuickActionsSheet(context, itemId, initialItem: widget.item)- : null,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- // Cover- AspectRatio(- aspectRatio: widget.coverAspectRatio,- child: ClipRRect(- borderRadius: BorderRadius.circular(10),- child: Stack(- fit: StackFit.expand,- children: [- // Cover image- coverUrl != null- ? _blurCover(coverUrl, lib.mediaHeaders, cs, widget.coverAspectRatio, title, author)- : CoverPlaceholder(title: title, author: author),-- // Progress bar at bottom of cover- if (progress > 0 && !isFinished)- Positioned(- left: 0,- right: 0,- bottom: 0,- child: LinearProgressIndicator(- value: progress.clamp(0.0, 1.0),- minHeight: 3,- backgroundColor: Colors.black38,- valueColor: AlwaysStoppedAnimation(cs.primary),++ if (itemId.isNotEmpty) {++ if (lib.isPodcastLibrary) {++ EpisodeListSheet.show(context, widget.item);++ } else {++ showBookDetailSheet(context, itemId);++ }++ }++ },++ // Long-press a book cover for the quick-actions sheet (podcasts skipped).++ onLongPress:++ (!widget.selectionMode &&++ gesturePolicy.allowsLongPressShortcuts &&++ itemId.isNotEmpty &&++ !lib.isPodcastLibrary)++ ? () => showQuickActionsSheet(++ context,++ itemId,++ initialItem: widget.item,++ )++ : null,++ child: Column(++ crossAxisAlignment: CrossAxisAlignment.start,++ children: [++ // Cover++ AspectRatio(++ aspectRatio: widget.coverAspectRatio,++ child: ClipRRect(++ borderRadius: BorderRadius.circular(10),++ child: Stack(++ fit: StackFit.expand,++ children: [++ // Cover image++ coverUrl != null++ ? _blurCover(++ coverUrl,++ lib.mediaHeaders,++ cs,++ widget.coverAspectRatio,++ title,++ author,++ )++ : CoverPlaceholder(title: title, author: author),++++ // Progress bar at bottom of cover++ if (progress > 0 && !isFinished)++ Positioned(++ left: 0,++ right: 0,++ bottom: 0,++ child: LinearProgressIndicator(++ value: progress.clamp(0.0, 1.0),++ minHeight: 3,++ backgroundColor: Colors.black38,++ valueColor: AlwaysStoppedAnimation(cs.primary),++ ),),-- ),-- // Unplayed-episode count badge (podcasts only)-- if (unfinishedCount > 0)-- Positioned(-- top: 4,-- right: 4,-- child: Container(-- padding: const EdgeInsets.symmetric(-- horizontal: 6, vertical: 2),-- decoration: BoxDecoration(-- color: cs.primary,-- borderRadius: BorderRadius.circular(10),-- ),-- child: Text(-- '$unfinishedCount',-- style: TextStyle(-- color: cs.onPrimary,-- fontSize: 10,-- fontWeight: FontWeight.w700,++ // Unplayed-episode count badge (podcasts only)++ if (unfinishedCount > 0)++ Positioned(++ top: 4,++ right: 4,++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 6,++ vertical: 2,++ ),++ decoration: BoxDecoration(++ color: cs.primary,++ borderRadius: BorderRadius.circular(10),++ ),++ child: Text(++ '$unfinishedCount',++ style: TextStyle(++ color: cs.onPrimary,++ fontSize: 10,++ fontWeight: FontWeight.w700,++ ),),),),-- ),-- // Subscribed bell (sits below unplayed badge when both show)-- if (isSubscribed)-- Positioned(-- top: unfinishedCount > 0 ? 26 : 4,-- right: 4,-- child: Container(-- padding: const EdgeInsets.all(3),-- decoration: BoxDecoration(-- color: Colors.black.withValues(alpha: 0.6),-- shape: BoxShape.circle,++ // Subscribed bell (sits below unplayed badge when both show)++ if (isSubscribed)++ Positioned(++ top: unfinishedCount > 0 ? 26 : 4,++ right: 4,++ child: Container(++ padding: const EdgeInsets.all(3),++ decoration: BoxDecoration(++ color: Colors.black.withValues(alpha: 0.6),++ shape: BoxShape.circle,++ ),++ child: const Icon(++ Icons.notifications_rounded,++ size: 11,++ color: Colors.white,++ ),),-- child: const Icon(Icons.notifications_rounded,-- size: 11, color: Colors.white),),-- ),-- // Explicit badge-- if (isExplicit)-- Positioned(-- top: (unfinishedCount > 0 ? 26 : 4) + (isSubscribed ? 22 : 0),-- right: 4,-- child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),-- decoration: BoxDecoration(-- color: Colors.red.withValues(alpha: 0.85),-- borderRadius: BorderRadius.circular(4),++ // Explicit badge++ if (isExplicit)++ Positioned(++ top:++ (unfinishedCount > 0 ? 26 : 4) +++ (isSubscribed ? 22 : 0),++ right: 4,++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 4,++ vertical: 1,++ ),++ decoration: BoxDecoration(++ color: Colors.red.withValues(alpha: 0.85),++ borderRadius: BorderRadius.circular(4),++ ),++ child: Text(++ l.libraryGridTilesExplicitBadge,++ style: const TextStyle(++ color: Colors.white,++ fontSize: 9,++ fontWeight: FontWeight.w800,++ ),++ ),),-- child: Text(l.libraryGridTilesExplicitBadge, style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w800)),),-- ),-- // Sequence badge-- if (widget.sequenceBadge != null)-- Positioned(-- top: 4, left: 4,-- child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),-- decoration: BoxDecoration(-- color: Colors.black.withValues(alpha: 0.7),-- borderRadius: BorderRadius.circular(6),++ // Sequence badge++ if (widget.sequenceBadge != null)++ Positioned(++ top: 4,++ left: 4,++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 5,++ vertical: 2,++ ),++ decoration: BoxDecoration(++ color: Colors.black.withValues(alpha: 0.7),++ borderRadius: BorderRadius.circular(6),++ ),++ child: Text(++ l.libraryGridTilesSequence(widget.sequenceBadge!),++ style: const TextStyle(++ color: Colors.white,++ fontSize: 9,++ fontWeight: FontWeight.w600,++ ),++ ),),-- child: Text(l.libraryGridTilesSequence(widget.sequenceBadge!),-- style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w600)),),-- ),-- // ── State badges (downloaded / finished) ──-- if (isFinished || isDownloaded)-- Positioned(-- left: 0, right: 0, bottom: 0,-- child: CoverStateBadges(-- isDownloaded: isDownloaded,-- isFinished: isFinished,++ // ── State badges (downloaded / finished) ──++ if (isFinished || isDownloaded)++ Positioned(++ left: 0,++ right: 0,++ bottom: 0,++ child: CoverStateBadges(++ isDownloaded: isDownloaded,++ isFinished: isFinished,++ ),),-- ),-- ],++ ],++ ),),),-- ),-- const SizedBox(height: 5),-- // Title-- Text(-- title,-- maxLines: 1,-- overflow: TextOverflow.ellipsis,-- style: tt.labelSmall?.copyWith(-- fontWeight: FontWeight.w600,-- color: cs.onSurface,-- fontSize: 11,-- ),-- ),-- // Author-- if (author.isNotEmpty)++ const SizedBox(height: 5),++ // TitleText(-- author,++ title,maxLines: 1,overflow: TextOverflow.ellipsis,style: tt.labelSmall?.copyWith(-- color: cs.onSurfaceVariant,-- fontSize: 10,++ fontWeight: FontWeight.w600,++ color: cs.onSurface,++ fontSize: 11,),),-- ],- ),++ // Author++ if (author.isNotEmpty)++ Text(++ author,++ maxLines: 1,++ overflow: TextOverflow.ellipsis,++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant,++ fontSize: 10,++ ),++ ),++ ],++ ),),);}-- Widget _blurCover(String coverUrl, Map<String, String> headers, ColorScheme cs, double aspectRatio, String title, String author) {++ Widget _blurCover(++ String coverUrl,++ Map<String, String> headers,++ ColorScheme cs,++ double aspectRatio,++ String title,++ String author,++ ) {final placeholder = CoverPlaceholder(title: title, author: author);final isSquare = (aspectRatio - 1.0).abs() < 0.01;if (!isSquare) {if (coverUrl.startsWith('/')) {-- return Image.file(File(coverUrl), fit: BoxFit.cover,-- errorBuilder: (_, __, ___) => placeholder);++ return Image.file(++ File(coverUrl),++ fit: BoxFit.cover,++ errorBuilder: (_, __, ___) => placeholder,++ );}-- return CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.cover,-- httpHeaders: headers, placeholder: (_, __) => placeholder,-- errorWidget: (_, __, ___) => placeholder);++ return CachedNetworkImage(++ imageUrl: coverUrl,++ fit: BoxFit.cover,++ httpHeaders: headers,++ placeholder: (_, __) => placeholder,++ errorWidget: (_, __, ___) => placeholder,++ );}if (coverUrl.startsWith('/')) {return BlurPaddedCover(-- blurChild: Image.file(File(coverUrl), fit: BoxFit.cover,-- errorBuilder: (_, __ ,___) => const SizedBox.shrink()),-- child: Image.file(File(coverUrl), fit: BoxFit.contain,-- errorBuilder: (_, __, ___) => placeholder),++ blurChild: Image.file(++ File(coverUrl),++ fit: BoxFit.cover,++ errorBuilder: (_, __, ___) => const SizedBox.shrink(),++ ),++ child: Image.file(++ File(coverUrl),++ fit: BoxFit.contain,++ errorBuilder: (_, __, ___) => placeholder,++ ),);}return BlurPaddedCover(-- blurChild: CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.cover,-- httpHeaders: headers, errorWidget: (_, __, ___) => const SizedBox.shrink()),-- child: CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.contain,-- httpHeaders: headers, placeholder: (_, __) => placeholder,-- errorWidget: (_, __, ___) => placeholder),++ blurChild: CachedNetworkImage(++ imageUrl: coverUrl,++ fit: BoxFit.cover,++ httpHeaders: headers,++ errorWidget: (_, __, ___) => const SizedBox.shrink(),++ ),++ child: CachedNetworkImage(++ imageUrl: coverUrl,++ fit: BoxFit.contain,++ httpHeaders: headers,++ placeholder: (_, __) => placeholder,++ errorWidget: (_, __, ___) => placeholder,++ ),);}}@@@ -310,96 -294,96 +404,113 @@@ class _StackedCovers extends StatelessWaspectRatio: coverAspectRatio,child: RepaintBoundary(child: Stack(-- children: [-- // Back covers (furthest back first so front paints on top). Drop-- // the per-back-cover BoxShadow blur — front cover's shadow is-- // enough visual depth and blurred shadows are expensive.-- for (int i = count - 1; i > 0; i--)-- Positioned(-- top: (totalOffset - i * inset),-- right: (totalOffset - i * inset),-- left: i * inset,-- bottom: i * inset,-- child: ClipRRect(-- borderRadius: BorderRadius.circular(10),-- child: _coverImage(coverUrls[i]),-- ),-- ),-- // Front cover (bottom-left)-- Positioned(-- top: totalOffset,-- right: totalOffset,-- left: 0,-- bottom: 0,-- child: DecoratedBox(-- decoration: BoxDecoration(-- borderRadius: BorderRadius.circular(10),-- boxShadow: count > 1-- ? [-- BoxShadow(-- color: Colors.black.withValues(alpha: 0.2),-- blurRadius: 3,-- offset: const Offset(-1, 1),-- ),-- ]-- : [],++ children: [++ // Back covers (furthest back first so front paints on top). Drop++ // the per-back-cover BoxShadow blur — front cover's shadow is++ // enough visual depth and blurred shadows are expensive.++ for (int i = count - 1; i > 0; i--)++ Positioned(++ top: (totalOffset - i * inset),++ right: (totalOffset - i * inset),++ left: i * inset,++ bottom: i * inset,++ child: ClipRRect(++ borderRadius: BorderRadius.circular(10),++ child: _coverImage(coverUrls[i]),++ ),),-- child: ClipRRect(-- borderRadius: BorderRadius.circular(10),-- child: Stack(-- fit: StackFit.expand,-- children: [-- _coverImage(coverUrls.isNotEmpty ? coverUrls[0] : null),-- // Series progress bar-- if (seriesProgress > 0 && booksFinished < numBooks)-- Positioned(-- left: 0,-- right: 0,-- bottom: 0,-- child: LinearProgressIndicator(-- value: seriesProgress.clamp(0.0, 1.0),-- minHeight: 3,-- backgroundColor: Colors.black38,-- valueColor: AlwaysStoppedAnimation(cs.primary),++ // Front cover (bottom-left)++ Positioned(++ top: totalOffset,++ right: totalOffset,++ left: 0,++ bottom: 0,++ child: DecoratedBox(++ decoration: BoxDecoration(++ borderRadius: BorderRadius.circular(10),++ boxShadow: count > 1++ ? [++ BoxShadow(++ color: Colors.black.withValues(alpha: 0.2),++ blurRadius: 3,++ offset: const Offset(-1, 1),++ ),++ ]++ : [],++ ),++ child: ClipRRect(++ borderRadius: BorderRadius.circular(10),++ child: Stack(++ fit: StackFit.expand,++ children: [++ _coverImage(coverUrls.isNotEmpty ? coverUrls[0] : null),++ // Series progress bar++ if (seriesProgress > 0 && booksFinished < numBooks)++ Positioned(++ left: 0,++ right: 0,++ bottom: 0,++ child: LinearProgressIndicator(++ value: seriesProgress.clamp(0.0, 1.0),++ minHeight: 3,++ backgroundColor: Colors.black38,++ valueColor: AlwaysStoppedAnimation(cs.primary),++ ),),-- ),-- // Finished banner-- if (booksFinished > 0 && booksFinished >= numBooks)-- const Positioned(-- left: 0, right: 0, bottom: 0,-- child: CoverStateBadges(isDownloaded: false, isFinished: true),-- ),-- // Book count badge-- Positioned(-- top: 6,-- right: 6,-- child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),-- decoration: BoxDecoration(-- color: cs.primaryContainer,-- borderRadius: BorderRadius.circular(10),++ // Finished banner++ if (booksFinished > 0 && booksFinished >= numBooks)++ const Positioned(++ left: 0,++ right: 0,++ bottom: 0,++ child: CoverStateBadges(++ isDownloaded: false,++ isFinished: true,++ ),),-- child: Row(-- mainAxisSize: MainAxisSize.min,-- children: [-- Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),-- const SizedBox(width: 3),-- Text(booksFinished > 0 && booksFinished < numBooks-- ? '$booksFinished/$numBooks'-- : '$numBooks',-- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,-- color: cs.onPrimaryContainer)),-- ],++ // Book count badge++ Positioned(++ top: 6,++ right: 6,++ child: Container(++ padding: const EdgeInsets.symmetric(++ horizontal: 7,++ vertical: 3,++ ),++ decoration: BoxDecoration(++ color: cs.primaryContainer,++ borderRadius: BorderRadius.circular(10),++ ),++ child: Row(++ mainAxisSize: MainAxisSize.min,++ children: [++ Icon(++ Icons.auto_stories_rounded,++ size: 11,++ color: cs.onPrimaryContainer,++ ),++ const SizedBox(width: 3),++ Text(++ booksFinished > 0 && booksFinished < numBooks++ ? '$booksFinished/$numBooks'++ : '$numBooks',++ style: TextStyle(++ fontSize: 10,++ fontWeight: FontWeight.w700,++ color: cs.onPrimaryContainer,++ ),++ ),++ ],++ ),),),-- ),-- ],++ ],++ ),),),),-- ),-- ],-- ),++ ],++ ),),);}@@@ -408,20 -392,20 +519,30 @@@if (url == null) return _placeholder();// Series stacked covers are always cropped to fit - no blur padding neededif (url.startsWith('/')) {-- return Image.file(File(url), fit: BoxFit.cover,-- errorBuilder: (_, __, ___) => _placeholder());++ return Image.file(++ File(url),++ fit: BoxFit.cover,++ errorBuilder: (_, __, ___) => _placeholder(),++ );}-- return CachedNetworkImage(imageUrl: url, fit: BoxFit.cover,-- httpHeaders: mediaHeaders, placeholder: (_, __) => _placeholder(),-- errorWidget: (_, __, ___) => _placeholder());++ return CachedNetworkImage(++ imageUrl: url,++ fit: BoxFit.cover,++ httpHeaders: mediaHeaders,++ placeholder: (_, __) => _placeholder(),++ errorWidget: (_, __, ___) => _placeholder(),++ );}Widget _placeholder() {return Container(color: cs.surfaceContainerHighest,child: Center(-- child: Icon(Icons.auto_stories_rounded,-- size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),++ child: Icon(++ Icons.auto_stories_rounded,++ size: 24,++ color: cs.onSurfaceVariant.withValues(alpha: 0.3),++ ),),);}@@@ -433,7 -417,7 +554,11 @@@class GridSeriesTile extends StatelessWidget {final Map<String, dynamic> item;final double coverAspectRatio;-- const GridSeriesTile({super.key, required this.item, this.coverAspectRatio = 1.0});++ const GridSeriesTile({++ super.key,++ required this.item,++ this.coverAspectRatio = 1.0,++ });@overrideWidget build(BuildContext context) {@@@ -443,23 -427,23 +568,24 @@@final lib = context.watch<LibraryProvider>();final auth = context.read<AuthProvider>();-- final collapsedSeries = item['collapsedSeries'] as Map<String, dynamic>? ?? {};-- final seriesName = collapsedSeries['name'] as String? ?? l.libraryGridTilesUnknownSeries;++ final collapsedSeries =++ item['collapsedSeries'] as Map<String, dynamic>? ?? {};++ final seriesName =++ collapsedSeries['name'] as String? ?? l.libraryGridTilesUnknownSeries;final seriesId = collapsedSeries['id'] as String? ?? '';final media = item['media'] as Map<String, dynamic>? ?? {};final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final author = metadata['authorName'] as String? ?? '';// Gather up to 4 cover URLs from libraryItemIds-- final itemIds = (collapsedSeries['libraryItemIds'] as List<dynamic>?)-- ?.map((e) => e as String)-- .toList() ?? [item['id'] as String? ?? ''];++ final itemIds =++ (collapsedSeries['libraryItemIds'] as List<dynamic>?)++ ?.map((e) => e as String)++ .toList() ??++ [item['id'] as String? ?? ''];final rawNumBooks = collapsedSeries['numBooks'] as int? ?? 0;final numBooks = rawNumBooks > 0 ? rawNumBooks : itemIds.length;-- final coverUrls = itemIds-- .take(4)-- .map((id) => lib.getCoverUrl(id))-- .toList();++ final coverUrls = itemIds.take(4).map((id) => lib.getCoverUrl(id)).toList();// Calculate series progressdouble totalProgress = 0;@@@ -473,7 -457,7 +599,9 @@@totalProgress += lib.getProgress(id);}}-- final seriesProgress = itemIds.isNotEmpty ? totalProgress / itemIds.length : 0.0;++ final seriesProgress = itemIds.isNotEmpty++ ? totalProgress / itemIds.length++ : 0.0;return GestureDetector(behavior: HitTestBehavior.opaque,@@@ -537,7 -521,7 +665,12 @@@ class GridSeriesTileDirect extends Statfinal Map<String, dynamic> series;final double coverAspectRatio;final String? parentSeriesId;-- const GridSeriesTileDirect({super.key, required this.series, this.coverAspectRatio = 1.0, this.parentSeriesId});++ const GridSeriesTileDirect({++ super.key,++ required this.series,++ this.coverAspectRatio = 1.0,++ this.parentSeriesId,++ });@overrideWidget build(BuildContext context) {@@@ -547,7 -531,7 +680,8 @@@final lib = context.watch<LibraryProvider>();final auth = context.read<AuthProvider>();-- final seriesName = series['name'] as String? ?? l.libraryGridTilesUnknownSeries;++ final seriesName =++ series['name'] as String? ?? l.libraryGridTilesUnknownSeries;final seriesId = series['id'] as String? ?? '';final books = series['books'] as List<dynamic>? ?? [];final numBooks = books.length;@@@ -562,13 -546,13 +696,10 @@@}// Gather up to 4 cover URLs from books-- final coverUrls = books-- .take(4)-- .map((b) {-- final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';-- return bookId.isNotEmpty ? lib.getCoverUrl(bookId) : null;-- })-- .toList();++ final coverUrls = books.take(4).map((b) {++ final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';++ return bookId.isNotEmpty ? lib.getCoverUrl(bookId) : null;++ }).toList();// Calculate series progressdouble totalProgress = 0;@@@ -584,7 -568,7 +715,9 @@@totalProgress += lib.getProgress(bookId);}}-- final seriesProgress = books.isNotEmpty ? totalProgress / books.length : 0.0;++ final seriesProgress = books.isNotEmpty++ ? totalProgress / books.length++ : 0.0;return GestureDetector(behavior: HitTestBehavior.opaque,@@@ -704,11 -688,11 +837,12 @@@ class GridListTile extends StatelessWidRow(children: [Icon(-- isPlaylist-- ? Icons.playlist_play_rounded-- : Icons.collections_bookmark_rounded,-- size: 12,-- color: cs.onSurfaceVariant),++ isPlaylist++ ? Icons.playlist_play_rounded++ : Icons.collections_bookmark_rounded,++ size: 12,++ color: cs.onSurfaceVariant,++ ),const SizedBox(width: 3),Expanded(child: Text(@@@ -730,7 -714,7 +864,10 @@@: l.collectionDetailBookCount(count),maxLines: 1,overflow: TextOverflow.ellipsis,-- style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 10),++ style: tt.labelSmall?.copyWith(++ color: cs.onSurfaceVariant,++ fontSize: 10,++ ),),],),@@@ -802,7 -786,7 +939,10 @@@ class GridAuthorTile extends StatelessWtop: 0,right: 0,child: Container(-- padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),++ padding: const EdgeInsets.symmetric(++ horizontal: 7,++ vertical: 3,++ ),decoration: BoxDecoration(color: cs.primaryContainer,borderRadius: BorderRadius.circular(10),@@@ -810,11 -794,11 +950,20 @@@child: Row(mainAxisSize: MainAxisSize.min,children: [-- Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),++ Icon(++ Icons.auto_stories_rounded,++ size: 11,++ color: cs.onPrimaryContainer,++ ),const SizedBox(width: 3),-- Text('$numBooks',-- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,-- color: cs.onPrimaryContainer)),++ Text(++ '$numBooks',++ style: TextStyle(++ fontSize: 10,++ fontWeight: FontWeight.w700,++ color: cs.onPrimaryContainer,++ ),++ ),],),),@@@ -841,9 -825,9 +990,11 @@@Widget _placeholder(ColorScheme cs) {return Center(-- child: Icon(Icons.person_rounded,-- size: 32, color: cs.onSecondaryContainer.withValues(alpha: 0.4)),++ child: Icon(++ Icons.person_rounded,++ size: 32,++ color: cs.onSecondaryContainer.withValues(alpha: 0.4),++ ),);}}--diff --cc lib/widgets/library_lists_tab.dartindex a066b823,484e62d1..5501f736--- a/lib/widgets/library_lists_tab.dart+++ b/lib/widgets/library_lists_tab.dart@@@ -10,6 -9,6 +10,7 @@@ class LibraryListsTab extends Statelessfinal List<Map<String, dynamic>> entries;final bool isLoading;final double coverAspectRatio;++ final double desktopMaxCrossAxisExtent;final void Function(Map<String, dynamic>) onOpenCollection;final void Function(Map<String, dynamic>) onOpenPlaylist;final Future<void> Function() onRefresh;@@@ -20,6 -19,6 +21,7 @@@super.key,required this.entries,required this.coverAspectRatio,++ this.desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,required this.onOpenCollection,required this.onOpenPlaylist,required this.onRefresh,@@@ -70,13 -69,13 +72,18 @@@: Column(mainAxisSize: MainAxisSize.min,children: [-- Icon(Icons.collections_bookmark_outlined,-- size: 56,-- color: cs.onSurfaceVariant.withValues(alpha: 0.3)),++ Icon(++ Icons.collections_bookmark_outlined,++ size: 56,++ color: cs.onSurfaceVariant.withValues(alpha: 0.3),++ ),const SizedBox(height: 12),-- Text('No collections or playlists',-- style: tt.bodyLarge-- ?.copyWith(color: cs.onSurfaceVariant)),++ Text(++ 'No collections or playlists',++ style: tt.bodyLarge?.copyWith(++ color: cs.onSurfaceVariant,++ ),++ ),],),),@@@ -90,35 -89,37 +97,39 @@@slivers: [...headers,SliverPadding(- padding: EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding(context)),- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),++ padding: EdgeInsets.fromLTRB(++ 16,++ 8,++ 16,++ libraryGridBottomPadding(context),++ ),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: responsiveGridCount(context),+ gridDelegate: libraryGridDelegate(+ context,childAspectRatio: coverAspectRatio < 1 ? 0.48 : 0.68,- crossAxisSpacing: 10,- mainAxisSpacing: 10,- ),- delegate: SliverChildBuilderDelegate(- (context, index) {- final entry = entries[index];- final isPlaylist = entry['_isPlaylist'] == true;- final name = entry['name'] as String? ?? '';- final ids = isPlaylist- ? _playlistBookIds(entry)- : _collectionBookIds(entry);- final count = isPlaylist- ? (entry['items'] as List<dynamic>?)?.length ?? ids.length- : (entry['books'] as List<dynamic>?)?.length ?? ids.length;- return GridListTile(- name: name,- bookIds: ids,- count: count,- isPlaylist: isPlaylist,- coverAspectRatio: coverAspectRatio,- onTap: () =>- isPlaylist ? onOpenPlaylist(entry) : onOpenCollection(entry),- );- },- childCount: entries.length,++ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,),- delegate: SliverChildBuilderDelegate(- (context, index) {- final entry = entries[index];- final isPlaylist = entry['_isPlaylist'] == true;- final name = entry['name'] as String? ?? '';- final ids = isPlaylist- ? _playlistBookIds(entry)- : _collectionBookIds(entry);- final count = isPlaylist- ? (entry['items'] as List<dynamic>?)?.length ?? ids.length- : (entry['books'] as List<dynamic>?)?.length ?? ids.length;- return GridListTile(- name: name,- bookIds: ids,- count: count,- isPlaylist: isPlaylist,- coverAspectRatio: coverAspectRatio,- onTap: () =>- isPlaylist ? onOpenPlaylist(entry) : onOpenCollection(entry),- );- },- childCount: entries.length,- ),++ delegate: SliverChildBuilderDelegate((context, index) {++ final entry = entries[index];++ final isPlaylist = entry['_isPlaylist'] == true;++ final name = entry['name'] as String? ?? '';++ final ids = isPlaylist++ ? _playlistBookIds(entry)++ : _collectionBookIds(entry);++ final count = isPlaylist++ ? (entry['items'] as List<dynamic>?)?.length ?? ids.length++ : (entry['books'] as List<dynamic>?)?.length ?? ids.length;++ return GridListTile(++ name: name,++ bookIds: ids,++ count: count,++ isPlaylist: isPlaylist,++ coverAspectRatio: coverAspectRatio,++ onTap: () => isPlaylist++ ? onOpenPlaylist(entry)++ : onOpenCollection(entry),++ );++ }, childCount: entries.length),),),],diff --cc lib/widgets/library_series_tab.dartindex 91c8c5dc,f8d2db40..1ae6cfcd--- a/lib/widgets/library_series_tab.dart+++ b/lib/widgets/library_series_tab.dart@@@ -10,6 -9,6 +10,7 @@@ class LibrarySeriesTab extends Statelesfinal bool hasMoreSeries;final bool rectangleCovers;final double coverAspectRatio;++ final double desktopMaxCrossAxisExtent;final Future<void> Function() onRefresh;final VoidCallback onLoadMore;final Widget? headerSliver;@@@ -22,6 -21,6 +23,7 @@@required this.hasMoreSeries,required this.rectangleCovers,required this.coverAspectRatio,++ this.desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,required this.onRefresh,required this.onLoadMore,this.headerSliver,@@@ -61,11 -60,11 +63,16 @@@child: Column(mainAxisSize: MainAxisSize.min,children: [-- Icon(Icons.collections_bookmark_outlined,-- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),++ Icon(++ Icons.collections_bookmark_outlined,++ size: 56,++ color: cs.onSurfaceVariant.withValues(alpha: 0.3),++ ),const SizedBox(height: 12),-- Text(l.libraryNoSeriesFound,-- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),++ Text(++ l.libraryNoSeriesFound,++ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant),++ ),],),),@@@ -79,27 -78,29 +86,32 @@@slivers: [...headers,SliverPadding(- padding: EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding(context)),- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),++ padding: EdgeInsets.fromLTRB(++ 16,++ 8,++ 16,++ libraryGridBottomPadding(context),++ ),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: responsiveGridCount(context),+ gridDelegate: libraryGridDelegate(+ context,childAspectRatio: rectangleCovers ? 0.48 : 0.68,- crossAxisSpacing: 10,- mainAxisSpacing: 10,- ),- delegate: SliverChildBuilderDelegate(- (context, index) {- if (index >= seriesItems.length) {- return const Center(- child: Padding(- padding: EdgeInsets.all(16),- child: CircularProgressIndicator(strokeWidth: 2),- ),- );- }- return GridSeriesTileDirect(- series: seriesItems[index], coverAspectRatio: coverAspectRatio);- },- childCount: seriesItems.length + (hasMoreSeries ? 1 : 0),++ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,),- delegate: SliverChildBuilderDelegate(- (context, index) {- if (index >= seriesItems.length) {- return const Center(- child: Padding(- padding: EdgeInsets.all(16),- child: CircularProgressIndicator(strokeWidth: 2),- ),- );- }- return GridSeriesTileDirect(- series: seriesItems[index], coverAspectRatio: coverAspectRatio);- },- childCount: seriesItems.length + (hasMoreSeries ? 1 : 0),- ),++ delegate: SliverChildBuilderDelegate((context, index) {++ if (index >= seriesItems.length) {++ return const Center(++ child: Padding(++ padding: EdgeInsets.all(16),++ child: CircularProgressIndicator(strokeWidth: 2),++ ),++ );++ }++ return GridSeriesTileDirect(++ series: seriesItems[index],++ coverAspectRatio: coverAspectRatio,++ );++ }, childCount: seriesItems.length + (hasMoreSeries ? 1 : 0)),),),],diff --cc lib/widgets/podcast_episode_feed.dartindex c2ce34fd,b1495b06..ba2dfbbe--- a/lib/widgets/podcast_episode_feed.dart+++ b/lib/widgets/podcast_episode_feed.dart@@@ -543,42 -541,21 +544,23 @@@ class _PodcastEpisodeFeedState extendsfinal finished =lib.getEpisodeProgressData(showId, epId)?['isFinished'] ==true;- return Dismissible(+ return SwipeAction(key: ValueKey('feed-$showId-$epId'),- direction: AppPlatform.isWeb- ? DismissDirection.startToEnd- : DismissDirection.horizontal,- // Swipes act without dismissing the row.- confirmDismiss: (direction) async {- if (direction == DismissDirection.startToEnd) {- _toggleFinished(ep);- } else {- _downloadEpisode(ep);- }- return false;- },- background: Container(- color: cs.primaryContainer,- alignment: Alignment.centerLeft,- padding: const EdgeInsets.only(left: 24),- child: Icon(- finished- ? Icons.radio_button_unchecked_rounded- : Icons.check_circle_rounded,- color: cs.onPrimaryContainer,- ),+ borderRadius: BorderRadius.zero,+ onStartToEnd: SwipeActionSpec(+ icon: finished+ ? Icons.radio_button_unchecked_rounded+ : Icons.check_circle_rounded,+ color: cs.primary,+ onTrigger: () => _toggleFinished(ep),),- secondaryBackground: AppPlatform.isWeb- onEndToStart: SwipeActionSpec(- icon: Icons.download_rounded,- color: cs.secondary,- onTrigger: () => _downloadEpisode(ep),- ),++ onEndToStart: AppPlatform.isWeb+ ? null- : Container(- color: cs.secondaryContainer,- alignment: Alignment.centerRight,- padding: const EdgeInsets.only(right: 24),- child: Icon(- Icons.download_rounded,- color: cs.onSecondaryContainer,- ),++ : SwipeActionSpec(++ icon: Icons.download_rounded,++ color: cs.secondary,++ onTrigger: () => _downloadEpisode(ep),+ ),child: Row(crossAxisAlignment: CrossAxisAlignment.center,children: [diff --cc lib/widgets/sleep_timer_sheet.dartindex d0da4887,eb8ea5d7..4df18f5c--- a/lib/widgets/sleep_timer_sheet.dart+++ b/lib/widgets/sleep_timer_sheet.dart@@@ -2,7 -2,6 +2,8 @@@ import 'package:flutter/material.dart'import '../l10n/app_localizations.dart';import '../services/audio_player_service.dart';import '../services/sleep_timer_service.dart';++import '../utils/app_platform.dart';+import 'adaptive_modal.dart';// ─── SHARED SLEEP TIMER SHEET ─────────────────────────────────void showSleepTimerSheet(BuildContext context, Color accent) {@@@ -163,13 -162,13 +164,14 @@@ class _SleepTimerSheetState extends Sta// Rewind on sleep_buildRewindSection(accent, tt, l),-- const SizedBox(height: 12),-- Container(-- height: 0.5, color: cs.onSurface.withValues(alpha: 0.08)),-- const SizedBox(height: 12),---- // Shake toggle-- _buildShakeToggle(accent, tt, l),++ if (!AppPlatform.isWeb) ...[++ const SizedBox(height: 12),++ Container(++ height: 0.5,++ color: cs.onSurface.withValues(alpha: 0.08)),++ const SizedBox(height: 12),++ _buildShakeToggle(accent, tt, l),++ ],],]),),@@@ -282,10 -281,10 +284,12 @@@Container(height: 0.5, color: cs.onSurface.withValues(alpha: 0.08)),const SizedBox(height: 12),_buildRewindSection(accent, tt, l),-- const SizedBox(height: 12),-- Container(height: 0.5, color: cs.onSurface.withValues(alpha: 0.08)),-- const SizedBox(height: 12),-- _buildShakeToggle(accent, tt, l),++ if (!AppPlatform.isWeb) ...[++ const SizedBox(height: 12),++ Container(height: 0.5, color: cs.onSurface.withValues(alpha: 0.08)),++ const SizedBox(height: 12),++ _buildShakeToggle(accent, tt, l),++ ],]);}