/* ═══════════════════════════════════════════════════════
   lib/utils · formatters, chip math, helpers
═══════════════════════════════════════════════════════ */

const CHIP_DEFS = [
  { key: 'black', label: 'Preta',    val: 5.00, bg: '#1a1a1a', stroke: '#666' },
  { key: 'blue',  label: 'Azul',     val: 1.00, bg: '#1a4fa0', stroke: '#4a8ff0' },
  { key: 'green', label: 'Verde',    val: 0.50, bg: '#1a6e3c', stroke: '#4aaf6e' },
  { key: 'red',   label: 'Vermelha', val: 0.25, bg: '#8b1a1a', stroke: '#e05555' },
  { key: 'white', label: 'Branca',   val: 0.10, bg: '#bcbcbc', stroke: '#f0f0f0' },
];

const PTS = [30, 25, 21, 18, 15, 12, 10, 8, 6, 4, 4];
const DEFAULT_FEE = 50;
const BUYIN_DEFAULT = 30;
const RET_DEFAULT = 5;

const fmtBRL = v => new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(v || 0);
const fmtNum = v => new Intl.NumberFormat('pt-BR').format(v || 0);
const fmtDate = iso => {
  if (!iso) return '';
  const [y, m, d] = iso.split('-');
  const months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
  return `${parseInt(d)} ${months[parseInt(m) - 1]}`;
};
const fmtDateFull = iso => {
  if (!iso) return '';
  const [y, m, d] = iso.split('-');
  return `${d}/${m}/${y}`;
};
const todayISO = () => new Date().toISOString().slice(0, 10);
const currentYM = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0'); };
const monthLabel = ym => {
  if (!ym) return '';
  const [y, m] = ym.split('-');
  const months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
  return `${months[parseInt(m) - 1]} ${y}`;
};
const prevMonth = ym => {
  let [y, m] = ym.split('-').map(Number); m--;
  if (m < 1) { m = 12; y--; }
  return `${y}-${String(m).padStart(2, '0')}`;
};
const nextMonth = ym => {
  let [y, m] = ym.split('-').map(Number); m++;
  if (m > 12) { m = 1; y++; }
  return `${y}-${String(m).padStart(2, '0')}`;
};

const mkBlankChips = () => ({ black: 0, blue: 0, green: 0, red: 0, white: 0 });
const mkPlayer = name => ({ name, buyins: 1, chips: mkBlankChips() });
const chipValue = chips => CHIP_DEFS.reduce((s, c) => s + (Number(chips?.[c.key]) || 0) * c.val, 0);
const gameValues = g => {
  const buyin = Number(g?.buyinValue) || BUYIN_DEFAULT;
  const ret = Number(g?.retValue) || RET_DEFAULT;
  return { buyin, ret, cv: buyin - ret };
};
const playerBalance = (p, gv) => chipValue(p.chips || {}) - (p.buyins || 1) * gv.cv;

const initials = name => {
  if (!name) return '?';
  const p = String(name).trim().split(/\s+/);
  return p.length >= 2 ? (p[0][0] + p[p.length - 1][0]).toUpperCase() : p[0].slice(0, 2).toUpperCase();
};

const genId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
const genClubCode = () => {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  let code = '';
  for (let i = 0; i < 6; i++) code += chars[Math.floor(Math.random() * chars.length)];
  return code;
};

/* Convert RTDB object->array shape */
const toArr = v => {
  if (!v) return [];
  if (Array.isArray(v)) return v.filter(x => x != null);
  if (typeof v === 'object') return Object.keys(v).sort().map(k => v[k]).filter(x => x != null);
  return [];
};

const findIdx = (arr, fn) => { for (let i = 0; i < arr.length; i++) if (fn(arr[i])) return i; return -1; };
const merge = (a, b) => Object.assign({}, a || {}, b || {});

/* Name alias resolution from the legacy app */
const NAME_ALIASES = { Bruno: 'Bruno Couto', 'DJ Eder': 'Eder', 'Dario Franz': 'Dario' };
const resolveAlias = n => NAME_ALIASES[n] || n;

/* Override nameToRankKey and getUserAvatar with improved versions (see store.jsx exports) */

/* Image resize utility (for avatars/logos) */
function resizeImage(file, size, cb) {
  const reader = new FileReader();
  reader.onload = e => {
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = size; canvas.height = size;
      const ctx = canvas.getContext('2d');
      const s = Math.min(img.width, img.height);
      const ox = (img.width - s) / 2, oy = (img.height - s) / 2;
      ctx.drawImage(img, ox, oy, s, s, 0, 0, size, size);
      cb(canvas.toDataURL('image/jpeg', 0.82));
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

Object.assign(window, {
  CHIP_DEFS, PTS, DEFAULT_FEE, BUYIN_DEFAULT, RET_DEFAULT,
  fmtBRL, fmtNum, fmtDate, fmtDateFull, todayISO, currentYM, monthLabel, prevMonth, nextMonth,
  mkBlankChips, mkPlayer, chipValue, gameValues, playerBalance,
  initials, genId, genClubCode, toArr, findIdx, merge,
  resolveAlias, NAME_ALIASES, resizeImage,
});
