/* ============================================================
   VYNDR 2.0 — slate adapter (§7, §E.1).
   Merges schedule + gamelines + streaks + grades into the GameCard
   contract, and detects the best/worst book line per game (the
   Bloomberg pattern — the #1 visual upgrade). Plain CommonJS so the
   .tsx cards import it (allowJs) AND Jest exercises the logic directly.
   ============================================================ */

/** American odds → decimal payout multiplier (higher = better for the bettor).
 *  "+150" → 2.5, "-110" → ~1.909. Returns null when unparseable. */
function parseAmericanOdds(odds) {
  if (odds == null) return null;
  const n = typeof odds === 'number' ? odds : parseInt(String(odds).replace(/[^\d+-]/g, ''), 10);
  if (!Number.isFinite(n) || n === 0) return null;
  return n > 0 ? 1 + n / 100 : 1 + 100 / Math.abs(n);
}

/** Mark the most/least favorable moneyline per side across a game's books.
 *  Input: { book1: { awayML, homeML, total }, ... } → rows with best/worst flags.
 *  best/worst only set when ≥2 books disagree (a lone price isn't "best"). */
function detectBestLines(books) {
  const entries = Object.entries(books || {});
  const rows = entries.map(([book, ln]) => ({
    book,
    awayML: ln.awayML || '—',
    homeML: ln.homeML || '—',
    ou: ln.total != null ? `O/U ${ln.total}` : '—',
    _away: parseAmericanOdds(ln.awayML),
    _home: parseAmericanOdds(ln.homeML),
  }));

  const mark = (side) => {
    const vals = rows.map((r) => r[side]).filter((v) => v != null);
    if (vals.length < 2) return [null, null];
    const max = Math.max(...vals);
    const min = Math.min(...vals);
    return max === min ? [null, null] : [max, min];
  };
  const [bestAway, worstAway] = mark('_away');
  const [bestHome, worstHome] = mark('_home');

  return rows.map((r) => ({
    book: r.book,
    awayML: r.awayML,
    homeML: r.homeML,
    ou: r.ou,
    bestAway: r._away != null && r._away === bestAway,
    worstAway: r._away != null && r._away === worstAway,
    bestHome: r._home != null && r._home === bestHome,
    worstHome: r._home != null && r._home === worstHome,
  }));
}

/**
 * Best available price across a prop's book rows (A1 Session 3).
 *
 * `rows` is the grouped odds shape the Express /api/odds proxy already
 * ships the browser: [{ book, line, over_odds, under_odds }] — one row
 * per book for the same player+stat.
 *
 * Data-semantics rule: a "best price" claim is only honest when ≥2 books
 * post the SAME line for the side and their prices differ — comparing
 * odds across different lines is meaningless, and a lone price isn't
 * "best". Anything else → null. Absent beats wrong.
 *
 * @param {Array<{book?:string,line?:number,over_odds?:number|null,under_odds?:number|null}>} rows
 * @param {string} [side] — 'over' | 'under' (default over)
 * @param {number|null} [refLine] — the line the card displays; when given,
 *   only books at that exact line compete.
 * @returns {{ book: string, odds: number } | null}
 */
function detectBestBook(rows, side = 'over', refLine = null) {
  const key = String(side || 'over').toLowerCase().startsWith('u') ? 'under_odds' : 'over_odds';
  const valid = (Array.isArray(rows) ? rows : []).filter(
    (r) => r && r.book && Number.isFinite(r.line) && r[key] != null && parseAmericanOdds(r[key]) != null,
  );
  if (valid.length < 2) return null;

  // Compare at ONE line: the displayed line when given, else the modal line.
  let line = Number.isFinite(refLine) ? refLine : null;
  if (line == null) {
    const counts = new Map();
    for (const r of valid) counts.set(r.line, (counts.get(r.line) || 0) + 1);
    let bestCount = 0;
    for (const [ln, c] of counts) if (c > bestCount) { bestCount = c; line = ln; }
  }
  const atLine = valid.filter((r) => r.line === line);
  if (atLine.length < 2) return null;

  const decimals = atLine.map((r) => parseAmericanOdds(r[key]));
  const max = Math.max(...decimals);
  if (max === Math.min(...decimals)) return null; // identical prices → no "best"
  const winner = atLine[decimals.indexOf(max)];
  return { book: winner.book, odds: winner[key] };
}

