# All files / src/app/user/content/[id]/watch useSubtitleControls.ts

0% Statements 0/96
0% Branches 0/52
0% Functions 0/9
0% Lines 0/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

     'use client';

    import { useCallback, useEffect, useState } from 'react';
    import type { RefObject } from 'react';
    import type { SubtitleTrackResponse } from '@/types';

    export type SubtitleControlsArgs = {
      contentId: number;
      subtitles: SubtitleTrackResponse[];
      playerOpen: boolean;
      videoRef: RefObject<HTMLVideoElement | null>;
      shakaRef: RefObject<any>;
    };

    export function useSubtitleControls({
      contentId,
      subtitles,
      playerOpen,
      videoRef,
      shakaRef}: SubtitleControlsArgs) {
      const [selectedSubtitleIndex, setSelectedSubtitleIndex] = useState<number>(-1);
      const [subtitleSize, setSubtitleSize] = useState<'sm' | 'md' | 'lg'>('md');

      const applySubtitleSelection = useCallback(
        (index: number) => {
          // Prefer Shaka-managed tracks when player is active
          const shakaPlayer = shakaRef.current;
          if (shakaPlayer) {
            try {
              const anyPlayer = shakaPlayer as any;
              const tracks = anyPlayer.getTextTracks?.() || [];

              if (index >= 0 && index < tracks.length) {
                anyPlayer.setTextTrackVisibility(true);
                anyPlayer.selectTextTrack(tracks[index]);
                setSelectedSubtitleIndex(index);
                try {
                  localStorage.setItem(`iptv_subs_${contentId}`, String(index));
                } catch {}
                return;
              }
            } catch {
              // fall through to native toggle
            }
          }

          // Fallback to native <video> text tracks (MP4/native)
          const v = videoRef.current;
          if (!v) {
            return;
          }

          const tracks = v.textTracks;

          // Disable all tracks first
          for (let i = 0; i < tracks.length; i++) {
            tracks[i].mode = 'disabled';
          }

          // Enable the selected track
          if (index >= 0 && index < tracks.length) {
            const track = tracks[index];
            track.mode = 'showing';

            // Force reload if track has no cues loaded yet
            if (!track.cues || track.cues.length === 0) {
              // Try to force reload by toggling mode
              track.mode = 'disabled';
              setTimeout(() => {
                track.mode = 'showing';
              }, 100);
            }
          }

          setSelectedSubtitleIndex(index);
          try {
            localStorage.setItem(`iptv_subs_${contentId}`, String(index));
          } catch {}
        },
        [contentId, shakaRef, videoRef]
      );

      const disableAllSubtitles = useCallback(() => {
        // Prefer Shaka when active
        const shakaPlayer = shakaRef.current;
        if (shakaPlayer) {
          try {
            (shakaPlayer as any).setTextTrackVisibility(false);
          } catch {}
          setSelectedSubtitleIndex(-1);
          try {
            localStorage.setItem(`iptv_subs_${contentId}`, String(-1));
          } catch {}
          return;
        }

        // Fallback to native
        const v = videoRef.current;
        if (!v) return;
        const tracks = v.textTracks;
        for (let i = 0; i < tracks.length; i++) {
          tracks[i].mode = 'disabled';
        }
        setSelectedSubtitleIndex(-1);
        try {
          localStorage.setItem(`iptv_subs_${contentId}`, String(-1));
        } catch {}
      }, [contentId, shakaRef, videoRef]);

      // Enhanced subtitle setup for native player
      useEffect(() => {
        if (!playerOpen) return;

        const setupSubtitles = () => {
          try {
            const v = videoRef.current;
            if (!v) return;

            // Wait for text tracks to be loaded
            if (v.textTracks.length === 0 && subtitles.length > 0) {
              return false;
            }

            const saved = localStorage.getItem(`iptv_subs_${contentId}`);
            if (saved !== null) {
              const idx = parseInt(saved, 10);
              if (Number.isFinite(idx) && idx >= -1) {
                if (idx === -1) {
                  disableAllSubtitles();
                } else if (idx < Math.min(subtitles.length, v.textTracks.length)) {
                  applySubtitleSelection(idx);
                } else {
                  // Saved index is out of range, reset to first available
                  if (subtitles.length > 0 && v.textTracks.length > 0) {
                    applySubtitleSelection(0);
                  } else {
                    disableAllSubtitles();
                  }
                }
                return true;
              }
            }

            // Default: enable first subtitle if available
            if (subtitles.length > 0 && v.textTracks.length > 0) {
              applySubtitleSelection(0);
            } else {
              disableAllSubtitles();
            }
            return true;
          } catch (err) {
            console.error('🎬 Error setting up subtitles:', err);
            return true; // Stop retrying on error
          }
        };

        // Try multiple times with increasing delays for native player
        let attempts = 0;
        const maxAttempts = 10;
        const retryTimers: ReturnType<typeof setTimeout>[] = [];

        const attemptSetup = () => {
          attempts++;

          const success = setupSubtitles();
          if (!success && attempts < maxAttempts) {
            const retryTimer = setTimeout(attemptSetup, 200 * attempts); // Increasing delays: 200ms, 400ms, 600ms, etc.
            retryTimers.push(retryTimer);
          }
        };

        // Start with immediate attempt, then use delays
        const timer = setTimeout(attemptSetup, 100);

        return () => {
          clearTimeout(timer);
          retryTimers.forEach((retryTimer) => clearTimeout(retryTimer));
        };
      }, [applySubtitleSelection, contentId, disableAllSubtitles, playerOpen, subtitles, videoRef]);

      return {
        selectedSubtitleIndex,
        setSelectedSubtitleIndex,
        subtitleSize,
        setSubtitleSize,
        applySubtitleSelection,
        disableAllSubtitles};
    }