import React, {useCallback, useEffect, useRef, useState} from 'react';
import {
  ActivityIndicator,
  Alert,
  BackHandler,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  ToastAndroid,
  View,
} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../components/common/TVTouchable';
import {RouteProp, useNavigation, useRoute} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {RootStackParamList} from '../navigation/types';
import {addonManager} from '../api/addonManager';
import {
  AddonManifest,
  AddonStreamResult,
  MetaDetail,
  Stream,
  Video,
} from '../api/addonTypes';
import {colors, typography} from '../utils/colors';
import {IS_TV} from '../utils/tv';
import {useLibraryStore} from '../store/libraryStore';
import {useSettingsStore} from '../store/settingsStore';
import {createDebridService} from '../utils/debridService';
import {
  startTorrentStream,
  stopTorrentStream,
  isTorrentStreamAvailable,
  TorrentProgress,
  preloadTorrent,
  playPreloadedTorrent,
  cancelPreload,
} from '../utils/torrentStreamService';
import {useWatchLaterStore} from '../store/watchLaterStore';
import DetailHero from '../components/detail/DetailHero';
import EpisodeList from '../components/detail/EpisodeList';
import StreamItem from '../components/detail/StreamItem';
import CastRow from '../components/detail/CastRow';
import LoadingSpinner from '../components/common/LoadingSpinner';

type Nav = StackNavigationProp<RootStackParamList>;
type Route = RouteProp<RootStackParamList, 'Detail'>;

type Tab = 'overview' | 'streams' | 'episodes';