function formatGameTime(iso) {
  if (!iso) return '';
  try {
    return new Date(iso).toLocaleString(undefined, { weekday: 'short', hour: 'numeric', minute: '2-digit' });
  } catch {
    return String(iso);
  }
}

/** Map one schedule game's lines entry → the GameCard `lines[]` contract. */
function mapGameLines(linesEntry) {
  if (!linesEntry || !linesEntry.books) return [];
  return detectBestLines(linesEntry.books);
}

/**
 * Map schedule + gamelines + streaks (+ optional grades) → GameCardData[]
 * (§7). Pure — no API calls, no side effects.
 */
function mapScheduleToGameCards(schedule, gamelines, streaks, grades) {
  const sched = Array.isArray(schedule) ? schedule : [];
  return sched.map((g) => {
    const id = g.id || `${g.awayTeam?.abbreviation || '?'}-${g.homeTeam?.abbreviation || '?'}`;
    const live = g.live === true || g.status === 'in';
    const linesEntry = gamelines && gamelines[id];
    return {
      id,
      sport: (g.sport || 'nba').toLowerCase(),
      live,
      score: g.score ? { away: g.score.away, home: g.score.home } : undefined,
      clock: g.clock || undefined,
      away: { abbr: g.awayTeam?.abbreviation || '', name: g.awayTeam?.name || '' },
      home: { abbr: g.homeTeam?.abbreviation || '', name: g.homeTeam?.name || '' },
      time: formatGameTime(g.gameTime),
      venue: g.venue || undefined,
      lines: mapGameLines(linesEntry),
      props: mapGradedProps(grades, g),
      // Session 43 — design enhanced-card fields (consumed by vyndr/GameCard;
      // legacy GameCard ignores the extras). playerStrips = props grouped so the
      // name appears once; pitchers = MLB probables when published.
      playerStrips: groupPropsByPlayer(mapGradedProps(grades, g)),
      pitchers: mapPitchers({ ...g, sport: g.sport }),
      streaks: mapStreaks(streaks, g),
    };
  });
}

function mapGradedProps(grades, game) {
  if (!Array.isArray(grades)) return [];
  const h = (game.homeTeam?.abbreviation || '').toUpperCase();
  const a = (game.awayTeam?.abbreviation || '').toUpperCase();
  return grades
    .filter((p) => {
      const t = (p.team || '').toUpperCase();
      return !t || t === h || t === a;
    })
    .map((p) => ({ player: p.player, stat: p.stat, line: p.line, grade: p.grade, side: p.side || 'Over', delta: p.delta }));
}

function mapStreaks(streaks, game) {
  if (!Array.isArray(streaks)) return [];
  const h = (game.homeTeam?.abbreviation || '').toUpperCase();
  const a = (game.awayTeam?.abbreviation || '').toUpperCase();
  return streaks
    .filter((s) => {
      const t = (s.team || '').toUpperCase();
      return t && (t === h || t === a);
    })
    .map((s) => ({ player: s.player, text: s.text || s.description || '' }));
}

/**
 * Group graded props by player → the design's enhanced-card `playerStrips`
 * (Session 43): player name once, archetype + stats placeholder, all props on
 * one line. `archetypeLookup(player)` is optional (sync) — when absent the
 * strip renders without an archetype badge (still valid).
 */
function groupPropsByPlayer(props, archetypeLookup) {
  if (!Array.isArray(props)) return [];
  const byPlayer = {};
  const order = [];
  for (const p of props) {
    if (!p || !p.player) continue;
    if (!byPlayer[p.player]) {
      const archetype = typeof archetypeLookup === 'function' ? archetypeLookup(p.player) : undefined;
      byPlayer[p.player] = {
        player: p.player,
        team: p.team || '',
        archetype: archetype || undefined,
        stats: [], // season stats wired when the stats cache lands (Session 44)
        props: [],
      };
      order.push(p.player);
    }
    byPlayer[p.player].props.push({
      stat: p.stat,
      line: p.line,
      side: (p.side || 'Over').toString().charAt(0).toUpperCase(),
      grade: p.grade,
    });
  }
  return order.map((name) => byPlayer[name]);
}

