// team-data.jsx — Procedural, sport-aware roster / stats / schedule / standings
// generators for the team detail pages. Keeps tenants.jsx light while making
// every sport feel populated with realistic-looking data.

// Deterministic PRNG so a given sport+tenant always renders the same numbers.
function _tdSeed(str) {
  let h = 2166136261 >>> 0;
  for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
  return h >>> 0;
}
function _rng(seed) {
  let s = seed >>> 0;
  return () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296; };
}

const FIRST_NAMES = ['Jalen','Marcus','Theo','Cole','Aja','Devin','Tyler','Mason','Eli','Cam','Drew','Reese','Owen','Kai','Jordan','Brett','Nico','Luca','Sawyer','Trey','Hayes','Beau','Dom','Zane','Roman','Kade','Quinn','Asher','Knox','Rhett'];
const LAST_NAMES = ['Greene','Carver','Raines','Holloway','Maddox','Sutton','Pierce','Vance','Boone','Ellis','Crawford','Mercer','Dalton','Reyes','Foster','Hapner','Kingston','Walsh','Brennan','Ortega','Sayer','Whitaker','Lund','Castillo','Nash','Ferro','Adler','Banks','Mosley','Tran'];
const HOMETOWNS = ['Baltimore, MD','Pittsburgh, PA','Huntington, WV','Columbus, OH','Charleston, WV','Cincinnati, OH','Salt Lake City, UT','Provo, UT','Lexington, KY','Louisville, KY','Tampa, FL','Dallas, TX','Atlanta, GA','Phoenix, AZ','Denver, CO'];
const CLASSES = ['Fr.','So.','Jr.','Sr.','Gr.'];

// Position sets by sport family
const POSITIONS = {
  fb:    ['QB','RB','WR','TE','OL','DL','LB','CB','S','K'],
  mbb:   ['G','G','F','F','C'],
  wbb:   ['G','G','F','F','C'],
  bsb:   ['P','C','1B','2B','3B','SS','LF','CF','RF','DH'],
  soc_w: ['GK','D','D','M','M','F','F'],
  soc:   ['GK','D','D','M','M','F','F'],
  vb:    ['OH','MB','S','L','OPP'],
  gym:   ['AA','VT','UB','BB','FX'],
  wr:    ['125','133','141','149','157','165','174','184','197','HWT'],
  default: ['G','F','M','D','U'],
};

function posSet(sportId) { return POSITIONS[sportId] || POSITIONS.default; }

// Stat schema per sport family. Returns column defs + a row generator.
function statSchema(sportId, rng) {
  const isBaseball = sportId === 'bsb';
  const isHoops = sportId === 'mbb' || sportId === 'wbb';
  const isSoccer = sportId === 'soc_w' || sportId === 'soc';
  const isFootball = sportId === 'fb';
  const isVolley = sportId === 'vb';

  if (isBaseball) {
    return {
      label: 'Batting',
      cols: ['GP','AB','R','H','2B','HR','RBI','AVG'],
      gen: () => {
        const ab = 80 + Math.floor(rng() * 140);
        const h = Math.floor(ab * (0.22 + rng() * 0.16));
        return [ 40 + Math.floor(rng()*15), ab, Math.floor(h*0.6), h, Math.floor(h*0.2), Math.floor(rng()*14), Math.floor(h*0.7), '.' + String(Math.round((h/ab)*1000)).padStart(3,'0') ];
      },
    };
  }
  if (isHoops) {
    return {
      label: 'Scoring',
      cols: ['GP','PPG','RPG','APG','FG%','3P%'],
      gen: () => [ 20 + Math.floor(rng()*12), (4 + rng()*18).toFixed(1), (1 + rng()*9).toFixed(1), (0.5 + rng()*6).toFixed(1), (38 + rng()*18).toFixed(1), (28 + rng()*18).toFixed(1) ],
    };
  }
  if (isSoccer) {
    return {
      label: 'Attacking',
      cols: ['GP','G','A','SH','SOG','MIN'],
      gen: () => [ 14 + Math.floor(rng()*8), Math.floor(rng()*12), Math.floor(rng()*9), Math.floor(rng()*40), Math.floor(rng()*22), 600 + Math.floor(rng()*900) ],
    };
  }
  if (isFootball) {
    return {
      label: 'Offense',
      cols: ['GP','YDS','TD','REC','AVG','LNG'],
      gen: () => { const yds = 100 + Math.floor(rng()*1400); const rec = 8 + Math.floor(rng()*60); return [ 8+Math.floor(rng()*4), yds, Math.floor(rng()*16), rec, (yds/rec).toFixed(1), 20+Math.floor(rng()*60) ]; },
    };
  }
  if (isVolley) {
    return {
      label: 'Attacking',
      cols: ['GP','K','A','D','B','SP'],
      gen: () => [ 20+Math.floor(rng()*8), Math.floor(rng()*300), Math.floor(rng()*400), Math.floor(rng()*250), Math.floor(rng()*70), 60+Math.floor(rng()*40) ],
    };
  }
  return {
    label: 'Overall',
    cols: ['GP','W','L','PCT'],
    gen: () => { const w = Math.floor(rng()*18); const l = Math.floor(rng()*10); return [ w+l, w, l, ((w/(w+l||1))).toFixed(3).replace(/^0/,'') ]; },
  };
}

