// Identity helpers + pure formatters. No JSX.

const REQUIRED_VOTES = 6;
const ACCEPT_THRESHOLD = 0.9;

const playerByIdent = (id) => Store.get().players.find(p => p.identifier === id);
const isVerifiedArtist = (id) => Store.get().verifiedSet.has(id);

const canVote        = (p) => !!p && (p.group !== 'user' || isVerifiedArtist(p.identifier));
// canSubmit is the eligibility floor — playtime, no bans, no blocks. The
// artist-profile gate is intentionally NOT here: a creator who hasn't set
// up their profile yet still "can submit", they just need to do that one
// step first. The submit screen routes them through onboarding.
const canSubmit      = (p) => !!p && p.playtime >= 100 && !p.banned && !p.blocked;
const hasArtistProfile = (p) => !!p && !!p.artistProfile;
const canForceAccept = (p) => !!p && p.group === 'admin';
const isUserOnly     = (p) => !!p && p.group === 'user' && !isVerifiedArtist(p.identifier);
const isBanned       = (p) => !!p && !!p.banned;
const isBlocked      = (p) => !!p && !!p.blocked;

function tally(sub) {
  const accepts = sub.votes.filter(v => v.vote === 'accept').length;
  const rejects = sub.votes.filter(v => v.vote === 'reject').length;
  const total = accepts + rejects;
  const ratio = total === 0 ? 0 : accepts / total;
  return { accepts, rejects, total, ratio, meetsAuto: total >= REQUIRED_VOTES && ratio >= ACCEPT_THRESHOLD };
}

function timeAgo(ms) {
  const diff = Date.now() - ms;
  const m = Math.floor(diff / 60_000);
  if (m < 60) return `${Math.max(1, m)}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

function fmt(s) {
  s = Math.max(0, Math.floor(s));
  const m = Math.floor(s / 60), ss = s % 60;
  return m + ':' + (ss < 10 ? '0' : '') + ss;
}

function fallbackAvatar(identifier) {
  const palettes = [
    ['#ff4d8d', '#7c3aed'], ['#06b6d4', '#ec4899'], ['#a855f7', '#3b82f6'],
    ['#10b981', '#06b6d4'], ['#fbbf24', '#f97316'], ['#6366f1', '#a855f7'],
    ['#f472b6', '#fb923c'], ['#3b82f6', '#06b6d4'], ['#f43f5e', '#fb7185'],
    ['#34d399', '#a78bfa'],
  ];
  let h = 0;
  for (let i = 0; i < (identifier || '').length; i++) h = ((h << 5) - h + identifier.charCodeAt(i)) | 0;
  return palettes[Math.abs(h) % palettes.length];
}

Object.assign(window, {
  REQUIRED_VOTES, ACCEPT_THRESHOLD,
  playerByIdent, isVerifiedArtist,
  canVote, canSubmit, hasArtistProfile, canForceAccept, isUserOnly, isBanned, isBlocked,
  tally, timeAgo, fmt, fallbackAvatar,
});