/**
 * Map an MLB schedule game's probable pitchers → the GameCard `pitchers` shape.
 * Returns undefined for non-MLB or when no probables are published.
 */
function mapPitchers(game) {
  if (!game || String(game.sport || '').toLowerCase() !== 'mlb') return undefined;
  const a = game.away?.probablePitcher || game.awayPitcher;
  const h = game.home?.probablePitcher || game.homePitcher;
  if (!a && !h) return undefined;
  const one = (p, era, arch) => ({
    name: (p && (p.name || p.fullName)) || (typeof p === 'string' ? p : '') || 'TBD',
    era: era != null ? String(era) : (p && p.era != null ? String(p.era) : '—'),
    archetype: arch || (p && p.archetype) || undefined,
  });
  return {
    away: one(a, game.awayPitcherERA, game.awayPitcherArchetype),
    home: one(h, game.homePitcherERA, game.homePitcherArchetype),
  };
}

/**
 * Should this game still show on the slate (Session 44)? Upcoming + live games
 * always show; a COMPLETED game is dropped once it's more than 24h old, so a
 * 5-day-old FINAL never lingers on the dashboard. Unknown/missing date → keep
 * (degrade open). `now` is injectable for tests.
 */
function isRelevantGame(game, now = Date.now()) {
  if (!game) return false;
  const state = String(game.state || game.status || '').toLowerCase();
  const isFinal = state === 'final' || state === 'post' || state === 'closed' || state === 'complete';
  if (!isFinal) return true;
  const raw = game.date || game.gameTime || game.commence_time || game.startTime;
  const t = raw ? new Date(raw).getTime() : NaN;
  if (Number.isNaN(t)) return true; // no parseable date → don't hide
  return (now - t) / 3_600_000 < 24;
}

// ── Pre-graded snapshot overlay (Session 45) ────────────────────────
// Session 46/47 — key by the normalized name (nicknames/accents/periods/parens)
// so variants merge; DISPLAY the de-dotted, paren-stripped form.
const { nameKey, normalizeName } = require('./playerName');
const displayName = (raw) => normalizeName(raw).display || String(raw || '');
const gradeKey = (player, stat) => `${nameKey(player)}|${String(stat || '').toLowerCase()}`;
const sideCh = (dir) => (String(dir || 'over').toLowerCase() === 'under' ? 'U' : 'O');

/** Index snapshot grades by player|stat → the locked grade record. */
function indexGrades(grades) {
  const map = {};
  for (const g of grades || []) {
    map[gradeKey(g.player || g.player_name, g.stat_type || g.stat)] = g;
  }
  return map;
}

/** Index line deltas by player|stat|side → delta record. */
function indexDeltas(deltas) {
  const map = {};
  for (const d of deltas || []) {
    map[`${gradeKey(d.player, d.stat)}|${d.side}`] = d;
  }
  return map;
}

