Repository navigation
Expand file tree
/
Copy pathViewCourseVideoScreen.kt
More file actions
3876 lines (3708 loc) · 196 KB
/
Copy pathViewCourseVideoScreen.kt
File metadata and controls
3876 lines (3708 loc) · 196 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.onlygyaan.presentation.screens
import android.util.Log
import androidx.annotation.OptIn
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathMeasure
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.layout.ContentScale
import coil.compose.AsyncImage
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Star
import androidx.compose.ui.res.painterResource
import com.onlygyaan.R
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import android.app.Activity
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.withStyle
import androidx.compose.foundation.text.ClickableText
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.media3.common.MediaItem
import androidx.media3.common.util.UnstableApi
import androidx.navigation.NavController
import com.onlygyaan.FastPixCache
import com.onlygyaan.FastPixPlayerView
import com.onlygyaan.fastPixToken
import com.onlygyaan.precachePlaybackId
import com.onlygyaan.data.remote.dto.CourseDto
import com.onlygyaan.data.remote.dto.LessonDto
import com.onlygyaan.presentation.viewmodels.HomeViewModel
import com.onlygyaan.ui.theme.SFPro
import com.onlygyaan.ui.theme.SFProBold
import com.onlygyaan.ui.theme.SFProMedium
import com.onlygyaan.ui.theme.SFProRegular
import com.onlygyaan.ui.theme.SFProSemiBold
import com.onlygyaan.ui.theme.Sora
import com.onlygyaan.ui.theme.SoraRegular
import com.onlygyaan.navigation.Screen
import com.onlygyaan.util.Resource
import io.fastpix.media3.core.FastPixPlayer
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope
import com.onlygyaan.ui.theme.Gilroy
import com.onlygyaan.ui.theme.GilroyBold
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.widget.Toast
import com.onlygyaan.data.local.DataStoreManager
import kotlinx.coroutines.flow.first
import org.koin.androidx.compose.koinViewModel
import org.koin.compose.koinInject
// ─── Theme Colors ─────────────────────────────────────────────────────────────
private val BackgroundDark = Color(0xFF111111)
private val SurfaceDark = Color(0xFF111111)
private val CardDark = Color(0xFF242424)
private val AccentPurple = Color(0xFF7B5EA7)
private val AccentOrange = Color(0xFFE8600A)
private val TextPrimary = Color(0xFFFFFFFF)
private val TextSecondary = Color(0xFFAAAAAA)
private val ProgressPurple = Color(0xFF9B6FD4)
private val StarYellow = Color(0xFFFFC107)
// Player/info-sheet drag handle: a flick past this speed (px/s) snaps straight
// to the next anchor in that direction, overriding the release-position threshold.
private const val FLING_VELOCITY_THRESHOLD = 1000f
// `anchors` is ascending (e.g. [Full, Half, Default]).
private fun nearestAnchorIndex(value: Float, anchors: FloatArray): Int {
var bestIdx = 0
var bestDist = Float.MAX_VALUE
for (i in anchors.indices) {
val dist = kotlin.math.abs(anchors[i] - value)
if (dist < bestDist) { bestDist = dist; bestIdx = i }
}
return bestIdx
}
private fun nextAnchorIndexAbove(value: Float, anchors: FloatArray): Int {
for (i in anchors.indices) if (anchors[i] > value + 0.5f) return i
return anchors.lastIndex
}
private fun nextAnchorIndexBelow(value: Float, anchors: FloatArray): Int {
for (i in anchors.indices.reversed()) if (anchors[i] < value - 0.5f) return i
return 0
}
@OptIn(UnstableApi::class)
@kotlin.OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ViewCourseVideoScreen(navController: NavController, courseId: String = "", startLessonId: String = "") {
val viewModel: HomeViewModel = koinViewModel()
val courseState by viewModel.courseState.collectAsState()
val lessonsState by viewModel.lessonsState.collectAsState()
val courseAssignmentId by viewModel.courseAssignmentId.collectAsState()
val isAssignmentSubmitted by viewModel.isAssignmentSubmitted.collectAsState()
val assignmentState by viewModel.assignmentState.collectAsState()
val assignmentDetail = (assignmentState as? Resource.Success)?.data
val lessonProgressCache by viewModel.lessonProgressCache.collectAsState()
val showNextEpisode by viewModel.showNextEpisode.collectAsState()
val globalLanguage by viewModel.globalLanguage.collectAsState()
val courseReviewsState by viewModel.courseReviewsState.collectAsState()
val currentUserId by viewModel.currentUserId.collectAsState()
val courseSavedLessonIds by viewModel.courseSavedLessonIds.collectAsState()
val course = (courseState as? Resource.Success)?.data
Log.d("VideoPlayback", "course=${course?.id} enrolledStudents=${course?.enrolledStudents} earnedAmount=${course?.earnedAmount}")
// Merge server-side lesson data with the in-memory progress cache so the list
// reflects watch progress as the user plays videos — without extra API calls.
val lessons = ((lessonsState as? Resource.Success)?.data ?: emptyList()).map { lesson ->
val cached = lessonProgressCache[lesson.id]
if (cached != null) {
android.util.Log.d("VideoPlayback", "lesson=${lesson.id} → using CACHE: lastPos=${cached.lastPosition} watchPct=${cached.watchPercent} completed=${cached.isCompleted}")
lesson.copy(progress = cached)
} else {
android.util.Log.d("VideoPlayback", "lesson=${lesson.id} → using API progress: lastPos=${lesson.progress?.lastPosition} watchPct=${lesson.progress?.watchPercent} completed=${lesson.progress?.isCompleted}")
lesson
}
}
// Fetch assignment details once we know the assignment ID
LaunchedEffect(courseAssignmentId) {
if (courseAssignmentId.isNotBlank()) viewModel.fetchAssignment(courseAssignmentId)
}
LaunchedEffect(courseId) {
android.util.Log.d("VideoPlayback", "LaunchedEffect courseId='$courseId'")
if (courseId.isNotBlank()) {
viewModel.fetchCourse(courseId)
viewModel.fetchLessons(courseId)
viewModel.fetchCourseReviews(courseId)
viewModel.fetchCourseSavedLessons(courseId)
} else {
android.util.Log.e("VideoPlayback", "courseId is blank — skipping fetch")
}
}
var isSaved by remember { mutableStateOf(false) }
var selectedTab by rememberSaveable { mutableStateOf(0) }
var isFullscreen by remember { mutableStateOf(false) }
var showLanguageSheet by remember { mutableStateOf(false) }
var audioTracks by remember { mutableStateOf<List<io.fastpix.media3.tracks.AudioTrack>>(emptyList()) }
// Label of the audio track currently playing — used to highlight the right row in the sheet.
// Label-based (not ID-based) so it stays valid across separate getAudioTracks() calls.
var currentAudioLabel by remember { mutableStateOf<String?>(null) }
// Persists the user's explicit in-player language choice across lesson changes.
var selectedTrackLabel by remember { mutableStateOf<String?>(null) }
val scrollState = rememberScrollState()
val view = LocalView.current
val context = LocalContext.current
val density = LocalDensity.current
// Block screen recording and screenshots while the player is visible
DisposableEffect(Unit) {
val window = (context as? Activity)?.window
window?.addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
onDispose {
window?.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
}
}
// "preview" → play preview clip with overlay; "lesson" → destroy preview player,
// build a fresh one with the first lesson's playback ID.
// rememberSaveable so navigating away and returning (e.g. story viewer) does not reset
// the player back to preview phase.
// Start directly in "lesson" phase when we already know (synchronously, from nav args)
// that this is a resume — e.g. tapped from "Pick up where you left off". Skips building
// a preview player at all, not just hiding its overlay.
var playerPhase by rememberSaveable { mutableStateOf(if (startLessonId.isNotBlank()) "lesson" else "preview") }
// The "Start this course" button + info overlay is only for a genuinely fresh course —
// defaults hidden, and is explicitly shown only once lessonsState confirms there's no
// progress anywhere in the course (see LaunchedEffect(lessonsState) below). Previously
// this defaulted true and flashed on-screen for every course open, fresh or not, until
// that same effect caught up and hid it again a beat later.
var showPreviewOverlay by rememberSaveable { mutableStateOf(false) }
var showLoader by rememberSaveable { mutableStateOf(true) }
var selectedLessonPlaybackId by rememberSaveable { mutableStateOf<String?>(null) }
// Hoisted above the player's key() block (rather than declared inside it) so it survives
// player rebuilds and can be read by the Modules list to show a pause icon on whichever
// lesson card is actually playing right now.
var isPlaying by remember { mutableStateOf(false) }
// Per-playback-ID resume positions — each lesson/preview independently remembers
// where the user left off. Persists across recompositions within the screen session
// (episode switches, story viewer, write-review, etc.).
val resumePositions = remember { mutableStateMapOf<String, Long>() }
// Set to true by story-bubble click → picked up by LaunchedEffect inside the key block
// to call player.pause() before the composable goes off-screen.
var pausePlayerFlag by remember { mutableStateOf(false) }
// Incremented by tapping the "Currently Playing" bar in the Modules list → picked up by
// a LaunchedEffect inside the key block to toggle play/pause on the live player, without
// that list needing direct access to the player instance (which lives inside key()).
var togglePlayPauseRequest by remember { mutableStateOf(0) }
// Derived reactively — re-reads lessonsState and selectedLessonPlaybackId on every access.
// Avoids the capture-at-launch-time bug of LaunchedEffect lambdas.
val currentLessonId by remember {
derivedStateOf {
if (playerPhase == "preview") return@derivedStateOf null
val list = (lessonsState as? Resource.Success)?.data ?: return@derivedStateOf null
if (selectedLessonPlaybackId != null)
list.find { it.playbackId == selectedLessonPlaybackId }?.id
else
list.firstOrNull()?.id
}
}
val currentLesson by remember {
derivedStateOf {
val list = (lessonsState as? Resource.Success)?.data ?: return@derivedStateOf null
if (selectedLessonPlaybackId != null)
list.find { it.playbackId == selectedLessonPlaybackId }
else
list.firstOrNull()
}
}
var isLiked by remember(currentLesson) { mutableStateOf(currentLesson?.isLiked ?: false) }
// Playback IDs derived from real API data
val previewPlaybackId = course?.previewLessons?.fastpix?.playbackId
val firstLessonPlaybackId = lessons.firstOrNull()?.playbackId
// Pre-cache the next couple of upcoming lessons so switching feels instant.
// Keyed on just the ordered playback-ID list (not the full `lessons` objects) — `lessons`
// gets a new copy every ~5s while playing (the progress ticker merges updated watch
// position into it), which would otherwise restart this effect that often and cancel
// in-flight pre-caching for no reason, since the actual queue window never changed.
val orderedLessonPlaybackIds = lessons.sortedBy { it.orderIndex }.map { it.playbackId }
LaunchedEffect(selectedLessonPlaybackId, orderedLessonPlaybackIds) {
if (orderedLessonPlaybackIds.isEmpty()) return@LaunchedEffect
val currentIdx = orderedLessonPlaybackIds.indexOfFirst {
it == (selectedLessonPlaybackId ?: firstLessonPlaybackId)
}
if (currentIdx < 0) return@LaunchedEffect
val urls = (currentIdx + 1..currentIdx + 2)
.mapNotNull { orderedLessonPlaybackIds.getOrNull(it) }
.map { id -> FastPixCache.playbackUrl(id, viewModel.fastPixToken(id)) }
FastPixCache.preCache(urls)
}
// Fetch + cache server progress whenever the active lesson changes —
// covers both the auto-playing first lesson and any manually selected lesson.
// Also hides the Next Episode button until the last-5-sec API call confirms it.
LaunchedEffect(currentLessonId) {
android.util.Log.d("VideoPlayback", "LaunchedEffect(currentLessonId) fired — currentLessonId=$currentLessonId playerPhase=$playerPhase")
viewModel.resetNextEpisode()
val lessonId = currentLessonId ?: run {
android.util.Log.d("VideoPlayback", "skipped fetchLessonProgress — currentLessonId is null")
isSaved = false
return@LaunchedEffect
}
android.util.Log.d("VideoPlayback", "→ fetchLessonProgress($lessonId)")
viewModel.fetchLessonProgress(lessonId)
isSaved = lessonId in courseSavedLessonIds
}
// getCourse's progress object carries the resume lesson's playback_id directly, so we
// can start warming its token/segments the moment THIS resolves — in parallel with
// fetchLessons() — instead of waiting for whichever of the two calls is slower before
// the queue-init effect even knows what to fetch a token for.
LaunchedEffect(courseState) {
val resumePlaybackId = (courseState as? Resource.Success)?.data?.progress?.playbackId
if (!resumePlaybackId.isNullOrBlank()) {
android.util.Log.d("VideoPlayback", "🔥 warming resume lesson from getCourse: $resumePlaybackId")
viewModel.precachePlaybackId(resumePlaybackId)
}
}
LaunchedEffect(courseState) {
when (val s = courseState) {
is Resource.Success -> {
android.util.Log.d("VideoPlayback", "courseState=Success")
android.util.Log.d("VideoPlayback", "course.id=${s.data?.id}")
android.util.Log.d("VideoPlayback", "previewPlaybackId=${s.data?.previewLessons?.fastpix?.playbackId}")
}
is Resource.Error -> android.util.Log.e("VideoPlayback", "courseState=Error msg=${s.message}")
else -> android.util.Log.d("VideoPlayback", "courseState=${s?.let { it::class.simpleName } ?: "null"}")
}
}
LaunchedEffect(lessonsState) {
when (val s = lessonsState) {
is Resource.Success -> {
android.util.Log.d("VideoPlayback", "lessonsState=Success count=${s.data?.size}")
s.data.forEachIndexed { i, l ->
android.util.Log.d("VideoPlayback", "lesson[$i] orderIndex=${l.orderIndex} title=${l.title} playbackId=${l.playbackId} isCompleted=${l.progress?.isCompleted} watchPct=${l.progress?.watchPercent} lastPos=${l.progress?.lastPosition}")
}
// Auto-skip preview when launched from saved lesson OR when course has progress
if (playerPhase == "preview") {
val sorted = s.data.sortedBy { it.orderIndex }
val hasProgress = sorted.any { l ->
l.progress != null && (l.progress.isCompleted || l.progress.watchPercent > 0)
}
if (startLessonId.isNotBlank() || hasProgress) {
android.util.Log.d("VideoPlayback", "📖 Skipping preview → lesson mode (startLessonId=$startLessonId hasProgress=$hasProgress)")
showPreviewOverlay = false
showLoader = true
playerPhase = "lesson"
} else {
// Genuinely fresh course — nothing started anywhere, no explicit
// resume target. Only now show the "Start this course" overlay.
android.util.Log.d("VideoPlayback", "🆕 Fresh course — showing Start Course overlay")
showPreviewOverlay = true
showLoader = false
}
}
}
is Resource.Error -> android.util.Log.e("VideoPlayback", "lessonsState=Error msg=${s.message}")
else -> android.util.Log.d("VideoPlayback", "lessonsState=${s?.let { it::class.simpleName } ?: "null"}")
}
}
LaunchedEffect(playerPhase, lessonsState) {
if (playerPhase == "lesson") {
val lessons = (lessonsState as? Resource.Success)?.data
if (!lessons.isNullOrEmpty()) {
if (selectedLessonPlaybackId == null) {
val sorted = lessons.sortedBy { it.orderIndex }
// If launched from saved lessons, jump directly to that lesson
val resumeLesson = if (startLessonId.isNotBlank()) {
val target = sorted.firstOrNull { it.id == startLessonId }
android.util.Log.d("VideoPlayback", "startLessonId=$startLessonId → target=${target?.title}")
target ?: sorted.firstOrNull { it.progress?.isCompleted != true } ?: sorted.last()
} else {
sorted.firstOrNull { it.progress?.isCompleted != true } ?: sorted.last()
}
selectedLessonPlaybackId = resumeLesson.playbackId
val lastPosSec = resumeLesson.progress?.lastPosition ?: 0
if (lastPosSec > 0 && resumeLesson.playbackId != null) {
resumePositions[resumeLesson.playbackId] = lastPosSec.toLong() * 1000L
}
android.util.Log.d("VideoPlayback", "✅ Resume → [${resumeLesson.orderIndex}] \"${resumeLesson.title}\" | playbackId=${resumeLesson.playbackId}")
}
} else {
android.util.Log.d("VideoPlayback", "⏳ Lessons not ready yet")
}
}
}
// After 5 s: hide the overlay buttons — preview video keeps playing.
// playerPhase stays "preview" so the player is NOT rebuilt.
LaunchedEffect(showPreviewOverlay) {
if (showPreviewOverlay) {
delay(5_000)
showPreviewOverlay = false
}
}
// Use real display pixels — immune to any inset/constraint narrowing in the hierarchy
val displayWidthPx = remember { context.resources.displayMetrics.widthPixels }
val displayHeightPx = remember { context.resources.displayMetrics.heightPixels }
// Three anchors for the draggable player/info-sheet split:
// - Default (640dp player height) — what a user sees the moment they land on a
// course, before any drag; the info sheet only shows a sliver below the player.
// - Half (300dp player height) — the pre-existing drag ceiling; info sheet visible
// at roughly half the screen. This is the original "opens to half of screen" behavior.
// - Full (0dp player height) — new: player collapses away entirely, info sheet fills
// the whole screen, video hidden behind it.
val defaultHeightPx = with(density) { 640.dp.toPx() }
val halfHeightPx = with(density) { 300.dp.toPx() }
val fullHeightPx = 0f
// Ascending order — used to find the nearest/next anchor during drag & tap handling.
val sheetAnchorsPx = remember(fullHeightPx, halfHeightPx, defaultHeightPx) {
floatArrayOf(fullHeightPx, halfHeightPx, defaultHeightPx)
}
// Unrestricted scope for animating the settle-to-anchor: the handle's gesture
// detection runs inside a restricted AwaitPointerEventScope that cannot itself
// launch/await a suspend animation, so the launch happens on this scope instead.
val sheetSettleScope = rememberCoroutineScope()
// Hold state directly so the NestedScrollConnection can safely read/write it
val playerHeightState = remember { mutableFloatStateOf(defaultHeightPx) }
val playerHeightDp by remember { derivedStateOf { with(density) { playerHeightState.floatValue.toDp() } } }
// True once the player has fully collapsed behind the expanded info sheet —
// drives auto pause/resume of the video (see LaunchedEffect inside the player key() block).
val isPlayerHidden by remember { derivedStateOf { playerHeightState.floatValue <= 0.5f } }
// -1 while stepping Default→Half→Full, +1 while stepping Full→Half→Default —
// lets a tap at the Half anchor know which direction to continue in.
var sheetTapDirection by remember { mutableStateOf(-1) }
// Intercept scroll: shrink player going down, expand player going up
val nestedScrollConnection = remember(fullHeightPx, defaultHeightPx) {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val delta = available.y
val current = playerHeightState.floatValue
return when {
// Scrolling up → shrink player first
delta < 0f && current > fullHeightPx -> {
val newHeight = (current + delta).coerceAtLeast(fullHeightPx)
playerHeightState.floatValue = newHeight
Offset(0f, newHeight - current)
}
// Scrolling down → expand player first (only if content is at top)
delta > 0f && current < defaultHeightPx && scrollState.value == 0 -> {
val newHeight = (current + delta).coerceAtMost(defaultHeightPx)
playerHeightState.floatValue = newHeight
Offset(0f, newHeight - current)
}
else -> Offset.Zero
}
}
// Explicit override required — Live Edit cannot proxy default interface
// methods whose parameters use Kotlin inline/value classes (like Offset)
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset = Offset.Zero
}
}
// MainActivity.enableEdgeToEdge() already sets setDecorFitsSystemWindows(false) for the
// whole activity — we must NOT restore it to true on dispose, or the system will add its own
// nav-bar padding on top of the AppBottomBar's navigationBarsPadding(), causing double space.
// We only need to ensure system bars are visible again when leaving this screen.
DisposableEffect(Unit) {
onDispose {
val window = (view.context as Activity).window
WindowInsetsControllerCompat(window, view).show(WindowInsetsCompat.Type.systemBars())
}
}
// Toggle bar visibility only — no window layout change because we're already edge-to-edge
LaunchedEffect(isFullscreen) {
val window = (view.context as Activity).window
val controller = WindowInsetsControllerCompat(window, view)
if (isFullscreen) {
controller.hide(WindowInsetsCompat.Type.systemBars())
controller.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
} else {
controller.show(WindowInsetsCompat.Type.systemBars())
}
}
val playerGradient = Brush.verticalGradient(
0f to Color(0xFF212121), 0.88f to Color(0xFF181818), 1f to Color(0xFF0D0D0D)
)
// Single composition tree — FastPixPlayerView is NEVER removed from the tree.
// Fullscreen is handled by changing modifiers only, so the AndroidView surface
// stays alive and the video never goes black.
Column(
modifier = Modifier
.fillMaxSize()
.background(BackgroundDark)
.let { if (!isFullscreen) it.nestedScroll(nestedScrollConnection) else it }
) {
// ── Top bar — hidden in fullscreen ────────────────────────────────────
if (!isFullscreen) {
Row(
modifier = Modifier
.fillMaxWidth()
.statusBarsPadding()
.background(BackgroundDark)
.padding(horizontal = 4.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Default.ArrowBack, "Back", tint = TextPrimary)
}
Text(
text = course?.translatedTitle ?: course?.title ?: "Loading…",
color = TextPrimary,
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f).padding(end = 12.dp)
)
}
}
// ── Player area — wrapping Box lets the preview overlay use matchParentSize()
// so it is always exactly the same size as the player, regardless of the
// required* child inside playerBoxMod that can inflate fillMaxSize() constraints.
Box {
// key() keeps FastPixPlayerView in the same composition slot
// regardless of sibling additions/removals (top bar, content).
// Modifier changes resize the container; the AndroidView inside is never recreated.
//
// IMPORTANT: playerBoxMod must ALWAYS have the same modifier structure
// (layout + clipToBounds) regardless of fullscreen state. Switching between
// Modifier.fillMaxSize() and Modifier.layout{}.clipToBounds() creates/destroys a
// Compose graphics layer on every toggle, which re-routes the AndroidView through
// the new layer and destabilises the SurfaceView → video goes blank on collapse.
// Keeping the structure identical means only the height *value* changes, and no
// layer is ever created or destroyed during the fullscreen toggle.
// Changing playerPhase destroys this entire block and rebuilds it fresh,
// giving a brand-new FastPixPlayer with no state from the previous phase.
key(playerPhase) {
// ── Per-phase player + state (reset automatically on phase change) ──
// Pre-create the PlayerView so AnalyticsConfig can wrap it before the player
// is built. Both are frozen in this key slot — rebuilt only when key changes.
val fpPlayerView = remember { io.fastpix.media3.PlayerView(context) }
val player = remember {
android.util.Log.d("VideoPlayback", "🏗 building player — phase=$playerPhase")
// Course-level analytics only (not per-lesson): this player now persists
// across every lesson switch within "lesson" phase, and AnalyticsConfig
// can't be rebound on a live player — accepted trade-off, analytics is not
// a concern for this pass.
val videoTitle = if (playerPhase == "lesson")
course?.title ?: ""
else
"Preview — ${course?.title ?: ""}"
val videoDetails = io.fastpix.data.domain.model.VideoDataDetails(
videoId = course?.id ?: "",
videoTitle = videoTitle
).apply {
videoSeries = course?.title ?: ""
}
val analyticsConfig = io.fastpix.media3.analytics.AnalyticsConfig.Builder(
fpPlayerView, "1154926753932935170"
)
.setVideoDataDetails(videoDetails)
.setEnabled(true)
.build()
FastPixPlayer.Builder(context)
.setAnalyticsConfig(analyticsConfig)
.setBufferConfig(io.fastpix.media3.buffer.BufferConfig.FEED)
.setCacheConfig(FastPixCache.cacheConfig)
.setAbrConfig(FastPixCache.abrConfig)
.let {
// Lets FastPix warm ~5s of the next queued lesson while the
// current one plays — only useful with setMediaItems(), which the
// lesson branch below uses.
if (playerPhase == "lesson") it.setPreloadConfig(io.fastpix.media3.preload.PreloadConfig.FEED)
else it
}
.build()
}
var currentMs by remember { mutableStateOf(0L) }
var durationMs by remember { mutableStateOf(0L) }
var showControls by remember { mutableStateOf(false) }
var videoEnded by remember { mutableStateOf(false) }
// Set right when a new lesson's queue is pushed via setMediaItems(); consumed
// by the next onBufferingEnd so a normal mid-lesson rebuffer is ignored.
var expectingNewLessonReady by remember { mutableStateOf(false) }
// Preview: single clip, plays immediately once loaded. Untouched by the
// queue-based rewrite below — preview isn't part of the lessons queue.
LaunchedEffect(playerPhase, previewPlaybackId) {
if (playerPhase != "preview") return@LaunchedEffect
android.util.Log.d("VideoPlayback", "📼 preparing preview media item id=$previewPlaybackId")
if (!previewPlaybackId.isNullOrBlank()) {
val playbackToken = try {
viewModel.fastPixToken(previewPlaybackId)
} catch (e: Exception) {
android.util.Log.e("VideoPlayback", "💥 getFastPixToken threw: ${e::class.simpleName}: ${e.message}", e)
null
}
// Built as a raw MediaItem + manually-constructed URL — same as the
// lesson/queue path below — instead of the SDK's setFastPixMediaItem()
// builder. Confirmed on-device: setFastPixMediaItem() rejected a
// verified-valid, non-blank 642-char token with "code=9010 Token is
// empty" (a server-side error, not a client validation — the string
// doesn't exist anywhere in the decompiled SDK), while the exact same
// token via a manually-built URL works fine on the lesson path. Whatever
// that builder does internally with the token, it doesn't survive intact.
val previewUrl = FastPixCache.playbackUrl(previewPlaybackId, playbackToken)
val previewItem = MediaItem.Builder()
.setMediaId(previewPlaybackId)
.setUri(previewUrl)
.build()
FastPixCache.invalidateToken(previewPlaybackId)
player.setMediaItems(listOf(previewItem), 0, 0L)
player.play(); isPlaying = true
}
}
// Lesson: set the WHOLE course's queue onto the persistent player exactly
// once (never rebuilt per lesson — see key(playerPhase) above), then navigate
// between lessons by seeking within that same queue instead of calling
// setMediaItems() again. Calling setMediaItems repeatedly (the previous
// approach) was confirmed via decompiling the SDK to force a full
// exoPlayer.prepare() every time — discarding whatever PreloadConfig had
// already warmed for the "next" item, defeating the entire point of the
// queue. Keyed on orderedLessonPlaybackIds (not `lessons`) since `lessons`
// gets a new copy every ~5s while playing (progress ticker).
var previousFlushLessonId by remember { mutableStateOf<String?>(null) }
var queueInitialized by remember { mutableStateOf(false) }
// Cheap guard against a same-instance re-trigger of this effect for the exact
// same target. NOTE: on-device this turned out insufficient on its own — the
// actual duplicate-token-request bug came from two separate composition
// instances each with their own remembered state, which this can't see across.
// The real fix is FastPixCache.dedupedTokenFetch(), which coalesces concurrent
// requests for the same playbackId at a process-wide level; this guard is kept
// as a harmless extra for the plain same-instance case.
var lastFastStartedId by remember { mutableStateOf<String?>(null) }
LaunchedEffect(playerPhase, selectedLessonPlaybackId, orderedLessonPlaybackIds) {
if (playerPhase != "lesson") return@LaunchedEffect
if (orderedLessonPlaybackIds.isEmpty()) return@LaunchedEffect
// Wait for the resume-lesson decision (the other LaunchedEffect above,
// also keyed on lessonsState) to actually set this — guessing via
// firstLessonPlaybackId here let this effect fire once with a wrong/
// premature target, then get cancelled and re-fire moments later once
// the real value landed. Confirmed on-device: that guess-then-correct
// cycle was costing ~600ms of pure waste on every course open.
val targetId = selectedLessonPlaybackId ?: return@LaunchedEffect
val targetIdx = orderedLessonPlaybackIds.indexOfFirst { it == targetId }
if (targetIdx < 0) return@LaunchedEffect
if (!queueInitialized && targetId == lastFastStartedId) return@LaunchedEffect
// Flush the outgoing lesson's watch position — replaces what used to
// happen automatically in DisposableEffect.onDispose per lesson-key-rebuild.
previousFlushLessonId?.let { lessonId ->
if (currentMs > 0) {
android.util.Log.d("VideoPlayback", "✅ flushing cache on switch — lessonId=$lessonId pos=${currentMs / 1000}s")
viewModel.cacheProgress(lessonId, (currentMs / 1000).toInt(), (durationMs / 1000).toInt())
}
}
currentMs = 0L; durationMs = 0L; videoEnded = false
expectingNewLessonReady = true
val startPositionMs = resumePositions[targetId] ?: 0L
if (!queueInitialized) {
lastFastStartedId = targetId
// Fast-start: fetch + queue ONLY the lesson about to play, so
// playback can begin the moment its (often already-cached) token
// resolves — not after every lesson in the course has one. Waiting
// on the whole course's tokens before the first frame was the
// actual bottleneck (verified on-device: ~1.2s of dead time from a
// handful of concurrent token fetches racing the one lesson that
// mattered). The rest of the queue is backfilled below, in the
// background, without blocking this.
android.util.Log.d("VideoPlayback", "⏳ fast-start awaiting token for id=$targetId")
val targetToken = viewModel.fastPixToken(targetId)
android.util.Log.d("VideoPlayback", "✓ fast-start token resolved for id=$targetId isNull=${targetToken == null}")
val targetUrl = FastPixCache.playbackUrl(targetId, targetToken)
val targetItem = MediaItem.Builder()
.setMediaId(targetId)
.setUri(targetUrl)
.build()
FastPixCache.invalidateToken(targetId)
android.util.Log.d("VideoPlayback", "📼 setMediaItems (fast-start, single item) id=$targetId startIdx=0 isWarm=${FastPixCache.isWarm(targetUrl)}")
player.setMediaItems(listOf(targetItem), 0, startPositionMs)
// Backfill the rest of the course around it — addMediaItems() does
// not disturb the item currently playing (only setMediaItems/prepare
// does), so this cannot interrupt what the user is already watching.
launch {
val before = orderedLessonPlaybackIds.subList(0, targetIdx).filterNotNull()
val after = orderedLessonPlaybackIds.subList(targetIdx + 1, orderedLessonPlaybackIds.size).filterNotNull()
suspend fun buildItems(ids: List<String>) = coroutineScope {
ids.map { id -> async { id to viewModel.fastPixToken(id) } }.awaitAll()
}.map { (id, token) ->
val item = MediaItem.Builder().setMediaId(id).setUri(FastPixCache.playbackUrl(id, token)).build()
FastPixCache.invalidateToken(id)
item
}
val beforeItems = buildItems(before)
val afterItems = buildItems(after)
if (beforeItems.isNotEmpty()) player.getExoPlayer().addMediaItems(0, beforeItems)
if (afterItems.isNotEmpty()) player.getExoPlayer().addMediaItems(beforeItems.size + 1, afterItems)
android.util.Log.d("VideoPlayback", "📼 backfilled queue — before=${beforeItems.size} after=${afterItems.size}")
queueInitialized = true
}
} else {
// Navigate within the existing queue — no setMediaItems, so whatever
// PreloadConfig already warmed for this item survives the switch.
android.util.Log.d("VideoPlayback", "⏭ seekTo phase=lesson idx=$targetIdx")
player.getExoPlayer().seekTo(targetIdx, startPositionMs)
// Resume explicitly instead of waiting on onBufferingEnd: that callback
// is gated on expectingNewLessonReady but never fires when the target
// item is already warm from the backfill above, which left playback
// stuck paused (and the loader stuck on) after every auto-advance to a
// pre-buffered next lesson.
player.play()
isPlaying = true
showLoader = false
showControls = true
expectingNewLessonReady = false
}
previousFlushLessonId = currentLessonId
}
DisposableEffect(Unit) {
onDispose {
// Final safety-net flush — fires on the preview→lesson transition and
// on leaving the screen (key(playerPhase) only rebuilds on those).
val lessonId = currentLessonId
val posSec = (currentMs / 1000).toInt()
val durSec = (durationMs / 1000).toInt()
android.util.Log.d("VideoPlayback", "onDispose — lessonId=$lessonId currentMs=$currentMs posSec=$posSec durSec=$durSec phase=$playerPhase")
if (lessonId == null) {
android.util.Log.w("VideoPlayback", "⚠ skipped — currentLessonId is null")
} else if (currentMs <= 0) {
android.util.Log.w("VideoPlayback", "⚠ skipped — currentMs=$currentMs (video may not have started)")
} else {
android.util.Log.d("VideoPlayback", "✅ flushing cache — lessonId=$lessonId pos=${posSec}s dur=${durSec}s")
viewModel.cacheProgress(lessonId, posSec, durSec)
}
android.util.Log.d("VideoPlayback", "♻️ player.release() phase=$playerPhase")
player.release()
}
}
// Pause when app goes to background, resume when it comes back
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_PAUSE -> player.pause()
Lifecycle.Event.ON_RESUME -> if (isPlaying) player.play()
else -> Unit
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
// Pause the player when the story viewer is about to open
LaunchedEffect(pausePlayerFlag) {
if (pausePlayerFlag) {
player.pause()
pausePlayerFlag = false
}
}
// Toggle play/pause when requested from the Modules list's "Currently
// Playing" bar. Baseline captured at the moment this player was built so a
// stale request left over from a lesson switch doesn't fire on the new player.
val toggleRequestBaseline = remember { togglePlayPauseRequest }
LaunchedEffect(togglePlayPauseRequest) {
if (togglePlayPauseRequest != toggleRequestBaseline) {
if (isPlaying) {
player.pause()
} else {
player.play()
// Bring the player back into view if it's hidden behind an
// expanded sheet — resuming playback should make it visible again.
sheetSettleScope.launch { scrollState.animateScrollTo(0) }
sheetSettleScope.launch {
Animatable(playerHeightState.floatValue).animateTo(
targetValue = halfHeightPx,
animationSpec = tween(durationMillis = 220)
) {
playerHeightState.floatValue = value
}
}
}
}
}
// Auto pause when the info sheet expands to full screen (video is hidden
// behind it) and auto resume when it collapses back and the video is
// visible again — only if playback was actually running before it hid.
var resumeAfterSheetCollapse by remember { mutableStateOf(false) }
LaunchedEffect(isPlayerHidden) {
if (isPlayerHidden) {
if (isPlaying) {
resumeAfterSheetCollapse = true
player.pause()
}
} else if (resumeAfterSheetCollapse) {
resumeAfterSheetCollapse = false
player.play()
}
}
LaunchedEffect(showControls, videoEnded) {
if (showControls && !videoEnded) {
delay(3000)
showControls = false
}
}
// ── Progress reporting ────────────────────────────────────────
// Ticker only runs while playing — cancelled automatically when isPlaying turns false
LaunchedEffect(isPlaying) {
if (!isPlaying) {
// Flush position immediately on pause
val lessonId = currentLessonId ?: return@LaunchedEffect
if (currentMs > 0) {
val posSec = (currentMs / 1000).toInt()
val durSec = (durationMs / 1000).toInt()
android.util.Log.d("VideoPlayback", "⏸ pause flush — lessonId=$lessonId pos=${posSec}s")
viewModel.sendProgress(lessonId, posSec)
viewModel.cacheProgress(lessonId, posSec, durSec)
}
return@LaunchedEffect
}
android.util.Log.i("VideoPlayback", "⏱ ticker started — phase=$playerPhase")
while (true) {
delay(5_000)
val lessonId = currentLessonId
if (lessonId == null) { android.util.Log.w("VideoPlayback", "⚠ skipped: lessonId is null"); continue }
if (currentMs <= 0) { android.util.Log.w("VideoPlayback", "⚠ skipped: currentMs=$currentMs"); continue }
val posSec = (currentMs / 1000).toInt()
val durSec = (durationMs / 1000).toInt()
android.util.Log.i("VideoPlayback", "✅ ticker firing — lessonId=$lessonId pos=${posSec}s calling sendProgress")
viewModel.sendProgress(lessonId, posSec)
viewModel.cacheProgress(lessonId, posSec, durSec)
}
}
val nearEnd = durationMs > 0 && currentMs > 0 && (durationMs - currentMs) < 1500L
LaunchedEffect(nearEnd) {
if (nearEnd && !videoEnded) {
delay(1500L)
if (durationMs > 0 && (durationMs - currentMs) < 1500L) {
if (playerPhase == "preview") {
// ✅ AUTO SWITCH TO LESSON 1
android.util.Log.d("VideoPlayback", "🎬 Preview ended → switching to Lesson 1")
showPreviewOverlay = false
showLoader = true
playerPhase = "lesson"
} else {
// Existing behavior for lessons
isPlaying = false
videoEnded = true
showControls = true
// If this was the last lesson, the assignment/certificate
// unlock state may have just changed server-side — force a
// re-fetch so isCourseCompleted picks it up. fetchCourse()'s
// own "already loaded" guard would otherwise skip this, since
// it was already fetched once when the screen opened.
val sortedLessons = lessons.sortedBy { it.orderIndex }
val isLastLesson = sortedLessons.lastOrNull()?.id == currentLessonId
android.util.Log.d("VideoPlayback", "lesson ended — currentLessonId=$currentLessonId lastLessonId=${sortedLessons.lastOrNull()?.id} isLastLesson=$isLastLesson courseId=$courseId")
if (courseId.isNotBlank() && isLastLesson) {
android.util.Log.d("VideoPlayback", "last lesson finished → forcing course re-fetch")
viewModel.fetchCourse(courseId, forceRefresh = true)
}
}
}
}
}
val playerBoxMod = Modifier
.layout { measurable, constraints ->
val heightPx = if (isFullscreen) displayHeightPx else playerHeightDp.roundToPx()
val placeable = measurable.measure(
constraints.copy(
minWidth = displayWidthPx,
maxWidth = displayWidthPx,
minHeight = heightPx,
maxHeight = heightPx
)
)
layout(displayWidthPx, heightPx) { placeable.place(0, 0) }
}
.clipToBounds()
// surfaceMod is INTENTIONALLY constant — never changes size based on isFullscreen.
val surfaceMod = Modifier
.requiredWidth(with(density) { displayWidthPx.toDp() })
.requiredHeight(with(density) { displayHeightPx.toDp() })
Box(modifier = playerBoxMod) {
Box(
modifier = surfaceMod
.background(playerGradient)
.pointerInput(isFullscreen, playerPhase, lessons, selectedLessonPlaybackId) {
val swipeThresholdPx = 80.dp.toPx()
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false)
var totalDy = 0f
var totalDx = 0f
var isDragging = false
loop@ while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull() ?: break@loop
if (!change.pressed) {
// Finger lifted — decide tap vs swipe
if (!isDragging) {
// Tap: toggle controls
if (playerPhase == "lesson" || (playerPhase == "preview" && !showPreviewOverlay)) showControls = !showControls
} else if (isFullscreen && playerPhase == "lesson") {
val currentIdx = lessons.indexOfFirst {
it.playbackId == (selectedLessonPlaybackId ?: lessons.firstOrNull()?.playbackId)
}
if (totalDy < -swipeThresholdPx && currentIdx < lessons.size - 1) {
// Swipe up → next lesson
val next = lessons[currentIdx + 1]
if (next.playbackId != null && !resumePositions.containsKey(next.playbackId)) {
val s = next.progress?.lastPosition ?: 0
if (s > 0) resumePositions[next.playbackId] = s.toLong() * 1000L
}
selectedLessonPlaybackId = next.playbackId
showLoader = true
isPlaying = false
} else if (totalDy < -swipeThresholdPx && currentIdx >= 0 && currentIdx == lessons.lastIndex) {
// Swipe up on the last lesson — nothing to advance to.
// Exit fullscreen, collapse the player out of the way, and
// scroll the info sheet down to the last lesson/certificate.
isFullscreen = false
sheetSettleScope.launch {
Animatable(playerHeightState.floatValue).animateTo(
targetValue = fullHeightPx,
animationSpec = tween(durationMillis = 220)
) {
playerHeightState.floatValue = value
}
}
sheetSettleScope.launch { scrollState.animateScrollTo(scrollState.maxValue) }
} else if (totalDy > swipeThresholdPx && currentIdx > 0) {
// Swipe down → prev lesson
val prev = lessons[currentIdx - 1]
if (prev.playbackId != null && !resumePositions.containsKey(prev.playbackId)) {
val s = prev.progress?.lastPosition ?: 0
if (s > 0) resumePositions[prev.playbackId] = s.toLong() * 1000L
}
selectedLessonPlaybackId = prev.playbackId