# All files / src/components/admin EpisodesManagementDialog.tsx

0% Statements 0/429
0% Branches 0/279
0% Functions 0/79
0% Lines 0/394

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
    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
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238

     /* eslint-disable @typescript-eslint/no-unused-vars */
    import React, { useState, useEffect, useCallback } from 'react';
    import { useTranslation } from 'react-i18next';
    import useLoadNamespace from '@/hooks/useLoadNamespace';
    import { z } from 'zod';
    import { VideoUploadField } from '@/components/ui/video-upload-field';
    import {
      Dialog,
      DialogContent,
      DialogHeader,
      DialogTitle
    } from '@/components/ui/dialog';
    import {
      Tabs,
      TabsContent,
      TabsList,
      TabsTrigger
    } from '@/components/ui/tabs';
    import {
      Card,
      CardContent,
      CardDescription,
      CardHeader,
      CardTitle
    } from '@/components/ui/card';
    import {
      Accordion,
      AccordionContent,
      AccordionItem,
      AccordionTrigger
    } from '@/components/ui/accordion';
    import { Button } from '@/components/ui/button';
    import { Input } from '@/components/ui/input';
    import { Label } from '@/components/ui/label';
    import { Textarea } from '@/components/ui/textarea';
    import { Badge } from '@/components/ui/badge';
    import { Plus, Trash2, Save, Play, AlertCircle, Loader2 } from 'lucide-react';
    import { Content, Series, Season as SeasonType, Episode as EpisodeType } from '@/types';
    import { contentService } from '@/services';
    import { apiErrorMessage } from '@/lib/utils';
    import { Tooltip } from '@/components/ui/tooltip';
    import i18n from '@/lib/i18n';
    import { toast } from 'sonner';

    // Episode schema (used for local form state)
    const episodeSchema = z.object({
      id: z.number().optional(),
      episode_number: z.number().min(1),
      title: z.string().min(1, i18n.t('manualSeries.titleRequired')),
      description: z.string().optional(),
      video_url: z.string().optional(),
      poster_url: z.string().optional(),
      runtime: z.number().min(1).optional()
    });

    // Extend inferred type with a few optional backend fields we sometimes map
    type Episode = z.infer<typeof episodeSchema> & {
      image_url?: string;
      has_subtitles?: boolean;
    };

    interface Season {
      id?: number;
      season_number: number;
      title: string;
      description?: string;
      poster_url?: string;
      episodes: Episode[];
    }

    interface EpisodesManagementDialogProps {
      isOpen: boolean;
      onClose: () => void;
      series: Content;
      onSuccess: () => void;
    }

    export default function EpisodesManagementDialog({
      isOpen,
      onClose,
      series,
      onSuccess }: EpisodesManagementDialogProps) {
      const nsLoading = useLoadNamespace('admin/episodes');
      const [seasons, setSeasons] = useState<Season[]>([]);
      const [activeSeasonTab, setActiveSeasonTab] = useState('0');
      const [isLoading, setIsLoading] = useState(false);
      const { t } = useTranslation(['admin/episodes', 'admin', 'translation']);
      const [isLoadingData, setIsLoadingData] = useState(false);
      const [loadError, setLoadError] = useState<string | null>(null);
      const [isNovela] = useState(false);
      const [isPreviewOpen, setIsPreviewOpen] = useState(false);
      const [isPreviewLoading, setIsPreviewLoading] = useState(false);
      const [previewUrl, setPreviewUrl] = useState<string | null>(null);
      const [previewLicenseServerUrl, setPreviewLicenseServerUrl] = useState<string | null>(null);
      const [previewDrmType, setPreviewDrmType] = useState<string | null>(null);
      const [previewTitle, setPreviewTitle] = useState<string>('');
      const [previewPoster, setPreviewPoster] = useState<string | undefined>(undefined);
      const videoRef = React.useRef<HTMLVideoElement | null>(null);
      const lastSaveRef = React.useRef<number>(0);
      const [isTesting, setIsTesting] = useState(false);
      const [testResults, setTestResults] = useState<Array<{ id?: number; title: string; ok: boolean; error?: string }>>([]);
      const [previewError, setPreviewError] = useState<string | null>(null);

      const defaultEpisode = (num = 1): Episode => ({
        episode_number: num,
        title: t('episodes.defaultEpisodeTitle', { number: num }),
        description: '',
        video_url: '',
        poster_url: '',
        runtime: undefined
      });

      const defaultSeason = (seasonNumber = 1): Season => ({
        season_number: seasonNumber,
        title: t('episodes.defaultSeasonTitle', { number: seasonNumber }),
        description: '',
        poster_url: '',
        episodes: [defaultEpisode(1)]
      });

      const checkEpisodeSubtitles = async (episodeId: number): Promise<boolean> => {
        try {
          const result = await contentService.getEpisodeSubtitles(episodeId);
          return result.success && result.data && result.data.length > 0;
        } catch (_error) {
          return false;
        }
      };

      const loadSeriesData = useCallback(async () => {
        setIsLoadingData(true);
        setLoadError(null);
        try {
          // UNIFIED: All episodic content (series, anime) uses the same series API
          // The category_id differentiates the type, not the API endpoint
          const seriesResult = await contentService.getSeriesByContentId(series.id);

          if (!seriesResult.success) {
            throw new Error(apiErrorMessage(seriesResult.error, t('episodes.failedToLoad')));
          }

          const seriesData = seriesResult.data as Series;
          const seasonsWithEpisodes: Season[] = [];

          // UNIFIED: All episodic content uses series/seasons/episodes structure
          const seasonsResult = await contentService.getSeriesSeasons(seriesData.id);
          if (!seasonsResult.success) {
            throw new Error(apiErrorMessage(seasonsResult.error, t('episodes.failedToLoadSeasons')));
          }

          const seasonsData = (seasonsResult.data || []) as SeasonType[];

          for (const seasonData of seasonsData) {
            const episodesResult = await contentService.getSeasonEpisodes(seasonData.id);
            const episodesData = episodesResult.success ? (episodesResult.data as EpisodeType[]) : [];

            const episodes: Episode[] = await Promise.all(
              (episodesData || []).map(async (ep) => {
                const hasSubtitles = ep.id ? await checkEpisodeSubtitles(ep.id) : false;
                return {
                  id: ep.id,
                  episode_number: ep.episode_number ?? 1,
                  title: ep.title || t('episodes.untitled'),
                  description: ep.description || '',
                  video_url: ep.stream_url || '',
                  poster_url: ep.image_url || ep.poster_url || '',
                  image_url: ep.image_url || ep.poster_url || '',
                  runtime: ep.runtime || undefined,
                  has_subtitles: hasSubtitles
                };
              })
            );

            if (episodes.length === 0) {
              episodes.push(defaultEpisode(1));
            }

            seasonsWithEpisodes.push({
              id: seasonData.id,
              season_number: seasonData.season_number,
              title: (seasonData as any).title || t('episodes.defaultSeasonTitle', { number: seasonData.season_number }),
              description: (seasonData as any).description || '',
              poster_url: (seasonData as any).poster_url || '',
              episodes
            });
          }

          if (seasonsWithEpisodes.length === 0) {
            seasonsWithEpisodes.push(defaultSeason(1));
          }

          setSeasons(seasonsWithEpisodes);
          setActiveSeasonTab('0');
        } catch (_error) {
          setLoadError(t('episodes.failedToLoad')); // Generic error
          setSeasons([defaultSeason(1)]);
          setActiveSeasonTab('0');
        } finally {
          setIsLoadingData(false);
        }
      }, [series, t]);

      useEffect(() => {
        if (isOpen && series) {
          loadSeriesData();
        }
      }, [isOpen, series, loadSeriesData]);

      const handlePreviewEpisode = async (episodeId?: number, title?: string, poster?: string) => {
        if (!episodeId) return;
        setPreviewTitle(title || t('episodes.previewTitle'));
        setPreviewPoster(poster);
        setIsPreviewOpen(true);
        setIsPreviewLoading(true);
        setPreviewUrl(null);
        setPreviewLicenseServerUrl(null);
        setPreviewDrmType(null);
        setPreviewError(null);
        try {
          const result = await contentService.getEpisodeForDelivery(episodeId);
          if (result.success && result.data?.stream_url) {
            // Extract DRM info
            const dataAny = result.data as any;
            if (dataAny.license_server_url) setPreviewLicenseServerUrl(dataAny.license_server_url);
            if (dataAny.drm_type) setPreviewDrmType(dataAny.drm_type);

            const s = result.data.stream_url.trim();
            try {
              if (s.startsWith('/api/')) {
                // Pre-check HEAD
                try {
                  const head = await fetch(s, { method: 'HEAD', credentials: 'include', cache: 'no-store' });
                  if (!head.ok) {
                    setPreviewError(t('episodes.previewError'));
                  }
                } catch (e: any) {
                  setPreviewError(t('episodes.previewError'));
                }
                setPreviewUrl(s);
              } else {
                const u = new URL(s);
                if (u.pathname.startsWith('/api/')) {
                  const normalized = `${u.pathname}${u.search}${u.hash}`;
                  try {
                    const head = await fetch(normalized, { method: 'HEAD', credentials: 'include', cache: 'no-store' });
                    if (!head.ok) setPreviewError(t('episodes.previewError'));
                  } catch { }
                  setPreviewUrl(normalized);
                } else {
                  setPreviewUrl(s);
                }
              }
            } catch {
              setPreviewUrl(s);
            }
          }
        } finally {
          setIsPreviewLoading(false);
        }
      };

      const loadExternalScript = async (id: string, src: string) => {
        return new Promise<void>((resolve, reject) => {
          if (document.getElementById(id)) {
            resolve();
            return;
          }
          const s = document.createElement('script');
          s.src = src;
          s.async = true;
          s.onload = () => resolve();
          s.onerror = (e) => reject(e);
          s.id = id;
          document.body.appendChild(s);
        });
      };

      React.useEffect(() => {
        let hlsInstance: any = null;
        let shakaPlayer: any = null;
        const video = videoRef.current;
        if (!isPreviewOpen || !previewUrl || !video) return;

        const url = previewUrl;
        const lower = url.split('?')[0].toLowerCase();

        const cleanup = () => {
          try {
            if (hlsInstance) hlsInstance.destroy();
            if (shakaPlayer) shakaPlayer.destroy();
          } catch { }
        };

        const setup = async () => {
          try {
            if (lower.endsWith('.mpd')) {
              await loadExternalScript('shaka-player-lib', '/vendor/shaka-player.compiled.min.js');
              const shaka = (window as any).shaka;
              if (!shaka) {
                setPreviewError(t('episodes.previewError'));
                return;
              }
              shakaPlayer = new shaka.Player();
              await shakaPlayer.attach(video);

              // Configure DRM
              const drmConfig: any = {
                retryParameters: {
                  maxAttempts: 3,
                  baseDelay: 1000,
                  backoffFactor: 2,
                  fuzzFactor: 0.5
                }
              };

              const useWidevine = previewLicenseServerUrl && (previewDrmType === 'widevine' || !previewDrmType);
              const usePlayReady = previewLicenseServerUrl && previewDrmType === 'playready';

              if (useWidevine) {
                drmConfig.servers = { 'com.widevine.alpha': previewLicenseServerUrl };
                drmConfig.advanced = {
                  'com.widevine.alpha': {
                    videoRobustness: 'SW_SECURE_CRYPTO',
                    audioRobustness: 'SW_SECURE_CRYPTO'
                  }
                };
              } else if (usePlayReady) {
                drmConfig.servers = { 'com.microsoft.playready': previewLicenseServerUrl };
              } else {
                drmConfig.preferredKeySystems = ['org.w3.clearkey'];
              }

              shakaPlayer.configure({ drm: drmConfig });

              await shakaPlayer.load(url);
              return;
            }
            if (lower.endsWith('.m3u8')) {
              const canNative = video.canPlayType('application/vnd.apple.mpegurl');
              if (canNative) { video.src = url; return; }
              await loadExternalScript('hls-js-lib', '/vendor/hls.min.js');
              const Hls = (window as any).Hls;
              if (Hls && Hls.isSupported()) {
                hlsInstance = new Hls();
                hlsInstance.loadSource(url);
                hlsInstance.attachMedia(video);
                return;
              }
              setPreviewError(t('episodes.previewNotSupported'));
              video.src = url;
              return;
            }
            video.src = url;
          } catch (e: any) {
            setPreviewError(t('episodes.previewError'));
          }
        };

        setup().then(() => {
          // Restore volume/position
          try {
            const key = `preview_state.episode.${previewTitle}`;
            const raw = localStorage.getItem(key);
            if (raw && videoRef.current) {
              const state = JSON.parse(raw);
              if (typeof state.volume === 'number') videoRef.current.volume = Math.max(0, Math.min(1, state.volume));
              const setTime = () => {
                if (typeof state.currentTime === 'number' && state.currentTime > 1) {
                  try { if (videoRef.current) videoRef.current.currentTime = state.currentTime; } catch { }
                }
              };
              if (videoRef.current.readyState >= 1) setTime(); else videoRef.current.addEventListener('loadedmetadata', setTime, { once: true });
            }
          } catch { }
        });
        return cleanup;
      }, [isPreviewOpen, previewUrl, previewLicenseServerUrl, previewDrmType]);

      // Persist episode preview state (volume/position)
      React.useEffect(() => {
        const video = videoRef.current;
        if (!isPreviewOpen || !previewUrl || !video) return;
        const key = `preview_state.episode.${previewTitle}`;
        const onTime = () => {
          const now = Date.now();
          if (now - lastSaveRef.current < 1500) return;
          lastSaveRef.current = now;
          try {
            const raw = localStorage.getItem(key);
            const base = raw ? JSON.parse(raw) : {};
            base.currentTime = Math.floor(video.currentTime || 0);
            base.volume = video.volume;
            localStorage.setItem(key, JSON.stringify(base));
          } catch { }
        };
        const onVolume = () => {
          try {
            const raw = localStorage.getItem(key);
            const base = raw ? JSON.parse(raw) : {};
            base.volume = video.volume;
            localStorage.setItem(key, JSON.stringify(base));
          } catch { }
        };
        const onError = () => {
          try {
            const err = (video.error && (video.error as any).message) || t('user.live.playbackError');
            setPreviewError(String(err));
          } catch { }
        };
        video.addEventListener('timeupdate', onTime);
        video.addEventListener('volumechange', onVolume);
        video.addEventListener('error', onError);
        return () => {
          video.removeEventListener('timeupdate', onTime);
          video.removeEventListener('volumechange', onVolume);
          video.removeEventListener('error', onError);
        };
      }, [isPreviewOpen, previewUrl, previewTitle]);

      const addSeason = () => {
        const newSeasonNumber = seasons.length + 1;
        const newSeason: Season = defaultSeason(newSeasonNumber);
        setSeasons([...seasons, newSeason]);
        setActiveSeasonTab((seasons.length).toString());
      };

      const removeSeason = (seasonIndex: number) => {
        if (seasons.length > 1) {
          const updatedSeasons = seasons.filter((_, index) => index !== seasonIndex);
          setSeasons(updatedSeasons);
          if (parseInt(activeSeasonTab) >= updatedSeasons.length) {
            setActiveSeasonTab('0');
          }
        }
      };

      const updateSeason = (seasonIndex: number, updatedSeason: Season) => {
        const updatedSeasons = [...seasons];
        updatedSeasons[seasonIndex] = updatedSeason;
        setSeasons(updatedSeasons);
      };

      const addEpisode = (seasonIndex: number) => {
        const updatedSeasons = [...seasons];
        const currentEpisodes = updatedSeasons[seasonIndex].episodes;
        const newEpisodeNumber = currentEpisodes.length + 1;
        const newEpisode: Episode = defaultEpisode(newEpisodeNumber);
        updatedSeasons[seasonIndex].episodes.push(newEpisode);
        setSeasons(updatedSeasons);
      };

      const removeEpisode = (seasonIndex: number, episodeIndex: number) => {
        const updatedSeasons = [...seasons];
        updatedSeasons[seasonIndex].episodes = updatedSeasons[seasonIndex].episodes.filter(
          (_, index) => index !== episodeIndex
        );
        setSeasons(updatedSeasons);
      };

      const updateEpisode = (seasonIndex: number, episodeIndex: number, updatedEpisode: Episode) => {
        const updatedSeasons = [...seasons];
        updatedSeasons[seasonIndex].episodes[episodeIndex] = updatedEpisode;
        setSeasons(updatedSeasons);
      };

      const handleSave = async () => {
        try {
          setIsLoading(true);
          const updatePromises: Promise<any>[] = [];

          for (const season of seasons) {
            for (const episode of season.episodes) {
              if (episode.id) {
                const updatePromise = contentService.updateEpisode(episode.id, {
                  title: episode.title,
                  description: episode.description,
                  stream_url: episode.video_url,
                  image_url: episode.poster_url
                });

                updatePromises.push(updatePromise);
              }
            }
          }

          await Promise.all(updatePromises);
          onSuccess();
          onClose();
        } catch (error) {
          console.error('Error saving episodes:', error);
        } finally {
          setIsLoading(false);
        }
      };

      return (
        <Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose(); }}>
          <DialogContent className="!max-w-[65vw] !w-[65vw] max-h-[75vh] overflow-y-auto sm:!max-w-[65vw] md:!max-w-[65vw] lg:!max-w-[65vw]" style={{ width: '65vw', maxWidth: '65vw' }}>
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                📺 {t('episodes.manageTitle', { title: series.title })}
              </DialogTitle>
            </DialogHeader>

            {nsLoading ? (
              <div className="flex items-center justify-center p-8">
                <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
                <span className="ml-2">{t('common.loading', { defaultValue: 'Loading...' })}</span>
              </div>
            ) : (
              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">{series.title}</CardTitle>
                    <CardDescription>
                      {series.description || t('episodes.noDescription')}
                    </CardDescription>
                  </CardHeader>
                </Card>

                {/* Preview Dialog */}
                <Dialog open={isPreviewOpen} onOpenChange={(open) => { if (!open) { setIsPreviewOpen(false); setPreviewUrl(null); } }}>
                  <DialogContent className="max-w-3xl">
                    <DialogHeader>
                      <DialogTitle>{previewTitle}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      {isPreviewLoading && (
                        <div className="flex h-64 items-center justify-center">
                          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-500" />
                        </div>
                      )}
                      {!isPreviewLoading && previewError && (
                        <div className="rounded border border-red-800 bg-red-950/40 p-3 text-sm text-red-300">
                          {previewError}
                        </div>
                      )}
                      {!isPreviewLoading && previewUrl && (
                        <video
                          key={previewUrl}
                          controls
                          autoPlay
                          playsInline
                          className="w-full max-h-[70vh] rounded bg-black"
                          poster={previewPoster}
                          ref={videoRef}
                        >
                          <source src={previewUrl} />
                        </video>
                      )}
                    </div>
                  </DialogContent>
                </Dialog>

                {isLoadingData && (
                  <Card>
                    <CardContent className="p-6">
                      <div className="flex items-center justify-center space-x-2">
                        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                        <span>{t('episodes.loadingSeasons')}</span>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {loadError && (
                  <Card>
                    <CardContent className="p-6">
                      <div className="flex items-center space-x-2 text-red-600">
                        <AlertCircle className="h-5 w-5" />
                        <span>{t('episodes.errorLoadingData')}: {loadError}</span>
                      </div>
                    </CardContent>
                  </Card>
                )}

                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>{t('episodes.seasonsAndEpisodes')}</CardTitle>
                        <CardDescription>
                          {t('episodes.manageSeasonsDescription')}
                        </CardDescription>
                      </div>
                      <div className="flex gap-2">
                        <Button onClick={async () => {
                          // Test all episodes in active season
                          const idx = parseInt(activeSeasonTab || '0', 10) || 0;
                          if (!seasons[idx]) return;
                          setIsTesting(true);
                          setTestResults([]);
                          const current = seasons[idx];
                          const results: Array<{ id?: number; title: string; ok: boolean; error?: string }> = [];
                          for (const ep of current.episodes) {
                            if (!ep.id) {
                              results.push({ id: undefined, title: ep.title, ok: false, error: t('common.error') });
                              continue;
                            }
                            try {
                              const res = await contentService.getEpisodeForDelivery(ep.id);
                              if (res.success && res.data?.stream_url) {
                                results.push({ id: ep.id, title: ep.title, ok: true });
                              } else {
                                results.push({ id: ep.id, title: ep.title, ok: false, error: res.error?.details || t('episodes.noUrl') });
                              }
                            } catch (_error) {
                              const errorMessage = _error instanceof Error ? _error.message : t('common.error');
                              results.push({ id: ep.id, title: ep.title, ok: false, error: errorMessage });
                            }
                          }
                          setTestResults(results);
                          setIsTesting(false);
                        }} variant="outline" size="sm" disabled={isLoadingData || isTesting} className="bg-blue-50 hover:bg-blue-100 border-blue-200 text-blue-700">
                          {isTesting ? (
                            <>
                              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
                              Probando...
                            </>
                          ) : (
                            <>
                              🧪 {t('episodes.testAll')}
                            </>
                          )}
                        </Button>
                        <Button onClick={loadSeriesData} variant="outline" size="sm" disabled={isLoadingData}>
                          🔄 {t('common.reload')}
                        </Button>
                        <Button onClick={addSeason} variant="outline">
                          <Plus className="h-4 w-4 mr-2" />
                          {t('episodes.addSeason')}
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    {testResults.length > 0 && (
                      <div className="mb-4 rounded-lg border border-blue-200 bg-gradient-to-r from-blue-50 to-indigo-50 p-4 shadow-sm">
                        <div className="text-sm font-semibold mb-3 text-blue-800 flex items-center">
                          📊 {t('episodes.testResults')}
                          <Badge variant="outline" className="ml-2 bg-white">
                            {testResults.filter(r => r.ok).length}/{testResults.length}
                          </Badge>
                        </div>
                        <div className="space-y-2 max-h-48 overflow-y-auto">
                          {testResults.map((r, i) => (
                            <div key={i} className={`flex items-center gap-2 p-2 rounded text-sm ${r.ok ? 'bg-green-100 text-green-800 border border-green-200' : 'bg-red-100 text-red-800 border border-red-200'}`}>
                              <span className="text-lg">{r.ok ? '✅' : '❌'}</span>
                              <span className="font-medium">{r.title || t('episodes.untitled')}</span>
                              {r.error && <span className="text-xs opacity-75">— {r.error}</span>}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                    {!isLoadingData && seasons.length > 0 && (
                      <Tabs value={activeSeasonTab} onValueChange={setActiveSeasonTab}>
                        <div className="w-full">
                          <TabsList className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-1 p-1 h-auto">
                            {seasons.map((season, index) => (
                              <TabsTrigger key={index} value={index.toString()} className="flex flex-col items-center gap-1 p-2 h-auto min-h-[60px] text-xs">
                                <span className="font-medium text-xs leading-tight text-center">{t('episodes.seasonLabel', { number: season.season_number })}</span>
                                <Badge variant="outline" className="text-xs px-1 py-0">
                                  {season.episodes.length} {t('episodes.epShort')}
                                </Badge>
                              </TabsTrigger>
                            ))}
                          </TabsList>
                        </div>

                        {seasons.map((season, seasonIndex) => (
                          <TabsContent key={seasonIndex} value={seasonIndex.toString()} className="mt-6">
                            <div className="space-y-6">
                              <SeasonEditor
                                season={season}
                                seasonIndex={seasonIndex}
                                onUpdateSeason={(updatedSeason) => updateSeason(seasonIndex, updatedSeason)}
                                onAddEpisode={() => addEpisode(seasonIndex)}
                                onRemoveEpisode={(episodeIndex) => removeEpisode(seasonIndex, episodeIndex)}
                                onUpdateEpisode={(episodeIndex, updatedEpisode) =>
                                  updateEpisode(seasonIndex, episodeIndex, updatedEpisode)
                                }
                                onRemoveSeason={() => removeSeason(seasonIndex)}
                                canRemoveSeason={seasons.length > 1}
                                isNovela={isNovela}
                                onPreviewEpisode={handlePreviewEpisode}
                              />
                            </div>
                          </TabsContent>
                        ))}
                      </Tabs>
                    )}

                    {!isLoadingData && seasons.length === 0 && (
                      <div className="text-center py-8">
                        <div className="text-gray-500 mb-4">
                          <Play className="h-12 w-12 mx-auto mb-2 opacity-50" />
                          <p>{t('episodes.noSeasonsFound')}</p>
                          <p className="text-sm">{t('episodes.addFirstSeasonHint')}</p>
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>

                <div className="flex justify-end gap-2">
                  <Button variant="outline" onClick={onClose}>
                    {t('common.cancel')}
                  </Button>
                  <Button onClick={handleSave} disabled={isLoading}>
                    <Save className="h-4 w-4 mr-2" />
                    {isLoading ? t('common.saving') : t('common.save')}
                  </Button>
                </div>
              </div>
            )}
          </DialogContent>
        </Dialog>
      );
    }

    // Season Editor Component
    interface SeasonEditorProps {
      season: Season;
      seasonIndex: number;
      onUpdateSeason: (season: Season) => void;
      onAddEpisode: () => void;
      onRemoveEpisode: (episodeIndex: number) => void;
      onUpdateEpisode: (episodeIndex: number, episode: Episode) => void;
      onRemoveSeason: () => void;
      canRemoveSeason: boolean;
      isNovela: boolean;
      onPreviewEpisode: (episodeId?: number, title?: string, poster?: string) => void;
    }

    function SeasonEditor({
      season,
      seasonIndex,
      onUpdateSeason,
      onAddEpisode,
      onRemoveEpisode,
      onUpdateEpisode,
      onRemoveSeason,
      canRemoveSeason,
      isNovela,
      onPreviewEpisode }: SeasonEditorProps) {
      const { t } = useTranslation(['admin/episodes', 'admin', 'translation']);

      const updateSeasonField = (field: keyof Season, value: string | number | Episode[] | undefined) => {
        onUpdateSeason({
          ...season,
          [field]: value
        });
      };

      return (
        <div className="space-y-6">
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <Label htmlFor={`season_title_${seasonIndex}`}>{t('episodes.seasonTitle')}</Label>
              <Input
                id={`season_title_${seasonIndex}`}
                value={season.title}
                onChange={(e) => updateSeasonField('title', e.target.value)}
                placeholder={t('episodes.defaultSeasonPlaceholder')}
              />
            </div>
            <div>
              <Label htmlFor={`season_number_${seasonIndex}`}>{t('episodes.seasonNumber')}</Label>
              <Input
                id={`season_number_${seasonIndex}`}
                type="number"
                value={season.season_number}
                onChange={(e) => updateSeasonField('season_number', parseInt(e.target.value))}
                min="1"
              />
            </div>
          </div>

          <div>
            <Label htmlFor={`season_description_${seasonIndex}`}>{t('episodes.description')}</Label>
            <Textarea
              id={`season_description_${seasonIndex}`}
              value={season.description || ''}
              onChange={(e) => updateSeasonField('description', e.target.value)}
              placeholder={t('episodes.seasonDescriptionPlaceholder')}
              rows={2}
            />
          </div>

          <div>
            <Label htmlFor={`season_poster_${seasonIndex}`}>{t('episodes.posterUrl')}</Label>
            <Input
              id={`season_poster_${seasonIndex}`}
              value={season.poster_url || ''}
              onChange={(e) => updateSeasonField('poster_url', e.target.value)}
              placeholder={t('createContent.form.posterUrlPlaceholder', { ns: 'translation' })}
            />
          </div>

          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h4 className="font-medium">{t('episodes.episodesCount', { count: season.episodes.length })}</h4>
              <div className="flex gap-2">
                <Button onClick={onAddEpisode} variant="outline" size="sm">
                  <Plus className="h-4 w-4 mr-2" />
                  {t('episodes.addEpisode')}
                </Button>
                {canRemoveSeason && (
                  <Button onClick={onRemoveSeason} variant="destructive" size="sm">
                    <Trash2 className="h-4 w-4 mr-2" />
                    {t('episodes.removeSeason')}
                  </Button>
                )}
              </div>
            </div>

            <EpisodesList
              episodes={season.episodes}
              seasonIndex={seasonIndex}
              onRemoveEpisode={onRemoveEpisode}
              onUpdateEpisode={onUpdateEpisode}
              isNovela={isNovela}
              onPreviewEpisode={onPreviewEpisode}
            />
          </div>
        </div>
      );
    }

    // Episodes List Component
    interface EpisodesListProps {
      episodes: Episode[];
      seasonIndex: number;
      onRemoveEpisode: (episodeIndex: number) => void;
      onUpdateEpisode: (episodeIndex: number, episode: Episode) => void;
      isNovela: boolean;
      onPreviewEpisode: (episodeId?: number, title?: string, poster?: string) => void;
    }

    function EpisodesList({
      episodes,
      seasonIndex,
      onRemoveEpisode,
      onUpdateEpisode,
      isNovela,
      onPreviewEpisode }: EpisodesListProps) {
      const { t } = useTranslation(['admin/episodes', 'admin', 'translation']);

      return (
        <Accordion type="single" collapsible className="w-full">
          {episodes.map((episode, episodeIndex) => (
            <AccordionItem key={episodeIndex} value={`episode-${episodeIndex}`}>
              <AccordionTrigger className="text-left">
                <div className="flex items-center justify-between w-full mr-4">
                  <span>{t('episodes.episodeLabel', { number: episode.episode_number })}: {episode.title || t('episodes.untitled')}</span>
                  <div className="flex items-center gap-2">
                    <Badge variant={episode.video_url ? 'default' : 'secondary'} className="text-xs">
                      {episode.video_url ? t('episodes.urlSet') : t('episodes.noUrl')}
                    </Badge>
                    {episode.has_subtitles && (
                      <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">
                        SUB
                      </Badge>
                    )}
                    {episode.video_url && (
                      <Tooltip content={t('admin.content.actions.preview')}>
                        <span
                          role="button"
                          tabIndex={0}
                          className="inline-flex items-center justify-center rounded border border-slate-700 bg-slate-900 px-2 py-1 text-xs text-slate-200 hover:bg-slate-800 cursor-pointer"
                          onClick={(e) => { e.stopPropagation(); onPreviewEpisode(episode.id, episode.title, episode.poster_url || episode.image_url); }}
                          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onPreviewEpisode(episode.id, episode.title, episode.poster_url || episode.image_url); } }}
                        >
                          <Play className="h-4 w-4 text-green-500" />
                        </span>
                      </Tooltip>
                    )}
                  </div>
                </div>
              </AccordionTrigger>
              <AccordionContent>
                <EpisodeEditor
                  episode={episode}
                  episodeIndex={episodeIndex}
                  seasonIndex={seasonIndex}
                  onUpdateEpisode={(updatedEpisode) => onUpdateEpisode(episodeIndex, updatedEpisode)}
                  onRemoveEpisode={() => onRemoveEpisode(episodeIndex)}
                  isNovela={isNovela}
                  onPreviewEpisode={(id, title, poster) => onPreviewEpisode(id, title, poster)}
                />
              </AccordionContent>
            </AccordionItem>
          ))}
        </Accordion>
      );
    }

    // Episode Editor Component
    interface EpisodeEditorProps {
      episode: Episode;
      episodeIndex: number;
      seasonIndex: number;
      onUpdateEpisode: (episode: Episode) => void;
      onRemoveEpisode: () => void;
      isNovela: boolean;
      onPreviewEpisode: (episodeId?: number, title?: string, poster?: string) => void;
    }

    function EpisodeEditor({
      episode,
      episodeIndex,
      seasonIndex,
      onUpdateEpisode,
      onRemoveEpisode,
      isNovela,
      onPreviewEpisode }: EpisodeEditorProps) {
      const [decryptedUrl, setDecryptedUrl] = React.useState<string>('');
      const [isLoadingUrl, setIsLoadingUrl] = React.useState(false);
      const [subtitleTracks, setSubtitleTracks] = React.useState<Array<{
        id: number;
        language: string;
        label?: string;
        url?: string;
      }>>([]);
      const [subtitleLanguage, setSubtitleLanguage] = React.useState('en');
      const [subtitleFile, setSubtitleFile] = React.useState<File | null>(null);
      const [isUploadingSubtitle, setIsUploadingSubtitle] = React.useState(false);
      const [deletingSubtitleId, setDeletingSubtitleId] = React.useState<number | null>(null);
      const subtitleFileInputRef = React.useRef<HTMLInputElement | null>(null);
      const { t } = useTranslation(['admin/episodes', 'admin', 'translation']);

      React.useEffect(() => {
        // Only load decrypted URL if we have an ID (existing episode)
        // For new episodes, we just use the video_url from props
        let isActive = true;

        const loadDecryptedUrl = async () => {
          if (episode.id) {
            setIsLoadingUrl(true);
            try {
              const result = await contentService.getEpisodeForEditing(episode.id);
              if (isActive) {
                if (result.success && result.data?.stream_url) {
                  setDecryptedUrl(result.data.stream_url);
                } else {
                  setDecryptedUrl(episode.video_url || '');
                }
              }
            } catch (error) {
              console.error('Error loading decrypted URL:', error);
              if (isActive) setDecryptedUrl(episode.video_url || '');
            } finally {
              if (isActive) setIsLoadingUrl(false);
            }
          } else {
            // Only update if it differs significantly to avoid cursor jumps,
            // but ideally we rely on local state for typing.
            // Here we just sync initial or external changes.
            if (episode.video_url !== decryptedUrl) {
              setDecryptedUrl(episode.video_url || '');
            }
          }
        };

        // We intentionally omit episode.video_url from deps to avoid circular loop while typing
        // We only want to re-load if the episode ID changes (switching episodes)
        loadDecryptedUrl();

        return () => { isActive = false; };
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [episode.id]);

      const loadEpisodeSubtitles = React.useCallback(async (): Promise<number> => {
        if (!episode.id) {
          setSubtitleTracks([]);
          return 0;
        }

        const result = await contentService.getEpisodeSubtitles(episode.id);
        if (result.success && Array.isArray(result.data)) {
          const tracks = result.data.map((track) => ({
            id: Number(track.id),
            language: String(track.language || '').toUpperCase(),
            label: track.label,
            url: track.url
          }));
          setSubtitleTracks(tracks);
          return tracks.length;
        }

        setSubtitleTracks([]);
        return 0;
      }, [episode.id]);

      React.useEffect(() => {
        loadEpisodeSubtitles().catch(() => {
          setSubtitleTracks([]);
        });
      }, [loadEpisodeSubtitles]);

      const handleUploadSubtitle = async () => {
        if (!episode.id || !subtitleFile || !subtitleLanguage.trim()) return;

        setIsUploadingSubtitle(true);
        const result = await contentService.uploadEpisodeSubtitle(
          episode.id,
          subtitleFile,
          subtitleLanguage
        );
        setIsUploadingSubtitle(false);

        if (!result.success) {
          toast.error(apiErrorMessage(result.error, t('episodes.subtitleUploadFailed')));
          return;
        }

        toast.success(t('episodes.subtitleUploaded'));
        setSubtitleFile(null);
        if (subtitleFileInputRef.current) {
          subtitleFileInputRef.current.value = '';
        }
        const count = await loadEpisodeSubtitles();
        updateEpisodeField('has_subtitles', count > 0);
      };

      const handleDeleteSubtitle = async (subtitleId: number) => {
        if (!episode.id) return;

        setDeletingSubtitleId(subtitleId);
        const result = await contentService.deleteEpisodeSubtitle(episode.id, subtitleId);
        setDeletingSubtitleId(null);

        if (!result.success) {
          toast.error(apiErrorMessage(result.error, t('episodes.subtitleDeleteFailed')));
          return;
        }

        toast.success(t('episodes.subtitleDeleted'));
        const count = await loadEpisodeSubtitles();
        updateEpisodeField('has_subtitles', count > 0);
      };

      const updateEpisodeField = (
        field: keyof Episode,
        value: string | number | boolean | undefined
      ) => {
        onUpdateEpisode({
          ...episode,
          [field]: value
        });
      };

      return (
        <div className="space-y-4 pt-4">
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <Label htmlFor={`episode_title_${seasonIndex}_${episodeIndex}`}>{t('episodes.episodeTitle')}</Label>
              <Input
                id={`episode_title_${seasonIndex}_${episodeIndex}`}
                value={episode.title}
                onChange={(e) => updateEpisodeField('title', e.target.value)}
                placeholder={t('episodes.defaultEpisodeTitle', { number: episode.episode_number })}
              />
            </div>
            <div>
              <Label htmlFor={`episode_number_${seasonIndex}_${episodeIndex}`}>{t('episodes.episodeNumber')}</Label>
              <Input
                id={`episode_number_${seasonIndex}_${episodeIndex}`}
                type="number"
                value={episode.episode_number}
                onChange={(e) => updateEpisodeField('episode_number', parseInt(e.target.value))}
                min="1"
              />
            </div>
          </div>

          <div>
            <Label htmlFor={`episode_description_${seasonIndex}_${episodeIndex}`}>{t('episodes.description')}</Label>
            <Textarea
              id={`episode_description_${seasonIndex}_${episodeIndex}`}
              value={episode.description || ''}
              onChange={(e) => updateEpisodeField('description', e.target.value)}
              placeholder={t('episodes.episodeDescriptionPlaceholder')}
              rows={2}
            />
          </div>

          <div>
            <Label htmlFor={`episode_video_url_${seasonIndex}_${episodeIndex}`}>
              {t('episodes.videoUrlLabel')} <span className="text-sm text-gray-500 ml-2">({t('episodes.videoExamples')})</span>
            </Label>
            <VideoUploadField
              value={decryptedUrl}
              onChange={(val) => {
                setDecryptedUrl(val);
                updateEpisodeField('video_url', val);
              }}
              onUpload={async (file) => {
                if (!episode.id) return '';
                const result = await contentService.uploadEpisodeVideo(episode.id, file);
                if (result.success && result.data) {
                  return result.data.path;
                }
                throw new Error(result.error?.details || 'Upload failed');
              }}
              uploadId={episode.id}
              disabled={isLoadingUrl || !episode.id}
              placeholder={t('createContent.form.videoUrlPlaceholder', { ns: 'translation' })}
              className={`text-lg p-0 ${decryptedUrl ? 'border-green-300' : 'border-red-300'}`} // p-0 to let internal input handle padding if needed, or adjust
            />
            {isLoadingUrl && (
              <p className="text-sm text-gray-500 mt-1">🔓 {t('episodes.decrypting')}</p>
            )}
          </div>

          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <Label htmlFor={`episode_poster_${seasonIndex}_${episodeIndex}`}>{t('episodes.posterUrl')}</Label>
              <Input
                id={`episode_poster_${seasonIndex}_${episodeIndex}`}
                value={episode.poster_url || ''}
                onChange={(e) => updateEpisodeField('poster_url', e.target.value)}
                placeholder={t('createContent.form.posterUrlPlaceholder', { ns: 'translation' })}
              />
            </div>
            <div>
              <Label htmlFor={`episode_runtime_${seasonIndex}_${episodeIndex}`}>{t('episodes.runtimeMinutes')}</Label>
              <Input
                id={`episode_runtime_${seasonIndex}_${episodeIndex}`}
                type="number"
                value={episode.runtime || ''}
                onChange={(e) => updateEpisodeField('runtime', e.target.value ? parseInt(e.target.value) : undefined)}
                placeholder="45"
                min="1"
              />
            </div>
          </div>

          <div className="rounded-md border p-3 bg-muted/20 space-y-3">
            <div className="flex items-center justify-between">
              <Label className="text-sm font-medium">{t('episodes.externalSubtitles')}</Label>
              <Badge variant="outline">{subtitleTracks.length}</Badge>
            </div>

            {subtitleTracks.length === 0 ? (
              <p className="text-xs text-muted-foreground">{t('episodes.noSubtitlesForEpisode')}</p>
            ) : (
              <div className="flex flex-wrap gap-2">
                {subtitleTracks.map((track) => (
                  <div
                    key={track.id}
                    className="inline-flex items-center gap-1 rounded border px-2 py-1 text-xs bg-white"
                  >
                    {track.url ? (
                      <a
                        href={track.url}
                        target="_blank"
                        rel="noreferrer"
                        className="font-mono hover:text-primary transition"
                      >
                        {track.language}
                      </a>
                    ) : (
                      <span className="font-mono">{track.language}</span>
                    )}
                    <button
                      type="button"
                      className="text-red-600 hover:text-red-700 disabled:opacity-50"
                      disabled={deletingSubtitleId === track.id}
                      onClick={() => handleDeleteSubtitle(track.id)}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                ))}
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-[130px_1fr_auto] gap-2 items-end">
              <div>
                <Label htmlFor={`episode_subtitle_language_${seasonIndex}_${episodeIndex}`}>{t('common.language')}</Label>
                <Input
                  id={`episode_subtitle_language_${seasonIndex}_${episodeIndex}`}
                  value={subtitleLanguage}
                  onChange={(e) => setSubtitleLanguage(e.target.value.trim().toLowerCase())}
                  placeholder={t('episodes.subtitleLanguagePlaceholder')}
                  maxLength={16}
                />
              </div>
              <div>
                <Label htmlFor={`episode_subtitle_file_${seasonIndex}_${episodeIndex}`}>{t('episodes.subtitleFileLabel')}</Label>
                <Input
                  id={`episode_subtitle_file_${seasonIndex}_${episodeIndex}`}
                  ref={subtitleFileInputRef}
                  type="file"
                  accept=".srt,.vtt,text/vtt,application/x-subrip"
                  onChange={(e) => setSubtitleFile(e.target.files?.[0] ?? null)}
                  disabled={!episode.id}
                />
              </div>
              <div className="flex flex-col gap-1">
                <Button
                  type="button"
                  onClick={handleUploadSubtitle}
                  disabled={!episode.id || isUploadingSubtitle || !subtitleFile || !subtitleLanguage.trim()}
                >
                  {isUploadingSubtitle ? t('common.uploading') : t('episodes.uploadSubtitle')}
                </Button>
                {!episode.id && (
                  <span className="text-[10px] text-muted-foreground text-center leading-tight">
                    {t('episodes.saveFirstToUpload', { defaultValue: 'Save episode first to upload subtitles' })}
                  </span>
                )}
              </div>
            </div>
          </div>

          <div className="flex justify-between items-center">
            <Button
              type="button"
              variant="outline"
              size="sm"
              disabled={!episode.id}
              onClick={() => onPreviewEpisode(episode.id, episode.title, episode.poster_url || episode.image_url)}
            >
              <Play className="h-4 w-4 mr-2" />
              {t('admin.content.actions.preview')}
            </Button>
            <Button onClick={onRemoveEpisode} variant="destructive" size="sm">
              <Trash2 className="h-4 w-4 mr-2" />
              {t('episodes.removeEpisode')}
            </Button>
          </div>
        </div>
      );
    }