const formatQualityLabel = (level, localize) => {
  if (!level?.height) {
    return undefined;
  }

  let label;

  if (typeof localize === "function") {
    if (level.height >= 2160) {
      label = localize("qualityHeight4K", [level.height]);
    } else if (level.height >= 1440) {
      label = localize("qualityHeight2K", [level.height]);
    } else if (level.height >= 720) {
      label = localize("qualityHeightHD", [level.height]);
    } else {
      label = localize("qualityHeight", [level.height]);
    }

    if (level.bandwidth) {
      const mbps = (level.bandwidth / 1000000).toFixed(2);
      label += localize("qualityBandwidth", [mbps]);
    }

    return label;
  }

  if (level.height >= 2160) {
    label = level.height + "p (4K)";
  } else if (level.height >= 1440) {
    label = level.height + "p (2K)";
  } else if (level.height >= 720) {
    label = level.height + "p (HD)";
  } else {
    label = level.height + "p";
  }

  if (level.bandwidth) {
    const mbps = (level.bandwidth / 1000000).toFixed(2);
    label += ` (${mbps} Mbps)`;
  }

  return label;
};

const getQualityTrackKey = (track) =>
  [track.height ?? "", track.width ?? "", track.bandwidth ?? ""].join("|");

const deduplicateQualityTracks = (tracks) => {
  const uniqueTracks = new Map();

  tracks.forEach((track) => {
    const key = getQualityTrackKey(track);
    const existing = uniqueTracks.get(key);

    if (!existing || track.active) {
      uniqueTracks.set(key, track);
    }
  });

  return Array.from(uniqueTracks.values());
};

const sortQualityTracks = (track1, track2) => {
  // Keep Auto option first
  if (track1.id === -1) return -1;
  if (track2.id === -1) return 1;

  // Sort by height (highest first)
  const height1 = track1.height || 0;
  const height2 = track2.height || 0;

  if (height1 === height2) {
    return (track2.bandwidth || 0) - (track1.bandwidth || 0);
  }

  return height2 - height1;
};

export {
  deduplicateQualityTracks,
  formatQualityLabel,
  getQualityTrackKey,
  sortQualityTracks,
};
