export function parseAmountToken(raw) {
  const s = String(raw || "").trim();
  if (!s) return NaN;
  if (s.includes(",") && s.includes(".")) {
    if (s.lastIndexOf(",") > s.lastIndexOf(".")) {
      return Number.parseFloat(s.replace(/\./g, "").replace(",", "."));
    }
    return Number.parseFloat(s.replace(/,/g, ""));
  }
  if (s.includes(",")) {
    const frac = s.split(",")[1] || "";
    if (frac.length === 2) return Number.parseFloat(s.replace(/\./g, "").replace(",", "."));
    return Number.parseFloat(s.replace(/,/g, ""));
  }
  if (s.includes(".")) {
    const parts = s.split(".");
    if (parts.length > 2 || (parts.length === 2 && parts[1].length === 3)) {
      return Number.parseFloat(s.replace(/\./g, ""));
    }
    return Number.parseFloat(s);
  }
  return Number.parseFloat(s);
}

export function extractPrizeAmount(text) {
  const s = String(text || "").trim();
  if (!s) return null;
  const tokens = s.match(/\d[\d.,]*/g);
  if (!tokens?.length) return null;
  let best = null;
  for (const token of tokens) {
    const val = parseAmountToken(token);
    if (!Number.isFinite(val) || val <= 0) continue;
    if (best == null || val > best) best = val;
  }
  return best;
}

export function formatPrizeDisplay(ev, locale) {
  const fromDesc = extractPrizeAmount(ev.prizeDescription);
  if (fromDesc != null) {
    const loc = locale === "en" ? "en-GB" : "tr-TR";
    return `${new Intl.NumberFormat(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(fromDesc)} ₺`;
  }
  const desc = String(ev.prizeDescription || "").trim();
  if (desc) return desc;
  const fromTitle = extractPrizeAmount(ev.title);
  if (fromTitle != null) {
    const loc = locale === "en" ? "en-GB" : "tr-TR";
    return `${new Intl.NumberFormat(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(fromTitle)} ₺`;
  }
  return "—";
}

export function splitCountdown(endsAt, nowSec) {
  if (!endsAt || !Number.isFinite(endsAt)) return null;
  let diff = Math.max(0, endsAt - nowSec);
  const days = Math.floor(diff / 86400);
  diff -= days * 86400;
  const hours = Math.floor(diff / 3600);
  diff -= hours * 3600;
  const mins = Math.floor(diff / 60);
  const secs = diff - mins * 60;
  return {
    days: String(days),
    hours: String(hours),
    mins: String(mins),
    secs: String(secs),
  };
}