// Generate a roster of N players for a sport.
function genRoster(sportId, tenantId, n = 14) {
  const rng = _rng(_tdSeed(`${tenantId}-${sportId}-roster`));
  const positions = posSet(sportId);
  const schema = statSchema(sportId, rng);
  const usedNums = new Set();
  const players = [];
  for (let i = 0; i < n; i++) {
    const fn = FIRST_NAMES[Math.floor(rng() * FIRST_NAMES.length)];
    const ln = LAST_NAMES[Math.floor(rng() * LAST_NAMES.length)];
    let num;
    do { num = 1 + Math.floor(rng() * 60); } while (usedNums.has(num));
    usedNums.add(num);
    const pos = positions[Math.floor(rng() * positions.length)];
    const ht = `${5 + Math.floor(rng()*2)}-${Math.floor(rng()*12)}`;
    const wt = 150 + Math.floor(rng() * 110);
    const cls = CLASSES[Math.floor(rng() * CLASSES.length)];
    const home = HOMETOWNS[Math.floor(rng() * HOMETOWNS.length)];
    const avatar = `mountaineer/assets/rewards/avatar-${String(1 + Math.floor(rng()*10)).padStart(2,'0')}.png`;
    players.push({
      id: `${sportId}-p${i}`,
      num, firstName: fn, lastName: ln, name: `${fn} ${ln}`,
      pos, ht, wt, cls, home, avatar,
      stats: schema.gen(),
      statCols: schema.cols,
      statLabel: schema.label,
    });
  }
  return { players, schema };
}

// Generate a season schedule (past + upcoming) for a sport.
function genSchedule(sportId, tenantId) {
  const rng = _rng(_tdSeed(`${tenantId}-${sportId}-sched`));
  const opps = ['Texas Tech','Kansas','Baylor','Iowa State','Oklahoma State','TCU','Cincinnati','Houston','UCF','BYU','Arizona','Colorado','Pitt','Penn State','Tennessee','Florida','Portland','LAFC'];
  const venues = ['Home','Away'];
  const months = ['SEP','OCT','NOV','DEC','JAN','FEB'];
  const games = [];
  // 8 past + 1 live + 5 upcoming
  for (let i = 0; i < 14; i++) {
    const opp = opps[Math.floor(rng() * opps.length)];
    const isHome = rng() > 0.45;
    const past = i < 8;
    const usScore = 14 + Math.floor(rng() * 28);
    const themScore = 10 + Math.floor(rng() * 26);
    const won = usScore > themScore;
    games.push({
      id: `${sportId}-g${i}`,
      opp, isHome, past, live: i === 8,
      date: `${months[Math.floor(i/3) % months.length]} ${1 + Math.floor(rng()*27)}`,
      time: ['12:00 PM','3:30 PM','6:00 PM','7:30 PM','2:00 PM'][Math.floor(rng()*5)],
      usScore, themScore, won,
      oppRecord: `${3+Math.floor(rng()*7)}-${Math.floor(rng()*6)}`,
    });
  }
  return games;
}

// Generate conference standings for a sport.
function genStandings(sportId, tenantId, conf) {
  const rng = _rng(_tdSeed(`${tenantId}-${sportId}-standings`));
  const teams = {
    'Big 12': ['West Virginia','Utah','Kansas','Kansas State','Baylor','TCU','Texas Tech','Iowa State','Oklahoma State','Cincinnati','Houston','UCF','BYU','Arizona','Colorado','Arizona State'],
    'Big Ten': ['Ohio State','Michigan','Penn State','Oregon','Iowa','Wisconsin','Indiana','Illinois','Nebraska','Minnesota'],
    'SEC': ['Kentucky','Georgia','Alabama','Tennessee','LSU','Florida','Texas A&M','Auburn','Ole Miss','Missouri'],
    'MLS': ['Real Salt Lake','LAFC','LA Galaxy','Seattle','Portland','Austin FC','Houston','Minnesota','Colorado','Vancouver'],
    'NWSL': ['Utah Royals','Portland','Kansas City','Orlando','Washington','San Diego','Gotham FC','Angel City','Houston','North Carolina'],
  };
  const list = (teams[conf] || teams['Big 12']).map((name, i) => {
    const w = 12 - i + Math.floor(rng() * 4);
    const l = 2 + i - Math.floor(rng() * 2);
    return { name, w: Math.max(0, w), l: Math.max(0, l), pct: 0 };
  });
  list.forEach(t => { t.pct = (t.w / (t.w + t.l || 1)); });
  list.sort((a, b) => b.pct - a.pct);
  return list.map((t, i) => ({ ...t, rank: i + 1, pct: t.pct.toFixed(3).replace(/^0/, '') }));
}

Object.assign(window, { genRoster, genSchedule, genStandings, statSchema, posSet });
