/** Pick one entry from a weighted list using dropRate as relative weight. */
export function pickWeighted(entries) {
  const total = entries.reduce((sum, e) => sum + e.dropRate, 0);
  if (total <= 0) {
    throw new Error('No valid drop rates');
  }
  let roll = Math.random() * total;
  for (const entry of entries) {
    roll -= entry.dropRate;
    if (roll <= 0) {
      return entry;
    }
  }
  return entries[entries.length - 1];
}

export function normalizeRates(entries) {
  const total = entries.reduce((sum, e) => sum + e.dropRate, 0);
  if (total <= 0) return entries.map((e) => ({ ...e, chance: 0 }));
  return entries.map((e) => ({
    ...e,
    chance: (e.dropRate / total) * 100,
  }));
}

/**
 * Boost drop rates below the median by (1 + luckPercent/100).
 * Same factor on all weights would not change odds — only rares get the boost.
 */
export function applyCatalogLuck(entries, luckPercent = 0) {
  const luck = Number(luckPercent) || 0;
  if (luck <= 0 || !entries?.length) return entries;

  const rates = entries.map((e) => e.dropRate).sort((a, b) => a - b);
  const mid = Math.floor(rates.length / 2);
  const median =
    rates.length % 2 === 0 ? (rates[mid - 1] + rates[mid]) / 2 : rates[mid];
  const factor = 1 + luck / 100;

  return entries.map((e) => ({
    ...e,
    dropRate: e.dropRate < median ? e.dropRate * factor : e.dropRate,
  }));
}
