import {ReplayData, UserReplayData} from "./replays";

export function formatDuration(seconds: number): string | null {
  if(!seconds) {
    return null;
  }

  const days = Math.floor(seconds / (3600 * 24));
  const hours = Math.floor((seconds % (3600 * 24)) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  let result = "";
  if (days > 0) result += `${days}d `;
  if (hours > 0 || days > 0) result += `${hours}h `;
  if (minutes > 0 || hours > 0 || days > 0) result += `${minutes}m`;

  return result.trim();
}

export function countryCodeToFlag(countryCode: string): string {
  const code = countryCode.toUpperCase();

  if (code.length !== 2) {
    throw new Error('Invalid country code: Must be exactly 2 characters.');
  }

  const codePoints = [...code].map(
    char => 0x1F1E6 - 65 + char.charCodeAt(0)
  );

  return String.fromCodePoint(...codePoints);
}

export function calculateAccuracy(replayData: ReplayData | UserReplayData): number {
  if(!replayData) {
    return 0;
  }

  const hit300 = replayData.count_300;
  const hit100 = replayData.count_100;
  const hit50 = replayData.count_50;
  const miss = replayData.count_miss;
  const totalHits = hit300 + hit100 + hit50 + miss;


  if (totalHits === 0) {
    return 0;
  }

  const accuracy = (300 * hit300 + 100 * hit100 + 50 * hit50) / (300 * totalHits);
  return accuracy * 100;
}