const STAT_SHORT = {
  total_bases: 'TB', home_runs: 'HR', hits: 'Hits', rbi: 'RBI', runs: 'Runs',
  strikeouts: 'Ks', hits_allowed: 'HA', earned_runs: 'ER', innings_pitched: 'IP',
  stolen_bases: 'SB', points: 'Pts', rebounds: 'Reb', assists: 'Ast', threes: '3PT',
  steals: 'Stl', blocks: 'Blk', pra: 'PRA', turnovers: 'TO',
};
function statShort(stat) {
  if (!stat) return '';
  return STAT_SHORT[stat] || String(stat).replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

/** Relative "Graded Xh ago" from an ISO timestamp. */
function gradedAgo(iso, now = Date.now()) {
  const t = iso ? new Date(iso).getTime() : NaN;
  if (Number.isNaN(t)) return '';
  const mins = Math.max(0, Math.round((now - t) / 60000));
  if (mins < 1) return 'just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.round(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.round(hrs / 24)}d ago`;
}

/** Team-identity match by nickname token (last word) — "New York Yankees"
 *  ↔ "Yankees"; exact string match also accepted. */
function slateTeamsMatch(a, b) {
  if (!a || !b) return false;
  const sa = String(a).toLowerCase(), sb = String(b).toLowerCase();
  if (sa === sb) return true;
  return teamMascot(a) !== '' && teamMascot(a) === teamMascot(b);
}

/**
 * Build pre-graded `playerStrips` for one game by OVERLAYING the snapshot's
 * locked grades onto the game's odds-derived props (which already carry the
 * correct game grouping). Each prop is either graded (grade + gradedAt + delta)
 * or `awaiting:true` (no snapshot match yet → "Awaiting next read", no Read
 * button). Archetype comes from the snapshot's per-player classification.
 *
 * Session 59 (work-order 1.6) — THE JOIN INVARIANT: when the snapshot knows
 * the player's REAL team (grades carry `team` from the stats resolve) and
 * the caller passes the game's participants (`gameTeams`), a prop whose
 * player does NOT belong to either team is DROPPED from the card entirely —
 * a bad feed row must not render a TB player under MIL@PIT. Props without
 * team info are kept (can't verify ≠ wrong).
 */
/**
 * @param {Array<object>} gameProps
 * @param {Record<string, any>} gradeIndex
 * @param {Record<string, any>} deltaIndex
 * @param {number} [now]
 * @param {{home?: string, away?: string} | null} [gameTeams]
 * @param {{lineups?: {byPlayer: Record<string, {status: string, slot?: number}>, postedTeams: string[]}, injuries?: Record<string, {status: string, detail?: string|null}>} | null} [viability]
 */
function buildPlayerStripsFromProps(gameProps, gradeIndex, deltaIndex, now = Date.now(), gameTeams = null, viability = null) {
  const byPlayer = {};
  const order = [];
  // Session 64 (A1-S5) — PROP VIABILITY resolution per player:
  //   lineups.byPlayer hit → CONFIRMED (slot n)
  //   team posted, player absent → NOT_IN (grade renders dead)
  //   team not posted → PROJECTED. Absent feeds → no chips at all.
  const lineupStatusFor = (pk, team) => {
    const lu = viability && viability.lineups;
    if (!lu || !lu.byPlayer || Object.keys(lu.byPlayer).length === 0) return null;
    if (lu.byPlayer[pk]) return lu.byPlayer[pk];
    const posted = team && Array.isArray(lu.postedTeams)
      && lu.postedTeams.some((t) => slateTeamsMatch(t, team));
    return posted ? { status: 'not_in' } : { status: 'projected' };
  };
  const injuryFor = (pk) => (viability && viability.injuries && viability.injuries[pk]) || null;
  for (const p of gameProps || []) {
    if (!p || !p.player) continue;
    // Session 46 — group by the normalized key so name variants ("A.J. Ewing"
    // / "AJ Ewing") merge into ONE strip; display the longest seen variant.
    const pk = nameKey(p.player);
    const rec = gradeIndex[gradeKey(p.player, p.stat_type || p.stat)];
    // Join guard: known player team that isn't in this game → bad row, drop.
    const knownTeam = (rec && rec.team) || p.team || '';
    if (knownTeam && gameTeams && (gameTeams.home || gameTeams.away)) {
      const inGame = slateTeamsMatch(knownTeam, gameTeams.home) || slateTeamsMatch(knownTeam, gameTeams.away);
      if (!inGame) continue;
    }
    if (!byPlayer[pk]) {
      byPlayer[pk] = {
        player: displayName(p.player),
        team: knownTeam,
        archetype: rec && rec.archetype ? { primary: rec.archetype } : undefined,
        // Wave 2A — real headshot id threaded from the snapshot grade
        // (MLBAM playerId / ESPN espnId). Absent → PlayerAvatar monogram.
        playerId: (rec && rec.playerId != null ? rec.playerId : undefined),
        espnId: (rec && rec.espnId != null ? rec.espnId : undefined),
        // Wave 2B — a RESOLVED absolute ESPN headshot URL (preferred over the
        // constructed (sport,id) URL). Absent → the id/monogram path stands.
        headshotUrl: (rec && rec.headshotUrl ? rec.headshotUrl : undefined),
        lineup: lineupStatusFor(pk, knownTeam),
        injury: injuryFor(pk),
        stats: [],
        props: [],
      };
      order.push(pk);
    } else {
      // Display the longest (most complete) de-dotted variant seen.
      const cand = displayName(p.player);
      if (cand.length > String(byPlayer[pk].player).length) byPlayer[pk].player = cand;
      if (!byPlayer[pk].archetype && rec && rec.archetype) byPlayer[pk].archetype = { primary: rec.archetype };
      // Fill an id from a later graded row if the first row lacked one.
      if (byPlayer[pk].playerId == null && rec && rec.playerId != null) byPlayer[pk].playerId = rec.playerId;
      if (byPlayer[pk].espnId == null && rec && rec.espnId != null) byPlayer[pk].espnId = rec.espnId;
      if (byPlayer[pk].headshotUrl == null && rec && rec.headshotUrl) byPlayer[pk].headshotUrl = rec.headshotUrl;
    }
    if (rec) {
      const side = sideCh(rec.direction);
      const delta = deltaIndex[`${gradeKey(p.player, p.stat_type || p.stat)}|${side}`];
      byPlayer[pk].props.push({
        stat: statShort(rec.stat_type || rec.stat),
        // A1 S11 — the CANONICAL stat key (live-tracking join; `stat` above is
        // the shortened display label and can't be joined on).
        statType: String(rec.stat_type || rec.stat || '').toLowerCase(),
        line: rec.line,
        side,
        grade: rec.grade,
        // Rev 3 flat edge-board (mobile screen 01) — the ranked hero figure.
        // Strict null (never 0-coerced) so an absent edge sorts last, not top.
        edge: (rec.edge_pct != null && Number.isFinite(Number(rec.edge_pct))) ? Number(rec.edge_pct) : null,
        // A1 S3 — the prop's own book + the best available price across the
        // game's book rows for the graded side (null unless ≥2 books at the
        // same current line disagree — see detectBestBook).
        book: p.book || null,
        bestBook: detectBestBook(p.books, side === 'U' ? 'under' : 'over', p.line),
        gradedAt: rec.gradedAt
          ? { ...rec.gradedAt, ago: gradedAgo(rec.gradedAt.timestamp, now) }
          : null,
        delta: delta ? { delta: delta.delta, direction: delta.direction, currentLine: delta.currentLine } : null,
        // Session 55 — settled outcome from the self-learning loop (hit/miss/push
        // + actual stat) once the game completes. null until settled.
        outcome: rec.outcome ? { result: rec.outcome.result, actual: rec.outcome.actual } : null,
        // Session 60 (Phase 2.5) — intraday movement (STEAM/VALUE/revised)
        // + the ORIGINAL grade when a public revision happened.
        movement: rec.movement || null,
        revisedFrom: rec.revised_from_grade || null,
        // S6 (A1 board, ROW-GRAMMAR sub-line) — real captured line history
        // (sparkline, ≥3 points) + last-10 ●/○ vs tonight's locked line.
        history: Array.isArray(rec.history) && rec.history.length > 0 ? rec.history : null,
        last10Dots: Array.isArray(rec.last10_dots) && rec.last10_dots.length > 0 ? rec.last10_dots : null,
      });
    } else {
      byPlayer[pk].props.push({
        stat: statShort(p.stat_type || p.stat),
        statType: String(p.stat_type || p.stat || '').toLowerCase(),
        line: p.line, side: '', grade: null, awaiting: true,
        book: p.book || null,
        bestBook: detectBestBook(p.books, p.direction || 'over', p.line),
      });
    }
  }
  // Session 48 — one prop row per stat (variant dupes like "Ks 5.5" + "Ks 3.5"
  // from "Matt"/"Matthew" collapse). Prefer the graded prop over an awaiting one.
  return order.map((key) => {
    const e = byPlayer[key];
    const byStat = new Map();
    for (const pr of e.props) {
      const sk = String(pr.stat).toLowerCase();
      const ex = byStat.get(sk);
      if (!ex || (pr.grade && !ex.grade)) byStat.set(sk, pr);
    }
    // Session 64 (A1-S5) — NOT-IN visibly kills every graded prop on the
    // strip (struck through + chip in the UI). The locked ledger read is
    // untouched — honesty is SHOWING the read is dead, not deleting it.
    const dead = e.lineup && e.lineup.status === 'not_in';
    const props = [...byStat.values()].map((pr) => (dead && pr.grade ? { ...pr, dead: true } : pr));
    return { ...e, props };
  });
}

// ── DS2 (Design v2) — Dashboard Slate Rebuild engine ────────────────
// Pure, testable functions behind the founder's #1 rebuild: rank the top
// grades on a VARYING signal (#13), promote ONE bold hero per card (#2),
// collapse the dead "Grades post …" repetition (#14), and the NEVER-EMPTY
// hero (#1, Part 6) — first paint ALWAYS proves the model.

const DS2_GRADE_RANK = {
  'A+': 0, A: 1, 'A-': 2, 'B+': 3, B: 4, 'B-': 5, 'C+': 6, C: 7, 'C-': 8, D: 9, F: 10,
};
/** Grade → sortable tier rank (lower = better). Unknown → 99. */
function gradeRankOf(g) {
  const k = String(g == null ? '' : g).trim().toUpperCase();
  return DS2_GRADE_RANK[k] !== undefined ? DS2_GRADE_RANK[k] : 99;
}
const numOr = (v, fallback) => {
  const n = typeof v === 'number' ? v : parseFloat(v);
  return Number.isFinite(n) ? n : fallback;
};

/**
 * #13 — rank tonight's grades by TIER, then the VARYING signal so a leaderboard
 * of near-identical rows stops being noise: confidence desc, then |edge| desc,
 * stable by input order. Drops gradeless rows. Returns at most `limit`.
 */
function selectTopGrades(grades, limit = 10) {
  const arr = (Array.isArray(grades) ? grades : []).filter((g) => g && g.grade);
  const scored = arr.map((g, idx) => ({
    g,
    idx,
    rank: gradeRankOf(g.grade),
    conf: numOr(g.confidence, -1),
    edge: Math.abs(numOr(g.edge, -Infinity)),
  }));
  scored.sort((a, b) => a.rank - b.rank || b.conf - a.conf || b.edge - a.edge || a.idx - b.idx);
  return scored.slice(0, Math.max(0, limit)).map((s) => s.g);
}

/**
 * #1 / Part 6 — build PROVEN receipts from settled ledger rows: only A-tier
 * grades that HIT (a miss never becomes proof). Carries the real result so the
 * receipt is verifiable. Best-grade first. `settledRows` = /api/ledger/model
 * entries (player_name, stat, line, side, grade, outcome, actual_value, …).
 */
function buildHeroReceipts(settledRows, limit = 8) {
  const rows = (Array.isArray(settledRows) ? settledRows : []).filter(
    (r) => r && String(r.outcome || '').toLowerCase() === 'hit' && gradeRankOf(r.grade) <= 2,
  );
  const mapped = rows.map((r) => ({
    player: displayName(r.player_name || r.player || ''),
    stat: r.stat,
    line: r.line,
    side: String(r.side || 'over'),
    grade: r.grade,
    sport: String(r.sport || '').toUpperCase(),
    outcome: 'hit',
    actual: r.actual_value != null ? r.actual_value : null,
    clvResult: r.clv_result || null,
  }));
  mapped.sort((a, b) => gradeRankOf(a.grade) - gradeRankOf(b.grade));
  return mapped.slice(0, Math.max(0, limit));
}

/**
 * #1 / Part 6 — the never-empty hero engine. Tonight's ranked top grades win;
 * when tonight is empty, fall back to yesterday's PROVEN A-tier receipts; only
 * `empty` when both are absent. First paint ALWAYS proves the model when any
 * settled proof exists.
 */
function heroFallbackState(tonightGrades, settledRows, limit = 10) {
  const tonight = selectTopGrades(tonightGrades, limit);
  if (tonight.length > 0) return { mode: 'tonight', items: tonight };
  const receipts = buildHeroReceipts(settledRows, Math.min(limit, 8));
  if (receipts.length > 0) return { mode: 'receipts', items: receipts };
  return { mode: 'empty', items: [] };
}

/**
 * #14 — collapse the dead per-prop "Grades post …" repetition. When a card has
 * NO graded reads yet (every prop awaiting), returns a single summary
 * ({ count, players, statLabels }) so the UI renders ONE compact line instead
 * of six identical rows. Any graded prop present → null (there are real reads
 * to show). No awaiting props → null.
 */
function pendingSummary(strips) {
  const list = Array.isArray(strips) ? strips : [];
  let awaiting = 0;
  let graded = 0;
  const players = new Set();
  const statLabels = [];
  for (const s of list) {
    for (const p of s.props || []) {
      if (p.grade) graded += 1;
      else if (p.awaiting) {
        awaiting += 1;
        players.add(s.player);
        if (statLabels.length < 6) statLabels.push(`${p.stat} ${p.line}`);
      }
    }
  }
  if (graded > 0 || awaiting === 0) return null;
  return { count: awaiting, players: players.size, statLabels };
}

/**
 * #2 — the ONE bold hero per card: the single highest-tier LIVE graded prop
 * (dead/not-in reads never lead). Returns { player, team, archetype, stat,
 * line, side, grade } or null when the card has no graded reads.
 */
function topReadForCard(strips) {
  let best = null;
  for (const s of Array.isArray(strips) ? strips : []) {
    for (const p of s.props || []) {
      if (!p.grade || p.dead) continue;
      const rank = gradeRankOf(p.grade);
      if (!best || rank < best.rank) {
        best = {
          rank,
          player: s.player,
          team: s.team || '',
          archetype: s.archetype || null,
          stat: p.stat,
          line: p.line,
          side: p.side || 'O',
          grade: p.grade,
        };
      }
    }
  }
  if (!best) return null;
  const { rank, ...rest } = best; // eslint-disable-line no-unused-vars
  return rest;
}

// ── MLB probable pitchers (Session 46) ──────────────────────────────
const teamToken = (name) => String(name == null ? '' : name).toLowerCase().replace(/[^a-z0-9 ]/g, '').trim();
const teamMascot = (name) => { const t = teamToken(name).split(' ').filter(Boolean); return t.length ? t[t.length - 1] : ''; };

/** Index probable-pitcher games by team (full + mascot) → { pitcher, era }. */
function buildPitcherMap(pitcherGames) {
  const map = {};
  for (const g of pitcherGames || []) {
    for (const side of [g.home, g.away]) {
      if (!side || !side.pitcher || !side.team) continue;
      const entry = { name: side.pitcher, era: side.era != null ? String(side.era) : null };
      map[teamToken(side.team)] = entry;
      const m = teamMascot(side.team);
      if (m && map[m] == null) map[m] = entry;
    }
  }
  return map;
}

/** Resolve { away, home } pitchers for a game's team names → GameCard shape. */
function pitchersForGameTeams(awayTeam, homeTeam, pitcherMap) {
  if (!pitcherMap) return undefined;
  const look = (name) => pitcherMap[teamToken(name)] || pitcherMap[teamMascot(name)] || null;
  const a = look(awayTeam);
  const h = look(homeTeam);
  if (!a && !h) return undefined;
  const one = (p) => ({ name: (p && p.name) || 'TBD', era: (p && p.era) || '—' });
  return { away: one(a), home: one(h) };
}

// ── Rev 3 — flat EDGE BOARD (mobile screen 01) ──────────────────────────
// Design's mobile board is a FLAT, edge-ranked list (all graded props across
// every game, sorted by edge), not game-grouped cards. This flattens the
// GameCardData[] the Slate already assembled (grade→game join already done)
// into ranked rows. Pure + testable. Sort: edge desc (STRICT null sorts LAST —
// never 0-coerced to the top), grade rank as tiebreak.
const EDGE_GRADE_RANK = { 'A+': 0, A: 1, 'A-': 2, 'B+': 3, B: 4, 'B-': 5, C: 6, D: 7, F: 8 };
function edgeGradeRank(g) {
  return EDGE_GRADE_RANK[g] != null ? EDGE_GRADE_RANK[g] : 9;
}
// Ceiling for a plausible prop-market edge; beyond it the value is a broken
// placeholder, not a signal (mirrored in MobileEdgeBoard.EdgeCell).
const EDGE_BOARD_SANE_MAX = 40;

function flattenToEdgeBoard(cards) {
  const rows = [];
  for (const c of Array.isArray(cards) ? cards : []) {
    const away = (c.away && c.away.abbr) || '';
    const home = (c.home && c.home.abbr) || '';
    for (const strip of (c.playerStrips || [])) {
      for (const p of (strip.props || [])) {
        if (!p || !p.grade || p.awaiting || p.dead) continue; // only live graded rows
        rows.push({
          player: strip.player,
          team: strip.team || '',
          stat: p.stat,
          statType: p.statType,
          line: p.line,
          side: p.side || 'O',
          grade: p.grade,
          // A real prop edge is single-digit %, never past ~40. Values beyond
          // that are the pipeline's miscalibrated placeholder (live: 60/100/140)
          // — treat as absent so the board neither displays nor RANKS on a fake
          // edge. When absent, rows fall through to the grade-rank tiebreak.
          edge: (p.edge != null && Number.isFinite(p.edge) && Math.abs(p.edge) <= EDGE_BOARD_SANE_MAX) ? p.edge : null,
          sport: c.sport || '',
          away,
          home,
          live: !!c.live,
          outcome: p.outcome || null,
          movement: p.movement || null,
          playerId: strip.playerId,
          espnId: strip.espnId,
          headshotUrl: strip.headshotUrl,
        });
      }
    }
  }
  rows.sort((a, b) => {
    const ea = a.edge == null ? -Infinity : a.edge;
    const eb = b.edge == null ? -Infinity : b.edge;
    if (eb !== ea) return eb - ea;
    return edgeGradeRank(a.grade) - edgeGradeRank(b.grade);
  });
  return rows.map((r, i) => ({ ...r, rank: i + 1 }));
}

/** Breadth-strip numbers for the mobile board header (Design screen 01):
 *  EDGES = count of A/B-tier graded rows · GAMES = games with ≥1 graded row.
 *  AVG CLV is NOT computed here (comes from /api/accuracy; honest '—' when
 *  absent — Design draws it but the row-level model doesn't produce per-slate
 *  CLV). Never fabricates. */
function edgeBoardBreadth(rows, games) {
  const list = Array.isArray(rows) ? rows : [];
  const edges = list.filter((r) => {
    const t = String(r.grade || '')[0];
    return t === 'A' || t === 'B';
  }).length;
  return { edges, games: Array.isArray(games) ? games.length : 0 };
}

module.exports = {
  parseAmericanOdds,
  detectBestLines,
  detectBestBook,
  mapGameLines,
  mapScheduleToGameCards,
  formatGameTime,
  groupPropsByPlayer,
  mapPitchers,
  isRelevantGame,
  indexGrades,
  indexDeltas,
  gradeKey,
  statShort,
  gradedAgo,
  buildPlayerStripsFromProps,
  flattenToEdgeBoard,
  edgeBoardBreadth,
  edgeGradeRank,
  buildPitcherMap,
  pitchersForGameTeams,
  // DS2 — dashboard rebuild engine.
  gradeRankOf,
  selectTopGrades,
  buildHeroReceipts,
  heroFallbackState,
  pendingSummary,
  topReadForCard,
};