export default function DetailScreen() {
  const navigation = useNavigation<Nav>();
  const route = useRoute<Route>();
  const {id, type, name: routeName, poster: routePoster} = route.params;

  const [meta, setMeta] = useState<MetaDetail | null>(null);
  const [streamResults, setStreamResults] = useState<AddonStreamResult[]>([]);
  const [metaLoading, setMetaLoading] = useState(true);
  const [streamsLoading, setStreamsLoading] = useState(true);
  const [resolvingStream, setResolvingStream] = useState(false);
  const [resolvingLabel, setResolvingLabel] = useState('');
  const [torrentProgress, setTorrentProgress] = useState<TorrentProgress | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>('overview');
  const [selectedEpisode, setSelectedEpisode] = useState<Video | null>(null);
  const userChangedTab = useRef(false);
  const cancelStreamRef = useRef<(() => void) | null>(null);

  const {addToWatchlist, removeFromWatchlist, toggleFavorite, getItem} =
    useLibraryStore();
  const libraryItem = getItem(id);
  const {debridProvider, realDebridKey, allDebridKey} = useSettingsStore();
  const watchLater = useWatchLaterStore();

  const isMovie = type === 'movie';

  // Handle hardware Back button — cancel resolving overlay if active
  useEffect(() => {
    const handler = BackHandler.addEventListener('hardwareBackPress', () => {
      if (resolvingStream) {
        stopTorrentStream();
        setResolvingStream(false);
        setTorrentProgress(null);
        return true; // consumed — don't navigate back
      }
      return false; // let React Navigation handle it
    });
    return () => handler.remove();
  }, [resolvingStream]);

  useEffect(() => {
    setMetaLoading(true);
    addonManager
      .getMetaFromFirst(type, id)
      .then(m => {
        setMeta(m);
        setMetaLoading(false);
        if (m?.type === 'series' && m.videos && m.videos.length > 0) {
          setActiveTab('episodes');
        }
      })
      .catch(() => setMetaLoading(false));

    // For movies, fetch streams immediately.
    // For series, streams are fetched per-episode (many addons like Torrentio
    // only return results for episode-specific IDs like tt123:1:1).
    if (type === 'movie') {
      if (cancelStreamRef.current) cancelStreamRef.current();
      setStreamResults([]);
      setStreamsLoading(true);
      cancelStreamRef.current = addonManager.streamStreamsFromAll(
        type,
        id,
        result => setStreamResults(prev => [...prev, result]),
        () => setStreamsLoading(false),
      );
    } else {
      setStreamsLoading(false);
    }

    return () => {
      if (cancelStreamRef.current) cancelStreamRef.current();
    };
  }, [id, type]);

  // Auto-switch to Streams tab for movies when streams load (if user hasn't manually changed tabs)
  useEffect(() => {
    if (
      isMovie &&
      !streamsLoading &&
      streamResults.some(r => r.streams.length > 0) &&
      !userChangedTab.current
    ) {
      setActiveTab('streams');
    }
  }, [isMovie, streamsLoading, streamResults]);

  const handleTabPress = useCallback((tab: Tab) => {
    userChangedTab.current = true;
    setActiveTab(tab);
  }, []);

  const handlePlayStream = useCallback(
    async (stream: Stream, addon: AddonManifest) => {
      const playerParams = {
        id,
        type,
        name: meta?.name ?? routeName ?? '',
        poster: meta?.poster ?? routePoster,
        ...(selectedEpisode
          ? {
              videoId: selectedEpisode.id,
              season: selectedEpisode.season,
              episode: selectedEpisode.episode,
            }
          : {}),
      };

      // Direct URL — play immediately
      if (stream.url) {
        navigation.navigate('Player', {...playerParams, stream});
        return;
      }

      // Torrent stream (infoHash only)
      if (stream.infoHash) {
        // 1) Check preloaded first — highest priority (already downloaded)
        const preloaded = watchLater.getItem(stream.infoHash);
        if (preloaded && preloaded.status !== 'error') {
          setResolvingLabel(
            preloaded.status === 'ready'
              ? 'Starting playback…'
              : 'Preparing stream…',
          );
          setResolvingStream(true);
          try {
            const result = await playPreloadedTorrent(stream.infoHash);
            setResolvingStream(false);
            navigation.navigate('Player', {
              ...playerParams,
              stream: {...stream, url: result.url},
            });
          } catch (e) {
            setResolvingStream(false);
            Alert.alert('Play Error', `Could not play torrent: ${String(e)}`);
          }
          return;
        }

        // 2) Try debrid service
        const apiKey =
          debridProvider === 'realdebrid'
            ? realDebridKey
            : debridProvider === 'alldebrid'
            ? allDebridKey
            : '';

        const debrid = createDebridService({
          provider: debridProvider,
          apiKey,
        });

        if (debrid && apiKey) {
          setResolvingLabel('Resolving stream via debrid…');
          setResolvingStream(true);
          try {
            const resolvedUrl = await debrid.resolveStream(
              stream.infoHash,
              stream.fileIdx,
            );
            setResolvingStream(false);
            navigation.navigate('Player', {
              ...playerParams,
              stream: {...stream, url: resolvedUrl},
            });
          } catch (e) {
            setResolvingStream(false);
            Alert.alert(
              'Debrid Error',
              `Could not resolve stream: ${String(e)}`,
            );
          }
          return;
        }

        // 3) Try local torrent streaming (live download + play)
        if (isTorrentStreamAvailable()) {
          setResolvingLabel('');
          setResolvingStream(true);
          setTorrentProgress({progress: 0, seeds: 0, downloadSpeed: 0, bufferProgress: 0, status: 'resolving'});
          try {
            const result = await startTorrentStream(
              stream.infoHash,
              p => setTorrentProgress(p),
            );
            setResolvingStream(false);
            setTorrentProgress(null);
            navigation.navigate('Player', {
              ...playerParams,
              stream: {...stream, url: result.url},
            });
          } catch (e) {
            setResolvingStream(false);
            setTorrentProgress(null);
            Alert.alert(
              'Torrent Error',
              `Could not stream torrent: ${String(e)}`,
            );
          }
          return;
        }

        // 4) No debrid and no local torrent support
        Alert.alert(
          'Torrent Stream',
          'This is a torrent stream. To play it, configure a debrid service (Real-Debrid or AllDebrid) in Settings.',
          [
            {text: 'Cancel', style: 'cancel'},
            {
              text: 'Open Settings',
              onPress: () => navigation.navigate('Settings'),
            },
          ],
        );
        return;
      }

      // External-only stream
      Alert.alert('External Stream', 'This stream requires an external app.', [
        {text: 'OK'},
      ]);
    },
    [
      id,
      type,
      meta,
      routeName,
      routePoster,
      navigation,
      debridProvider,
      realDebridKey,
      allDebridKey,
      watchLater,
      selectedEpisode,
    ],
  );

  const handlePlayEpisode = useCallback(
    (video: Video, stream: Stream, addon: AddonManifest) => {
      navigation.navigate('Player', {
        id,
        type,
        name: meta?.name ?? routeName ?? '',
        stream,
        videoId: video.id,
        season: video.season,
        episode: video.episode,
        poster: meta?.poster ?? routePoster,
      });
    },
    [id, type, meta, routeName, routePoster, navigation],
  );

  const handleWatchLater = useCallback(
    (stream: Stream) => {
      if (!stream.infoHash || !isTorrentStreamAvailable()) return;
      const existing = watchLater.getItem(stream.infoHash);

      if (existing && existing.status !== 'error') {
        // Already preloaded or downloading — play it
        setResolvingLabel(
          existing.status === 'ready'
            ? 'Starting playback…'
            : 'Preparing stream…',
        );
        setResolvingStream(true);
        playPreloadedTorrent(stream.infoHash)
          .then(result => {
            setResolvingStream(false);
            navigation.navigate('Player', {
              id,
              type,
              name: meta?.name ?? routeName ?? '',
              stream: {...stream, url: result.url},
              poster: meta?.poster ?? routePoster,
            });
          })
          .catch(e => {
            setResolvingStream(false);
            Alert.alert('Play Error', `Could not play preloaded torrent: ${String(e)}`);
          });
        return;
      }

      if (existing?.status === 'error') {
        // Failed — remove and re-queue
        cancelPreload(stream.infoHash);
        watchLater.removeItem(stream.infoHash);
      }

      // Queue for pre-download
      watchLater.addItem({
        infoHash: stream.infoHash,
        name: meta?.name ?? routeName ?? '',
        poster: meta?.poster ?? routePoster,
        type,
        id,
        ...(selectedEpisode
          ? {
              season: selectedEpisode.season,
              episode: selectedEpisode.episode,
              episodeTitle: selectedEpisode.title,
            }
          : {}),
      });
      ToastAndroid.show('Added to Watch Later — downloading...', ToastAndroid.SHORT);

      preloadTorrent(stream.infoHash, p => {
        if (p.status === 'complete') {
          watchLater.updateProgress(stream.infoHash, 100, 'ready');
        } else {
          watchLater.updateProgress(
            stream.infoHash,
            p.progress,
            p.status === 'resolving' ? 'resolving' : 'downloading',
          );
        }
      }).catch(e => {
        watchLater.updateStatus(stream.infoHash, 'error', String(e));
      });
    },
    [id, type, meta, routeName, routePoster, navigation, watchLater],
  );

  const allStreams = (() => {
    const raw = streamResults.flatMap(r =>
      r.streams.map(s => ({stream: s, addon: r.addon})),
    );
    // Deduplicate streams:
    // - Same infoHash = same torrent (native module picks largest video file)
    // - Same url = same direct link
    // - Same filename = same content from different sources
    const seen = new Set<string>();
    return raw.filter(({stream}) => {
      const keys: string[] = [];
      if (stream.infoHash) {
        keys.push(`hash:${stream.infoHash.toLowerCase()}`);
      }
      if (stream.url) {
        keys.push(`url:${stream.url}`);
      }
      if (stream.externalUrl) {
        keys.push(`ext:${stream.externalUrl}`);
      }
      if (stream.behaviorHints?.filename) {
        keys.push(`file:${stream.behaviorHints.filename.toLowerCase()}`);
      }
      if (keys.length === 0) return true;
      // If ANY key was already seen, it's a duplicate
      const isDupe = keys.some(k => seen.has(k));
      if (isDupe) return false;
      keys.forEach(k => seen.add(k));
      return true;
    });
  })();

  // Build streams tab label with count + loading state
  const streamsTabLabel = streamsLoading
    ? `Streams${allStreams.length > 0 ? ` (${allStreams.length}…)` : ' (loading…)'}`
    : `Streams${allStreams.length > 0 ? ` (${allStreams.length})` : ''}`;

  const tabs: {key: Tab; label: string}[] = [
    {key: 'overview', label: 'Overview'},
    ...(type === 'series' ? [{key: 'episodes' as Tab, label: 'Episodes'}] : []),
    {key: 'streams', label: streamsTabLabel},
  ];

  if (metaLoading) return <LoadingSpinner fullScreen />;

  const displayName = meta?.name ?? routeName ?? '';
  const displayPoster = meta?.poster ?? routePoster;

  // For movies: always provide onPressPlay; if still loading, show toast
  const moviePlayHandler = isMovie
    ? allStreams.length > 0
      ? () => handlePlayStream(allStreams[0].stream, allStreams[0].addon)
      : streamsLoading
      ? () => {
          ToastAndroid.show('Streams are still loading, please wait...', ToastAndroid.SHORT);
        }
      : undefined // no streams found
    : undefined;

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" translucent backgroundColor="transparent" />

      {/* Back button floating */}
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => navigation.goBack()}
        focusable={IS_TV || undefined}>
        <Icon name="arrow-left" size={22} color={colors.textPrimary} />
      </TouchableOpacity>

      {/* Resolving / torrent buffering overlay */}
      {resolvingStream && (
        <View style={styles.resolvingOverlay}>
          <ActivityIndicator size="large" color={colors.primary} />
          {torrentProgress !== null ? (
            <>
              <Text style={styles.resolvingText}>
                {torrentProgress.status === 'resolving'
                  ? 'Finding torrent peers…'
                  : `Buffering torrent… ${Math.round(torrentProgress.bufferProgress)}%`}
              </Text>
              <View style={styles.torrentStats}>
                <View style={styles.torrentStatItem}>
                  <Icon name="account-group" size={16} color={colors.textMuted} />
                  <Text style={styles.torrentStatText}>
                    {torrentProgress.seeds} seed{torrentProgress.seeds !== 1 ? 's' : ''}
                  </Text>
                </View>
                <View style={styles.torrentStatItem}>
                  <Icon name="download" size={16} color={colors.textMuted} />
                  <Text style={styles.torrentStatText}>
                    {torrentProgress.downloadSpeed > 0
                      ? `${(torrentProgress.downloadSpeed / 1024).toFixed(0)} KB/s`
                      : '—'}
                  </Text>
                </View>
                <View style={styles.torrentStatItem}>
                  <Icon name="percent" size={16} color={colors.textMuted} />
                  <Text style={styles.torrentStatText}>
                    {torrentProgress.progress}% total
                  </Text>
                </View>
              </View>
              {/* Progress bar */}
              <View style={styles.torrentProgressBar}>
                <View
                  style={[
                    styles.torrentProgressFill,
                    {width: `${Math.round(torrentProgress.bufferProgress)}%`},
                  ]}
                />
              </View>
              <TouchableOpacity
                style={styles.cancelTorrentBtn}
                onPress={() => {
                  stopTorrentStream();
                  setResolvingStream(false);
                  setTorrentProgress(null);
                }}
                focusable={IS_TV || undefined}
                hasTVPreferredFocus={IS_TV || undefined}>
                <Text style={styles.cancelTorrentText}>Cancel</Text>
              </TouchableOpacity>
            </>
          ) : (
            <Text style={styles.resolvingText}>{resolvingLabel || 'Resolving stream…'}</Text>
          )}
        </View>
      )}

      <ScrollView showsVerticalScrollIndicator={false}>
        {meta ? (
          <DetailHero
            meta={meta}
            isInWatchlist={libraryItem?.isWatchlist ?? false}
            isFavorite={libraryItem?.isFavorite ?? false}
            onAddToWatchlist={() => {
              if (libraryItem?.isWatchlist) {
                removeFromWatchlist(id);
              } else {
                addToWatchlist({
                  id,
                  type,
                  name: displayName,
                  poster: displayPoster,
                });
              }
            }}
            onToggleFavorite={() => toggleFavorite(id)}
            onPressPlay={moviePlayHandler}
            streamsLoading={streamsLoading}
            isMovie={isMovie}
          />
        ) : (
          <View style={styles.noMeta}>
            <Text style={styles.noMetaTitle}>{displayName}</Text>
          </View>
        )}

        {/* Tab bar */}
        <View style={styles.tabs}>
          {tabs.map(tab => (
            <TouchableOpacity
              key={tab.key}
              style={[styles.tab, activeTab === tab.key && styles.tabActive]}
              onPress={() => handleTabPress(tab.key)}
              focusable={IS_TV || undefined}>
              <Text
                style={[
                  styles.tabText,
                  activeTab === tab.key && styles.tabTextActive,
                ]}>
                {tab.label}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        {/* Tab content */}
        {activeTab === 'overview' && meta && (
          <View>
            <CastRow cast={meta.cast} director={meta.director} />
            {meta.awards && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>Awards</Text>
                <Text style={styles.infoValue}>{meta.awards}</Text>
              </View>
            )}
            {meta.country && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>Country</Text>
                <Text style={styles.infoValue}>{meta.country}</Text>
              </View>
            )}
            {meta.language && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>Language</Text>
                <Text style={styles.infoValue}>{meta.language}</Text>
              </View>
            )}
          </View>
        )}

        {activeTab === 'episodes' && meta?.videos && meta.videos.length > 0 && (
          <EpisodeList
            videos={meta.videos}
            currentVideoId={selectedEpisode?.id}
            onSelectEpisode={video => {
              setSelectedEpisode(video);
              setStreamsLoading(true);
              setStreamResults([]);
              setActiveTab('streams');
              // Torrentio/Stremio addons expect: {imdbId}:{season}:{episode}
              // Cinemeta usually returns video.id in that format, but fall back to constructing it
              const episodeId =
                video.id.includes(':')
                  ? video.id
                  : `${id}:${video.season ?? 1}:${video.episode ?? 1}`;
              if (cancelStreamRef.current) cancelStreamRef.current();
              cancelStreamRef.current = addonManager.streamStreamsFromAll(
                type,
                episodeId,
                result => setStreamResults(prev => [...prev, result]),
                () => setStreamsLoading(false),
              );
            }}
          />
        )}

        {activeTab === 'streams' && (
          <View style={styles.streamList}>
            {/* Episode context header for series */}
            {selectedEpisode && type === 'series' && (
              <TouchableOpacity
                style={styles.episodeHeader}
                onPress={() => {
                  setActiveTab('episodes');
                }}
                focusable={IS_TV || undefined}>
                <Icon name="arrow-left" size={18} color={colors.textMuted} />
                <Text style={styles.episodeHeaderText}>
                  S{selectedEpisode.season}E{selectedEpisode.episode} — {selectedEpisode.title}
                </Text>
              </TouchableOpacity>
            )}
            {/* Show streams as they arrive */}
            {allStreams.length > 0 && allStreams.map(({stream, addon}, idx) => {
              const wlItem = stream.infoHash ? watchLater.getItem(stream.infoHash) : undefined;
              return (
                <StreamItem
                  key={`${addon.id}-${idx}`}
                  stream={stream}
                  addon={addon}
                  onPress={() => handlePlayStream(stream, addon)}
                  onWatchLater={stream.infoHash ? () => handleWatchLater(stream) : undefined}
                  watchLaterStatus={wlItem?.status ?? null}
                  watchLaterProgress={wlItem?.progress}
                />
              );
            })}
            {/* Loading indicator — shown while addons are still responding */}
            {streamsLoading && (
              <View style={styles.streamsLoadingRow}>
                <ActivityIndicator size="small" color={colors.primary} />
                <Text style={styles.streamsLoadingText}>
                  {allStreams.length > 0
                    ? `Found ${allStreams.length} streams, loading more…`
                    : 'Loading streams…'}
                </Text>
              </View>
            )}
            {/* Empty state — only shown when fully loaded with no results */}
            {!streamsLoading && allStreams.length === 0 && (
              <View style={styles.noStreams}>
                <Icon
                  name={type === 'series' && !selectedEpisode ? 'television-play' : 'movie-off'}
                  size={48}
                  color={colors.textMuted}
                />
                <Text style={styles.noStreamsText}>
                  {type === 'series' && !selectedEpisode
                    ? 'Select an episode to see available streams.'
                    : selectedEpisode
                    ? 'No streams found for this episode.'
                    : 'No streams found. Install a stream addon like Torrentio.'}
                </Text>
                {type === 'series' && !selectedEpisode && (
                  <TouchableOpacity
                    style={styles.goToEpisodesBtn}
                    onPress={() => setActiveTab('episodes')}
                    focusable={IS_TV || undefined}>
                    <Text style={styles.goToEpisodesBtnText}>Go to Episodes</Text>
                  </TouchableOpacity>
                )}
              </View>
            )}
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: colors.background},
  backBtn: {
    position: 'absolute',
    top: 44,
    left: 16,
    zIndex: 10,
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  noMeta: {padding: 80, alignItems: 'center'},
  noMetaTitle: {...typography.title, color: colors.textPrimary},
  tabs: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: colors.border,
    marginBottom: 16,
  },
  tab: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 2,
    borderBottomColor: 'transparent',
    marginRight: 4,
  },
  tabActive: {borderBottomColor: colors.primary},
  tabText: {...typography.body, color: colors.textMuted},
  tabTextActive: {color: colors.primary, fontWeight: '600'},
  streamList: {paddingHorizontal: 16, paddingBottom: 20},
  streamsLoadingRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 10,
    paddingVertical: 16,
  },
  streamsLoadingText: {
    ...typography.caption,
    color: colors.textMuted,
    fontSize: 13,
  },
  episodeHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingVertical: 10,
    marginBottom: 8,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: colors.border,
  },
  episodeHeaderText: {
    ...typography.body,
    color: colors.textSecondary,
    fontWeight: '600',
    flex: 1,
  },
  noStreams: {
    alignItems: 'center',
    paddingVertical: 40,
    gap: 12,
    paddingHorizontal: 24,
  },
  noStreamsText: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
  },
  goToEpisodesBtn: {
    backgroundColor: colors.primary,
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 8,
    marginTop: 4,
  },
  goToEpisodesBtnText: {
    color: '#fff',
    fontWeight: '700',
    fontSize: 14,
  },
  infoRow: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingVertical: 8,
    gap: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: colors.border,
  },
  infoLabel: {
    ...typography.caption,
    color: colors.textMuted,
    width: 80,
    textTransform: 'uppercase',
    fontWeight: '600',
  },
  infoValue: {...typography.body, color: colors.textSecondary, flex: 1},
  resolvingOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.75)',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 100,
    gap: 16,
  },
  resolvingText: {
    ...typography.subtitle,
    color: colors.textPrimary,
  },
  torrentStats: {
    flexDirection: 'row',
    gap: 20,
    marginTop: 4,
  },
  torrentStatItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  torrentStatText: {
    ...typography.caption,
    color: colors.textMuted,
    fontSize: 13,
  },
  torrentProgressBar: {
    width: '70%',
    height: 4,
    borderRadius: 2,
    backgroundColor: 'rgba(255,255,255,0.15)',
    marginTop: 8,
    overflow: 'hidden',
  },
  torrentProgressFill: {
    height: '100%',
    borderRadius: 2,
    backgroundColor: colors.primary,
  },
  cancelTorrentBtn: {
    marginTop: 12,
    paddingHorizontal: 24,
    paddingVertical: 10,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.3)',
    backgroundColor: 'rgba(255,255,255,0.1)',
  },
  cancelTorrentText: {
    ...typography.body,
    color: colors.textSecondary,
  },
});
