import type { LeaderboardItem, LeaderboardType } from "./components/achievementsTypes";

/**
 * The figure each leaderboard row shows, and the rank beside it.
 *
 * Pure, so the podium, the table and the community banner read one rule:
 * - individuals: completed whole hours, without minutes or fractions;
 * - teams: executed opportunities;
 * - companies: `total_score` (completed opportunities + sponsorships), which
 *   is what the board is ranked by. `sponsored_count` alone put a "0" at rank 1.
 */

/** Whole hours for achievement totals; truncates minutes without changing stored values. */
export function wholeAchievementHours(value: number | string | null | undefined): string {
  const hours = Number(typeof value === "string" ? value.split(":")[0] : value ?? 0);
  return String(Number.isFinite(hours) ? Math.max(0, Math.floor(hours)) : 0);
}

/** Prefer the server display, stripping its minutes for the leaderboard. */
export function leaderboardHours(item: Pick<LeaderboardItem, "total_hours" | "total_hours_display">): string {
  return wholeAchievementHours(item.total_hours_display || item.total_hours);
}

/** The row's figure, without its unit label. Counts use Western digits. */
export function leaderboardValue(item: LeaderboardItem, type: LeaderboardType): string {
  switch (type) {
    case "individuals":
      return leaderboardHours(item);
    case "teams":
      return Number(item.executed_opportunities || 0).toLocaleString("en-US");
    case "companies":
      return Number(
        item.total_score ?? (item.executed_opportunities || 0) + (item.sponsored_count || 0)
      ).toLocaleString("en-US");
    default:
      return "0";
  }
}

/**
 * The backend's competition rank (ties share a number: 1, 1, 3), falling back
 * to the row's position for a payload that predates the field.
 */
export function leaderboardRank(item: Pick<LeaderboardItem, "rank"> | null | undefined, position: number): number {
  const rank = Number(item?.rank);
  return Number.isInteger(rank) && rank > 0 ? rank : position;
}

/** Choose the localized unit from the displayed H:MM value, preserving fractional hours. */
export function hourUnitForDisplay(display: string, t: (key: string, options?: { count: number }) => string): string {
  const [hours, minutes = "0"] = display.split(":");
  const value = Number(hours) + Number(minutes) / 60;
  return t("ACHIEVEMENTS.HOUR_UNIT", { count: Number.isFinite(value) ? value : 0 });
}
