// Bottom-sheet wybór jakości po resolve. Sortuje malejąco po pikselach (4K > 1080 > 720 > ...).
// Single quality → caller pomija modal i odpala od razu.
import React from 'react';
import {
  Modal,
  Pressable,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { theme } from '../theme';
import type { StreamLink } from '../types';

export function qualityToInt(q: string | null | undefined): number {
  if (!q) return 0;
  const s = q.toLowerCase();
  if (s.includes('4k') || s.includes('uhd')) return 2160;
  if (s.includes('2k') || s.includes('qhd')) return 1440;
  const m = s.match(/\d+/);
  if (m) return parseInt(m[0], 10);
  if (s.includes('fhd')) return 1080;
  if (s.includes('hd')) return 720;
  if (s.includes('sd')) return 480;
  return 0;
}

export function sortByQualityDesc(links: StreamLink[]): StreamLink[] {
  return [...links].sort((a, b) => qualityToInt(b.quality) - qualityToInt(a.quality));
}

export function PlaybackQualityModal({
  visible,
  links,
  onSelect,
  onCancel,
}: {
  visible: boolean;
  links: StreamLink[];
  onSelect: (link: StreamLink) => void;
  onCancel: () => void;
}) {
  const sorted = React.useMemo(() => sortByQualityDesc(links), [links]);

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
      onRequestClose={onCancel}
    >
      <Pressable style={styles.backdrop} onPress={onCancel}>
        <Pressable style={styles.sheet} onPress={(e) => e.stopPropagation()}>
          <Text style={styles.title}>Select quality</Text>
          {sorted.map((link, i) => {
            const px = qualityToInt(link.quality);
            return (
              <Pressable
                key={`${link.stream_url || link.embed_url}-${i}`}
                style={styles.row}
                onPress={() => onSelect(link)}
              >
                <Text style={styles.rowQuality}>
                  {link.quality || 'unknown'}
                </Text>
                <Text style={styles.rowMeta}>
                  {px ? `${px}p` : ''}
                  {link.type ? ` · ${shortType(link.type)}` : ''}
                </Text>
              </Pressable>
            );
          })}
          <Pressable style={styles.cancel} onPress={onCancel}>
            <Text style={styles.cancelText}>Cancel</Text>
          </Pressable>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

function shortType(t: string): string {
  const low = t.toLowerCase();
  if (low.includes('mp4') || low === 'direct') return 'mp4';
  if (low.includes('mpegurl') || low.includes('m3u8')) return 'hls';
  if (low.includes('dash')) return 'dash';
  if (low.includes('webm')) return 'webm';
  return t;
}

const styles = StyleSheet.create({
  backdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'flex-end',
  },
  sheet: {
    backgroundColor: theme.bg,
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    paddingHorizontal: 16,
    paddingTop: 14,
    paddingBottom: 24,
    borderTopColor: theme.border,
    borderTopWidth: 1,
  },
  title: {
    color: theme.muted,
    fontSize: 12,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 10,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: theme.card,
    borderColor: theme.border,
    borderWidth: 1,
    borderRadius: 8,
    padding: 14,
    marginBottom: 8,
  },
  rowQuality: { color: theme.fg, fontSize: 16, fontWeight: '600' },
  rowMeta: { color: theme.muted, fontSize: 13 },
  cancel: {
    marginTop: 6,
    padding: 12,
    alignItems: 'center',
  },
  cancelText: { color: theme.muted, fontSize: 14 },
});
