☰

Poker Hold'em

Poker Hold'em · Torn City poker HUD (read-only overlay): mandatory 1,000,000-trial Monte Carlo in pooled Web Workers, pot odds + EV, real card images from the viewed page, compact visual outs, opponent trends, decision debrief, hand replay + counterfactual EV, training drills, runtime diagnostics, session + bankroll tracking. No network requests, no transport hooks, no automation: everything stays on your device.

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         Poker Hold'em
// @namespace    https://torn.com/
// @version      20.11.2026
// @description  Poker Hold'em · Torn City poker HUD (read-only overlay): mandatory 1,000,000-trial Monte Carlo in pooled Web Workers, pot odds + EV, real card images from the viewed page, compact visual outs, opponent trends, decision debrief, hand replay + counterfactual EV, training drills, runtime diagnostics, session + bankroll tracking. No network requests, no transport hooks, no automation: everything stays on your device.
// @author       Gatsuke [4326255]
// @match        *://www.torn.com/page.php?sid=holdem*
// @match        *://torn.com/page.php?sid=holdem*
// @run-at       document-start
// @grant        none
// @license      All Rights Reserved. Proprietary, no modification, no redistribution
// @supportURL   https://www.torn.com/forums.php?p=forums&f=67&b=0&a=0
// @noframes
// ==/UserScript==


(() => {
  'use strict';

  const SCRIPT_VERSION = '20.11.2026';

  if (window.__tnp_loaded__) return;
  window.__tnp_loaded__ = true;

  const DBG = (() => {
    let on = false;
    try { on = (typeof localStorage !== 'undefined' && localStorage.getItem('tnp_debug') === '1'); } catch (e) { }
    return {
      get on() { return on; },
      enable() { on = true; try { localStorage.setItem('tnp_debug', '1'); } catch (e) { } },
      disable() { on = false; try { localStorage.removeItem('tnp_debug'); } catch (e) { } },
      log(...args) { if (on) console.log('[TNP]', ...args); },
      warn(...args) { if (on) console.warn('[TNP]', ...args); },
      info(...args) { if (on) console.info('[TNP]', ...args); },
      debug(...args) { if (on) console.debug('[TNP]', ...args); }
    };
  })();
  const tlog = (...args) => DBG.log(...args);
  const twarn = (...args) => DBG.warn(...args);
  const tinfo = (...args) => DBG.info(...args);
  const tdebug = (...args) => DBG.debug(...args);

  if (typeof window !== 'undefined') {
    window.__TNP_DEBUG__ = DBG;
  }

  const provenance = {};
  const PROV_FRESH_MS = 15000;
  const provSet = (field, value, source, status, detail) => {
    provenance[field] = {
      value,
      source: String(source || ''),
      status: String(status || 'unknown'),
      detail: detail || '',
      at: Date.now()
    };
  };
  const provClassify = (entry, now) => {
    if (!entry) return 'unavailable';
    const age = now - entry.at;
    if (entry.status === 'known' || entry.status === 'fresh') return age <= PROV_FRESH_MS ? 'fresh' : 'stale';
    if (entry.status === 'inferred') return age <= PROV_FRESH_MS ? 'inferred' : 'stale';
    if (entry.status === 'stale') return 'stale';
    return 'unavailable';
  };
  const provenanceReport = () => {
    const now = Date.now();
    const order = ['holeCards', 'boardCards', 'pot', 'toCall', 'activeOpponents', 'heroStack',
      'effectiveStack', 'position', 'heroTurn', 'table', 'actionLog', 'equity'];
    const rows = [];
    for (const key of order.concat(Object.keys(provenance).filter(k => !order.includes(k)))) {
      const e = provenance[key];
      if (!e) { rows.push({ field: key, state: 'unavailable', source: '', ageMs: null, value: null }); continue; }
      if (rows.some(r => r.field === key)) continue;
      rows.push({
        field: key,
        state: provClassify(e, now),
        source: e.source,
        detail: e.detail,
        ageMs: now - e.at,
        value: e.value
      });
    }
    return rows;
  };
  const provenanceSummary = () => {
    const rows = provenanceReport();
    const fresh = rows.filter(r => r.state === 'fresh').length;
    const stale = rows.filter(r => r.state === 'stale').length;
    const inferred = rows.filter(r => r.state === 'inferred').length;
    const unavailable = rows.filter(r => r.state === 'unavailable').length;
    const confidence = fresh / Math.max(1, fresh + stale + inferred + unavailable);
    return { fresh, stale, inferred, unavailable, confidence };
  };

  const RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
  const SUITS = ['♠', '♥', '♦', '♣'];
  const RANK_VALS = { '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14 };

  const MC_MANDATE = Object.freeze({
    totalTrials: 1000000,
    minSamples: 1000000,
    maxSamples: 1000000,
    ciHalfWidth: 0,
    deadlineMs: 120000,
    sliceMs: 10,
    minSlice: 1000,
    progressEvery: 25000,
    deterministic: true
  });
  const mcTargetsNow = () => MC_MANDATE;

      const scenarioSeed = (hole, board, opponents, ranges) => {
    let h = 2166136261 >>> 0;
    const str = `${(hole || []).join('')}|${(board || []).join('')}|${opponents | 0}|${(ranges || []).map(r => (r === null || r === undefined) ? -1 : Math.round(r * 1e6)).join(',')}`;
    for (let i = 0; i < str.length; i++) {
      h ^= str.charCodeAt(i);
      h = Math.imul(h, 16777619) >>> 0;
    }
    return h || 1;
  };

  const MC_POOL_SIZE = Math.min(8, Math.max(1,
    ((typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 2) - 1));

  const EXACT_FLOP_CAP = 1200000;
  const EXACT_FLOP_DEADLINE_MS = 3000;

          const TABLE_CATALOG = Object.freeze([
    { name: 'Oligarch',        id: 16, slug: 'oligarch',        sb: 5_000_000_000, bb: 10_000_000_000, minBuy: 500_000_000_000, maxBuy: 2_000_000_000_000, timer: 30, seats: 5 },
    { name: 'Fire Pit',        id: 14, slug: 'fire_pit',        sb: 1_250_000_000, bb:  2_500_000_000, minBuy: 125_000_000_000, maxBuy:   500_000_000_000, timer: 15, seats: 9 },
    { name: 'High Rollers',    id: 15, slug: 'high_rollers',    sb:   500_000_000, bb:  1_000_000_000, minBuy:  50_000_000_000, maxBuy:   200_000_000_000, timer: 15, seats: 9 },
    { name: 'Slow Cooker',     id: 13, slug: 'slow_cooker',     sb:   250_000_000, bb:    500_000_000, minBuy:  25_000_000_000, maxBuy:   100_000_000_000, timer: 30, seats: 9 },
    { name: 'Juan on Juan',    id: 19, slug: 'juan_on_juan',    sb:   250_000_000, bb:    500_000_000, minBuy:  25_000_000_000, maxBuy:   100_000_000_000, timer: 30, seats: 2 },
    { name: "Cat's Chance",    id: 25, slug: 'cats_chance',     sb:   125_000_000, bb:    250_000_000, minBuy:  12_500_000_000, maxBuy:    50_000_000_000, timer: 15, seats: 9 },
    { name: 'Tripod',          id: 12, slug: 'tripod',          sb:    50_000_000, bb:    100_000_000, minBuy:   5_000_000_000, maxBuy:    20_000_000_000, timer: 15, seats: 3 },
    { name: 'Comatose Cove',   id: 22, slug: 'comatose_cove',   sb:    50_000_000, bb:    100_000_000, minBuy:   5_000_000_000, maxBuy:    20_000_000_000, timer: 30, seats: 6 },
    { name: 'River Wizard',    id: 28, slug: 'river_wizard',    sb:    50_000_000, bb:    100_000_000, minBuy:   5_000_000_000, maxBuy:    20_000_000_000, timer: 15, seats: 9 },
    { name: 'Old Folks Home',  id: 21, slug: 'old_folks_home',  sb:    25_000_000, bb:     50_000_000, minBuy:   2_500_000_000, maxBuy:    10_000_000_000, timer: 30, seats: 6 },
    { name: 'Duel at Dawn',    id: 18, slug: 'duel_at_dawn',    sb:     5_000_000, bb:     10_000_000, minBuy:     500_000_000, maxBuy:     2_000_000_000, timer: 15, seats: 2 },
    { name: 'Fourplay',        id: 17, slug: 'fourplay',        sb:     5_000_000, bb:     10_000_000, minBuy:     500_000_000, maxBuy:     2_000_000_000, timer: 15, seats: 4 },
    { name: "Old 'n' Slow",    id: 11, slug: 'old_n_slow',      sb:     5_000_000, bb:     10_000_000, minBuy:     500_000_000, maxBuy:     2_000_000_000, timer: 30, seats: 6 },
    { name: 'Boom or Bust',    id: 20, slug: 'boom_or_bust',    sb:     2_500_000, bb:      5_000_000, minBuy:     250_000_000, maxBuy:     1_000_000_000, timer: 15, seats: 9 },
    { name: 'Six of the Best', id: 27, slug: 'six_of_the_best', sb:       500_000, bb:      1_000_000, minBuy:      50_000_000, maxBuy:     200_000_000, timer: 15, seats: 6 },
    { name: 'Tight Knit',      id:  8, slug: 'tight_knit',      sb:       250_000, bb:        500_000, minBuy:      25_000_000, maxBuy:     100_000_000, timer: 15, seats: 6 },
    { name: 'Quickdraw',       id:  7, slug: 'quickdraw',       sb:       125_000, bb:        500_000, minBuy:      12_500_000, maxBuy:       50_000_000, timer: 15, seats: 9,
     anomaly: 'Wiki prints stakes as "$1.25k / $5k". All 26 other tables run SB = BB/2 and buy-in = 50–200×BB; both hold for Quickdraw only if the intended stakes are $1.25k/$2.5k. Encoded verbatim; treat as unverified.' },
    { name: 'E-asy Street',   id: 24, slug: 'easy_street',     sb:        25_000, bb:         50_000, minBuy:       2_500_000, maxBuy:      10_000_000, timer: 15, seats: 9 },
    { name: 'Sprinkles',      id:  5, slug: 'sprinkles',       sb:        12_500, bb:         25_000, minBuy:       1_250_000, maxBuy:       5_000_000, timer: 15, seats: 9 },
    { name: 'Five Star Man',  id: null, slug: null,            sb:         5_000, bb:         10_000, minBuy:         500_000, maxBuy:       2_000_000, timer: 15, seats: 5 },
    { name: 'Broke Jokes',    id: 26, slug: 'broke_jokes',     sb:         2_500, bb:          5_000, minBuy:         250_000, maxBuy:       1_000_000, timer: 15, seats: 9 },
    { name: 'Hobo Holdem',    id:  3, slug: 'hobo_holdem',     sb:         1_250, bb:          2_500, minBuy:         125_000, maxBuy:         500_000, timer: 15, seats: 9 },
    { name: 'Newbie Corner',  id:  2, slug: 'newbie_corner',   sb:           500, bb:          1_000, minBuy:          50_000, maxBuy:         200_000, timer: 30, seats: 9 },
    { name: 'Gatling Gun',    id:  6, slug: 'gatling_gun',     sb:        50_000, bb:        100_000, minBuy:       5_000_000, maxBuy:      20_000_000, timer: 15, seats: 9 },
    { name: 'Periodic',       id: 23, slug: 'periodic',        sb:     5_000_000, bb:     10_000_000, minBuy:       500_000_000, maxBuy:     2_000_000_000, timer: 30, seats: 9 },
    { name: 'Pound It',       id: 10, slug: 'pound_it',        sb:    12_500_000, bb:     25_000_000, minBuy:    1_250_000_000, maxBuy:     5_000_000_000, timer: 15, seats: 9 },
    { name: 'Ballsy',         id: 9, slug: 'ballsy',          sb:     1_250_000, bb:      2_500_000, minBuy:     125_000_000, maxBuy:     500_000_000, timer: 15, seats: 9 },
    { name: '8-bit',          id: 4, slug: '8-bit',            sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null,
     anomaly: 'Added from the client bundle table-art map. Stakes not published in any source this audit could verify; identified by table art or channel id only.' },
    { name: 'Spilled Milk',   id: 32, slug: 'spilled_milk',    sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Dive Bar',       id: 33, slug: 'dive_bar',        sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Lost at Sea',    id: 34, slug: 'lost_at_sea',     sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Jaded',          id: 35, slug: 'jaded',           sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Hell For',       id: 36, slug: 'hell_for',        sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Beach Please',   id: 37, slug: 'beach_please',    sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Cut the Cord',   id: 38, slug: 'cut_the_cord',    sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Natural Talent', id: 39, slug: 'natural_talent',  sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Luxe',           id: 40, slug: 'luxe',            sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' },
    { name: 'Bloody Hell',    id: 41, slug: 'bloody_hell',     sb: null, bb: null, minBuy: null, maxBuy: null, timer: null, seats: null, anomaly: 'Stakes unverified; identified by table art or channel id only.' }
  ]);

      const tableKeyOf = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
  const TABLE_BY_KEY = Object.freeze((() => {
    const m = new Map();
    for (const t of TABLE_CATALOG) {
      m.set(tableKeyOf(t.name), t);
      if (t.slug) m.set(tableKeyOf(t.slug), t);
    }
    return m;
  })());

  const identifyTable = (sbDollars, bbDollars, opts = 0) => {

    const o = (typeof opts === 'number') ? { players: opts } : (opts || {});
    const players = Math.max(0, o.players | 0);
    const seats = Math.max(0, o.seats | 0);
    const minSeats = Math.max(0, o.minSeats | 0);
    const speed = Math.max(0, o.speed | 0);
    if (!(bbDollars > 0)) return null;
    const sbCents = Math.round((sbDollars || 0) * 100), bbCents = Math.round(bbDollars * 100);
    let byBoth = [], byBB = [];
    for (const t of TABLE_CATALOG) {
      if (t.bb == null || t.sb == null) continue;
      if (t.bb === bbCents && t.sb === sbCents) byBoth.push(t);
      else if (t.bb === bbCents) byBB.push(t);
    }
    let pool = byBoth.length ? byBoth : byBB;
    if (!pool.length) return null;
    const basis = [`stakes ${(sbDollars || 0).toLocaleString()}/${bbDollars.toLocaleString()}${byBoth.length ? '' : ' (big blind only)'}`];

    if (seats > 0) {
      const exact = pool.filter((t) => t.seats === seats);
      if (exact.length) {
        pool = exact;
        basis.push(`seat count ${seats} (game list)`);
      } else {
        basis.push(`seat count ${seats} matched no same-stakes table: ignored`);
      }
    }

                if (minSeats > 1 && pool.length > 1) {
      const fitting = pool.filter((t) => t.seats >= minSeats);
      if (fitting.length && fitting.length < pool.length) {
        pool = fitting;
        basis.push(`at least ${minSeats} seats observed this session`);
      }
    }

    if (speed > 0 && pool.length > 1) {
      const spd = pool.filter((t) => t.timer === speed);
      if (spd.length && spd.length < pool.length) {
        pool = spd;
        basis.push(`action timer ${speed}s`);
      }
    }

    if (players > 0 && pool.length > 1) {
      const fitting = pool.filter((t) => t.seats >= players);
      if (fitting.length && fitting.length < pool.length) {
        pool = fitting;
        basis.push(`${players} seated (lower bound; smaller-capacity tables excluded)`);
      } else {
        basis.push(`${players} seated (lower bound, excluded nothing here)`);
      }
    }
    if (pool.length > 1 && minSeats > 1) {
      const exactCap = pool.filter((t) => t.seats === minSeats);
      if (exactCap.length === 1) {
        pool = exactCap;
        basis.push(`capacity ${minSeats} matches the highest seat slot observed`);
      }
    }
    if (pool.length > 1) {
      const names = pool.map((t) => t.name).join(' / ');
      basis.push(`same stakes match ${pool.length} tables with different seat counts (${names}); refusing to alias them without a seat count`);
      return {
        ...pool[0], name: `Ambiguous (${names})`,
        seats: null, unresolved: true,
        alternates: pool.slice(1).map((t) => t.name),
        confidence: 'ambiguous', basis
      };
    }
    const primary = pool[0];
    const alternates = pool.slice(1).map((t) => t.name);
    const confidence = seats > 0 ? 'confirmed' : 'likely';
    return { ...primary, alternates, confidence, basis };
  };

  const PREFLOP_EQUITY_169 = Object.freeze(JSON.parse(
    '{"22":0.5034,"33":0.5371,"44":0.5698,"55":0.6039,"66":0.6326,"77":0.6618,"88":0.6913,"99":0.7208,"TT":0.75,"JJ":0.7745,"QQ":0.8002,"KK":0.8231,' +
    '"AA":0.8519,"AKs":0.6696,"AQs":0.662,"AJs":0.6544,"ATs":0.6459,"A9s":0.6261,"A8s":0.6195,"A7s":0.6102,"A6s":0.5982,"A5s":0.5986,"A4s":0.5897,"A3s":0.5817,' +
    '"A2s":0.5737,"KQs":0.6341,"KJs":0.6253,"KTs":0.6173,"K9s":0.6,"K8s":0.5833,"K7s":0.5748,"K6s":0.566,"K5s":0.5579,"K4s":0.549,"K3s":0.5401,"K2s":0.5316,' +
    '"QJs":0.6032,"QTs":0.5946,"Q9s":0.5773,"Q8s":0.5605,"Q7s":0.5432,"Q6s":0.5364,"Q5s":0.5279,"Q4s":0.519,"Q3s":0.5102,"Q2s":0.5018,"JTs":0.5753,"J9s":0.5572,' +
    '"J8s":0.5401,"J7s":0.5231,"J6s":0.5063,"J5s":0.5,"J4s":0.4899,"J3s":0.4824,"J2s":0.473,"T9s":0.5401,"T8s":0.5238,"T7s":0.5073,"T6s":0.4887,"T5s":0.472,' +
    '"T4s":0.466,"T3s":0.457,"T2s":0.4479,"98s":0.5074,"97s":0.4901,"96s":0.4749,"95s":0.4568,"94s":0.4387,"93s":0.4329,"92s":0.4244,"87s":0.4801,"86s":0.4628,' +
    '"85s":0.446,"84s":0.4269,"83s":0.4089,"82s":0.4028,"76s":0.4537,"75s":0.4365,"74s":0.4182,"73s":0.4006,"72s":0.3811,"65s":0.4317,"64s":0.4135,"63s":0.3946,' +
    '"62s":0.3769,"54s":0.4154,"53s":0.3963,"52s":0.3789,"43s":0.3865,"42s":0.3687,"32s":0.3602,"AKo":0.6533,"AQo":0.6444,"AJo":0.6353,"ATo":0.6278,"A9o":0.6084,' +
    '"A8o":0.5988,"A7o":0.5886,"A6o":0.5774,"A5o":0.5768,"A4o":0.5676,"A3o":0.5579,"A2o":0.5488,"KQo":0.6137,"KJo":0.6052,"KTo":0.5973,"K9o":0.5775,"K8o":0.5606,' +
    '"K7o":0.5524,"K6o":0.5423,"K5o":0.533,"K4o":0.5236,"K3o":0.5137,"K2o":0.505,"QJo":0.5817,"QTo":0.5728,"Q9o":0.5542,"Q8o":0.5362,"Q7o":0.5177,"Q6o":0.5096,' +
    '"Q5o":0.5012,"Q4o":0.4919,"Q3o":0.4821,"Q2o":0.473,"JTo":0.5524,"J9o":0.5324,"J8o":0.5139,"J7o":0.4971,"J6o":0.4789,"J5o":0.4717,"J4o":0.4618,"J3o":0.4526,' +
    '"J2o":0.4428,"T9o":0.5153,"T8o":0.497,"T7o":0.4784,"T6o":0.461,"T5o":0.4422,"T4o":0.4353,"T3o":0.4255,"T2o":0.4167,"98o":0.4807,"97o":0.4638,"96o":0.4447,' +
    '"95o":0.4275,"94o":0.406,"93o":0.3998,"92o":0.3909,"87o":0.4496,"86o":0.4323,"85o":0.4154,"84o":0.3935,"83o":0.3743,"82o":0.3688,"76o":0.4234,"75o":0.405,' +
    '"74o":0.3855,"73o":0.3662,"72o":0.3456,"65o":0.3987,"64o":0.3799,"63o":0.3609,"62o":0.34,"54o":0.3812,"53o":0.3634,"52o":0.3427,"43o":0.3511,"42o":0.3326,' +
    '"32o":0.3229}'
  ));

  const handClassKey = (c1, c2) => {
    const r1 = c1[0], r2 = c2[0];
    const hi = RANK_VALS[r1] >= RANK_VALS[r2] ? r1 : r2;
    const lo = hi === r1 ? r2 : r1;
    if (hi === lo) return hi + lo;
    return hi + lo + (c1[1] === c2[1] ? 's' : 'o');
  };

  const expandRange = (spec) => {
    const out = new Set();
    const RANK_ORDER = 'AKQJT98765432';
    const pos = (r) => RANK_ORDER.indexOf(r);
    const addPairRange = (from, to) => {

      for (let i = pos(from); i >= pos(to); i--) out.add(RANK_ORDER[i] + RANK_ORDER[i]);
    };

    const addKickerWalk = (hi, loKick, hiKick, so) => {
      for (let k = pos(loKick); k >= pos(hiKick); k--) {
        const klo = RANK_ORDER[k];
        if (klo !== hi && pos(klo) > pos(hi)) out.add(hi + klo + so);
      }
    };
    const parseHand = (h) => {
      const m = h.match(/^([AKQJT2-9])([AKQJT2-9])(s|o)$/);
      if (!m) return null;
      const [, a, b, so] = m;
      const hi = pos(a) < pos(b) ? a : b;
      const lo = hi === a ? b : a;
      return { hi, lo, so };
    };
    for (const tok of spec.split(/[,\s]+/).filter(Boolean)) {
      const plus = tok.endsWith('+');
      const body = plus ? tok.slice(0, -1) : tok;

      if (body.includes('-')) {
        const parts = body.split('-');
        if (parts.length === 2) {
          const A = parseHand(parts[0]), B = parseHand(parts[1]);
          if (A && B && A.so === B.so && A.hi === B.hi) {
            addKickerWalk(A.hi, A.lo, B.lo, A.so);
            continue;
          }
          const pA = parts[0].match(/^([AKQJT2-9])\1$/);
          const pB = parts[1].match(/^([AKQJT2-9])\1$/);
          if (pA && pB) { addPairRange(pA[1], pB[1]); continue; }
        }
        continue;
      }

      const m = body.match(/^([AKQJT2-9])([AKQJT2-9])(s|o)?$/);
      if (!m) continue;
      const [, a, b, so] = m;
      if (a === b) {

        if (plus) addPairRange(a, 'A');
        else out.add(a + a);
      } else if (so) {
        const hi = pos(a) < pos(b) ? a : b;
        const lo = hi === a ? b : a;
        if (plus) addKickerWalk(hi, lo, 'K', so);
        else out.add(hi + lo + so);
      } else {

        const hi = pos(a) < pos(b) ? a : b;
        const lo = hi === a ? b : a;
        out.add(hi + lo + 's');
        out.add(hi + lo + 'o');
      }
    }
    return out;
  };

  const RANGE_CHARTS = Object.freeze({

    open: Object.freeze({
      UTG: expandRange('22+ A5s-AKs KTs+ QTs+ JTs T9s 98s 87s 76s AQo+'),
      MP:  expandRange('22+ A4s+ K8s+ Q8s+ J8s+ T8s+ 97s+ 87s 76s 65s AJo+ KQo'),
      CO:  expandRange('22+ A2s+ K5s+ Q6s+ J7s+ T6s+ 96s+ 86s+ 75s+ 65s 54s ATo+ KJo+ QJo'),
      BTN: expandRange('22+ A2s+ K2s+ Q6s+ J5s+ T5s+ 95s+ 85s+ 75s+ 64s+ 54s 43s A2o+ K8o+ Q8o+ J8o+ T8o+ 98o 87o'),
      SB:  expandRange('22+ A2s+ K2s+ Q4s+ J6s+ T6s+ 96s+ 85s+ 75s+ 64s+ 54s A5o+ K9o+ QTo+ JTo'),
      BB:  expandRange('')
    }),

    defend: Object.freeze({
      UTG: expandRange(''),
      MP:  expandRange('22-JJ AJs+ AQs+ KQs QJs JTs T9s 98s 87s AQo+'),
      CO:  expandRange('22-99 ATs+ A5s KJs+ QJs+ JTs T9s 98s 87s 76s AJo+ KQo'),
      BTN: expandRange('22-99 A2s+ K9s+ QTs+ J9s+ T8s+ 97s+ 87s 76s 65s A9o+ KTo+ QJo JTo'),
      SB:  expandRange('22-99 A5s+ KJs+ QTs+ JTs T9s AQo+'),
      BB:  expandRange('22-99 A2s+ K5s+ Q8s+ J8s+ T8s+ 97s+ 87s 76s 65s A9o+ KTo+ QTo+ JTo T9o')
    }),

    threeBet: Object.freeze({
      UTG: expandRange('QQ+ AKs AKo'),
      MP:  expandRange('QQ+ AKs AQs AKo'),
      CO:  expandRange('JJ+ AQs+ AKo'),
      BTN: expandRange('TT+ AJs+ KQs AQo+'),
      SB:  expandRange('TT+ AJs+ KQs AQo+'),
      BB:  expandRange('99+ ATs+ KQs AJo+')
    }),

    huOpen: Object.freeze({
      BTN: expandRange('22+ A2s+ K2s+ Q2s+ J4s+ T5s+ 95s+ 85s+ 74s+ 63s+ 53s 43s A2o+ K5o+ Q6o+ J7o+ T8o+ 97o+ 87o 76o'),
      BB:  expandRange('22+ A2s+ K2s+ Q4s+ J6s+ T6s+ 96s+ 85s+ 75s+ 64s+ 54s A2o+ K7o+ Q8o+ J8o+ T8o+ 98o')
    }),
    huDefend: Object.freeze({
      BTN: expandRange('22+ A2s+ K2s+ Q2s+ J4s+ T4s+ 94s+ 84s+ 74s+ 63s+ 53s+ 43s A2o+ K2o+ Q4o+ J6o+ T6o+ 96o+ 86o+ 76o 65o'),
      BB:  expandRange('22+ A2s+ K2s+ Q2s+ J4s+ T5s+ 95s+ 85s+ 74s+ 64s+ 54s A2o+ K4o+ Q6o+ J7o+ T7o+ 97o+ 87o 76o')
    })
  });

  const mergeMcPartials = (parts) => {
    let runs = 0, sum = 0, sumSquares = 0;
    let wins = 0, ties = 0, losses = 0;
    let types = null;
    for (const p of parts) {
      if (!p) continue;
      runs += p.samples | 0;
      sum += p.resultSum || 0;
      sumSquares += p.resultSumSquares || 0;
      wins += p.winCount || 0;
      ties += p.tieCount || 0;
      losses += p.lossCount || 0;
      if (p.typeCounts) {
        if (!types) types = new Array(10).fill(0);
        for (let t = 0; t < 10; t++) types[t] += p.typeCounts[t] | 0;
      }
    }
    return {
      runs, sum, sumSquares,
      wins, ties, losses, types,
      equity: runs > 0 ? sum / runs : 0,
      ci: varianceCI(sum, sumSquares, runs),
      typeDist: types ? types.map(c => c / Math.max(1, runs)) : null,
      samples: runs
    };
  };

  const HAND_TYPE_NAMES = [
    'High Card', 'One Pair', 'Two Pair', 'Trips', 'Straight',
    'Flush', 'Full House', 'Quads', 'Straight Flush', 'Royal Flush'
  ];

  const PLAYER_TYPES = {
    MANIAC:          { label: 'MANIAC',  short: 'MAN', color: '#E5606B', vpip: 0.72, pfr: 0.55, afq: 0.62 },
    LAG:             { label: 'LAG',     short: 'LAG', color: '#E8945C', vpip: 0.50, pfr: 0.32, afq: 0.50 },
    TAG:             { label: 'TAG',     short: 'TAG', color: '#45C98A', vpip: 0.24, pfr: 0.20, afq: 0.44 },
    FISH:            { label: 'FISH',    short: 'FSH', color: '#E09A5A', vpip: 0.65, pfr: 0.06, afq: 0.10 },
    CALLING_STATION: { label: 'CALLER', short: 'CLR', color: '#6FA8E8', vpip: 0.55, pfr: 0.07, afq: 0.14 },
    ROCK:            { label: 'ROCK',   short: 'RCK', color: '#8A94A6', vpip: 0.07, pfr: 0.04, afq: 0.25 },
    NIT:             { label: 'NIT',    short: 'NIT', color: '#57C8D6', vpip: 0.13, pfr: 0.06, afq: 0.26 },
    TIGHT_PASSIVE:   { label: 'CAUTIOUS',short: 'CTN', color: '#C4CBD7', vpip: 0.20, pfr: 0.05, afq: 0.18 },
    LOOSE_PASSIVE:   { label: 'GAMBLER',short: 'PSV', color: '#B48CE8', vpip: 0.47, pfr: 0.10, afq: 0.19 },
    UNKNOWN:         { label: '???',    short: '?',   color: '#98A2B5', vpip: 0,    pfr: 0,    afq: 0    }
  };

  const MIN_AFQ_POSTFLOP_ACTIONS = 8;

  const afqRate = (p) => (p && (p.postTotal ?? 0) >= MIN_AFQ_POSTFLOP_ACTIONS && p.postTotal > 0)
    ? p.postAgg / p.postTotal
    : null;

        const MIN_AF_ACTIONS = 6;
  const afOf = (aggActions, callActions) => {
    const agg = Math.max(0, Math.floor(aggActions || 0));
    const calls = Math.max(0, Math.floor(callActions || 0));
    const sample = agg + calls;
    if (sample < MIN_AF_ACTIONS) return { af: null, infinite: false, sample };
    if (calls === 0) return { af: null, infinite: agg > 0, sample };
    return { af: Math.round((agg / calls) * 10) / 10, infinite: false, sample };
  };
  const afLabelOf = (r) => (r && r.af !== null) ? String(r.af) : (r && r.infinite ? '∞' : 'n/a');

  const preflopScore = (c1, c2) => {
    const r1 = RANK_VALS[c1[0]], r2 = RANK_VALS[c2[0]];
    const hi = Math.max(r1, r2), lo = Math.min(r1, r2);
    const suited = c1[1] === c2[1];
    const gap = hi - lo - 1;

    if (hi === lo) return 300 + hi * 20;

    let score = hi * 20 + lo * 4;
    if (suited) score += 25;
    if (gap === 0) score += 15;
    else score -= gap * 8;
    if (hi === 14) score += 15;
    if (hi >= 11 && lo >= 10) score += 20;
    return score;
  };

  const PREFLOP_SORTED_SCORES = (() => {
    const allCards = [];
    for (const r of RANKS) for (const s of SUITS) allCards.push(r + s);
    const scores = [];
    for (let i = 0; i < allCards.length; i++)
      for (let j = i + 1; j < allCards.length; j++)
        scores.push(preflopScore(allCards[i], allCards[j]));
    scores.sort((a, b) => a - b);
    return scores;
  })();

  const PREFLOP_THRESHOLDS = (() => {
    const thresholds = {};
    for (let i = 1; i <= 99; i++) {
      const pct = i / 100;
      const idx = Math.floor(PREFLOP_SORTED_SCORES.length * (1 - pct));
      thresholds[pct.toFixed(2)] = PREFLOP_SORTED_SCORES[Math.min(idx, PREFLOP_SORTED_SCORES.length - 1)];
    }
    return thresholds;
  })();

  const getRangeThreshold = (rangePct) => {
    if (!rangePct || rangePct >= 0.95) return null;
    const key = rangePct.toFixed(2);
    return PREFLOP_THRESHOLDS[key] ?? null;
  };

  const preflopTopFraction = (c1, c2) => {
    const s = preflopScore(c1, c2);
    const scores = PREFLOP_SORTED_SCORES;
    let lo = 0, hi = scores.length;
    while (lo < hi) { const mid = (lo + hi) >> 1; if (scores[mid] < s) lo = mid + 1; else hi = mid; }
    return 1 - lo / scores.length;
  };

  const OPEN_THRESHOLDS = { UTG: 0.15, MP: 0.20, CO: 0.28, BTN: 0.42, SB: 0.36, BB: 0.45 };

  const STRATEGY_PROFILES = Object.freeze({
    tight:      { label: 'Tight',      open: 0.75, defend: 0.80, threeBet: 0.70, value: 1.12, bluff: 0.55, note: 'Plays fewer hands: opens and defends about 20-25% tighter, 3-bets less, and needs more equity to raise for value.' },
    balanced:   { label: 'Balanced',   open: 1.00, defend: 1.00, threeBet: 1.00, value: 1.00, bluff: 1.00, note: 'The standard thresholds: baseline open/defend charts, neutral 3-bet and value-bet cut-offs.' },
    aggressive: { label: 'Aggressive', open: 1.30, defend: 1.15, threeBet: 1.45, value: 0.92, bluff: 1.35, note: 'Plays more hands: wider opens and defends, ~45% more 3-bets, thinner value raises and more bluffing.' }
  });
  const strategyProfile = () => STRATEGY_PROFILES[settings.strategyProfile] ?? STRATEGY_PROFILES.balanced;

  const getPreflopIntent = (hole, pos, raiseLevel, activeOpps, toCall, opts = {}) => {
    const top = preflopTopFraction(hole[0], hole[1]);
    const key = handClassKey(hole[0], hole[1]);
    const headsUp = activeOpps === 1;
    const prof = strategyProfile();
    const ringSize = Number.isFinite(opts.seats) && opts.seats >= 2 ? opts.seats : activeOpps + 1;

    const short = ringSize <= 3 && activeOpps >= 2;
    const semiShort = ringSize === 4 && activeOpps >= 2;

    const chartPos = headsUp ? (pos === 'BTN' || pos === 'SB' ? 'BTN' : 'BB') : pos;
    const openChart = headsUp ? RANGE_CHARTS.huOpen : RANGE_CHARTS.open;
    const defendChart = headsUp ? RANGE_CHARTS.huDefend : RANGE_CHARTS.defend;
    const posOpen = openChart[chartPos] ?? openChart.BTN;

    const shortBlindDefend = short && (pos === 'SB' || pos === 'BB');
    const posDefendTight = defendChart[chartPos] ?? defendChart.BB;
    const posDefend = shortBlindDefend ? RANGE_CHARTS.huDefend.BB : posDefendTight;
    const threeBet = RANGE_CHARTS.threeBet[pos] ?? RANGE_CHARTS.threeBet.MP;

    const opp = opts.opp || null;
    const notes = Array.isArray(opts.oppNotes) ? opts.oppNotes : null;
    const note = (t) => { if (notes) notes.push(t); };
    const oppType = opp && opp.tier !== 'unknown' && PLAYER_TYPES[opp.type] ? opp.type : null;
    const oppFold3 = opp && (opp.foldTo3BetOpp ?? 0) >= 5 ? opp.foldTo3Bet : null;
    const opp3bet = opp && (opp.threeBetOpp ?? 0) >= 8 ? opp.threeBet : null;
    const oppFoldOpen = opp && (opp.foldVsOpenOpp ?? 0) >= 5 ? opp.foldVsOpen : null;
    const oppLoosePassive = oppType === 'FISH' || oppType === 'CALLING_STATION' || oppType === 'LOOSE_PASSIVE';
    const oppWild = oppType === 'MANIAC' || oppType === 'LAG';

    if (opts.noPreFlop) {
      if (!(toCall > 0) && !opts.toCallUnknown) return 'check';
      if (posDefend.has(key)) return 'call';
      let npfCut = headsUp ? 0.60 : (activeOpps >= 3 ? 0.40 : 0.34);
      if (short) npfCut += 0.12;
      return top <= npfCut * prof.defend ? 'call' : 'fold';
    }

    if (opts.toCallUnknown && !(toCall > 0)) {
                        const unknownCut = headsUp ? 0.62 : (short ? 0.44 : (activeOpps >= 3 ? 0.38 : 0.34));
      if (posDefend.has(key) || top <= unknownCut * prof.defend) return 'call';
      return 'fold';
    }

    if (!(toCall > 0)) {
      const stealSpot = !headsUp && (pos === 'BTN' || pos === 'CO' || pos === 'SB');
      let stealCut = 0;
      if (stealSpot && oppFoldOpen !== null && oppFoldOpen >= 55) {
        const joint = typeof opp.stealFoldJoint === 'number' ? opp.stealFoldJoint : (oppFoldOpen / 100);
        if (joint >= 0.60) stealCut = 0.14;
        else if (joint >= 0.45) stealCut = 0.08;
        if (stealCut > 0) {
          note(`${opp.name} folds ${oppFoldOpen}% vs opens (${opp.foldVsOpen}/${opp.foldVsOpenOpp}); joint fold ~${Math.round(joint * 100)}%: steal wider`);
        }
      }
      if (posOpen.has(key) || (stealCut > 0 && top <= (OPEN_THRESHOLDS[pos] ?? 0.22) * prof.open + stealCut)) return 'raise';

      if (!headsUp && pos === 'BB' && threeBet.has(key)) return 'raise';

      if (!headsUp && (short || semiShort)
        && (pos === 'BTN' || pos === 'SB' || pos === 'CO')) {
        const shortOpenCut = (short ? (pos === 'BTN' ? 0.60 : 0.52) : 0.48) * prof.open;
        if (top <= shortOpenCut) return 'raise';
      }
      return 'check';
    }

    if (raiseLevel >= 3) {
      let fiveBetCut = 0.02;
      let callCut = short ? 0.10 : 0.05;
      if (oppWild) {
        fiveBetCut = 0.06;
        callCut = short ? 0.18 : 0.12;
        note(`${opp.name} is a ${opp.type}: their 4-bet+ is light: 5-bet for value, call wider`);
      } else if (oppType === 'NIT' || oppType === 'ROCK' || oppType === 'TIGHT_PASSIVE') {
        fiveBetCut = 0.012;
        callCut = 0.03;
        note(`${opp.name} is a ${oppType}: their 4-bet+ means strength: only continue with the top`);
      }
      if (threeBet.has(key) || top <= fiveBetCut * prof.threeBet) return 'raise';
      return top <= callCut * prof.defend ? 'call' : 'fold';
    }

    if (raiseLevel === 2) {
      let fourBetCut = 0, callCutWide = null;
      if (opp3bet !== null && opp3bet <= 6) {
        fourBetCut = 0.015;
        note(`${opp.name} 3-bets only ${opp3bet}% (${opp.threeBet}/${opp.threeBetOpp}): their 3-bet means strength`);
      } else if (oppWild || (opp3bet !== null && opp3bet >= 12)) {
        fourBetCut = 0.06;
        callCutWide = 0.18;
        note(`${opp.name} 3-bets light (${oppWild ? opp.type : opp3bet + '%'}): call wider, 4-bet for value`);
      }
      if (threeBet.has(key) || (fourBetCut > 0 && top <= fourBetCut * prof.threeBet)) return 'raise';
      if ((shortBlindDefend ? posDefendTight : posDefend).has(key)) return 'call';
      let callCut = headsUp ? 0.38 : (short ? 0.26 : (activeOpps >= 3 ? 0.17 : 0.14));
      if (semiShort) callCut += 0.02;
      if (callCutWide !== null) callCut = Math.max(callCut, callCutWide);
      return top <= callCut * prof.defend ? 'call' : 'fold';
    }
    if (raiseLevel === 1) {
      let extra3betCut = 0;
      if (oppWild) {
        extra3betCut = 0.16;
        note(`${opp.name} is a ${opp.type}: 3-bet lighter for value and leverage`);
      } else if (oppFold3 !== null && oppFold3 >= 55) {
        extra3betCut = oppFold3 >= 70 ? 0.22 : 0.15;
        note(`${opp.name} folds ${oppFold3}% to 3-bets (${opp.foldTo3Bet}/${opp.foldTo3BetOpp}): re-raise bluff works`);
      } else if (oppLoosePassive && (oppFold3 === null || oppFold3 <= 35)) {
        extra3betCut = 0.10;
        note(`${opp.name} calls 3-bets too often: 3-bet for value, skip the bluffs`);
      }
      if (threeBet.has(key) || (extra3betCut > 0 && top <= extra3betCut * prof.threeBet)) return 'raise';
      if (posDefend.has(key)) return 'call';

      const inPos = pos === 'BTN' || pos === 'CO';
      const isBlind = pos === 'SB' || pos === 'BB';
      let callCut = headsUp ? 0.52 : (activeOpps >= 3 ? 0.30 : 0.26);
      if (inPos) callCut += 0.03;
      if (isBlind) callCut += 0.02;

      if (short) callCut += isBlind ? 0.16 : 0.10;
      else if (semiShort) callCut += isBlind ? 0.06 : 0.04;
      return top <= callCut * prof.defend ? 'call' : 'fold';
    }

    if (posOpen.has(key)) return 'raise';
      const openCut = (OPEN_THRESHOLDS[pos] ?? 0.22) * prof.open;
    const limpHostile = oppWild;
    if (limpHostile) note(`${opp.name} is a ${opp.type}: limping invites a raise: enter with a raise or fold`);
    const limpCap = limpHostile ? Math.min(0.35, short ? 0.65 : (semiShort ? 0.60 : 0.55))
      : short ? 0.65 : (semiShort ? 0.60 : 0.55);
    return top <= Math.min(limpCap * prof.defend, openCut + (short ? 0.28 : semiShort ? 0.22 : 0.18)) ? 'call' : 'fold';
  };

  const CARD_STR = [];
  const RANK_OF = new Uint8Array(52);
  const SUIT_OF = new Uint8Array(52);
  const CARD_IDX = {};
  (() => {
    let i = 0;
    for (const r of RANKS) for (const s of SUITS) {
      const c = r + s;
      CARD_STR[i] = c;
      RANK_OF[i] = RANK_VALS[r];
      SUIT_OF[i] = SUITS.indexOf(s);
      CARD_IDX[c] = i;
      i++;
    }
  })();

  const PRE_SCORE = (() => {
    const t = new Int16Array(52 * 52);
    for (let a = 0; a < 52; a++) for (let b = 0; b < 52; b++) {
      if (a === b) continue;
      t[a * 52 + b] = preflopScore(CARD_STR[a], CARD_STR[b]);
    }
    return t;
  })();

  let _rngState = (Date.now() ^ 0x9e3779b9) >>> 0 || 1;
  const rng = () => {
    let x = _rngState;
    x ^= x << 13; x >>>= 0;
    x ^= x >>> 17;
    x ^= x << 5;  x >>>= 0;
    _rngState = x;
    return x / 4294967296;
  };

  const straightHighFromMask = (mask) => {
    for (let hi = 14; hi >= 6; hi--) {
      const need = 0b11111 << (hi - 4);
      if ((mask & need) === need) return hi;
    }

    const wheel = (1 << 14) | (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2);
    if ((mask & wheel) === wheel) return 5;
    return 0;
  };

  const _rc = new Uint8Array(15);
  const _sc = new Uint8Array(4);
  const _sm = new Uint16Array(4);

  const evalFastIdx = (cards, n) => {
    _rc.fill(0); _sc.fill(0); _sm.fill(0);
    let rankMask = 0;
    for (let i = 0; i < n; i++) {
      const c = cards[i];
      const r = RANK_OF[c], s = SUIT_OF[c];
      _rc[r]++; _sc[s]++;
      _sm[s] |= (1 << r);
      rankMask |= (1 << r);
    }

    let flushSuit = -1;
    for (let s = 0; s < 4; s++) if (_sc[s] >= 5) { flushSuit = s; break; }

    if (flushSuit >= 0) {
      const sfHigh = straightHighFromMask(_sm[flushSuit]);
      if (sfHigh > 0) {
        const type = sfHigh === 14 ? 9 : 8;
        return (type << 20) | (sfHigh << 16);
      }
    }

    let quads = 0, trip1 = 0, trip2 = 0, pair1 = 0, pair2 = 0;
    for (let r = 14; r >= 2; r--) {
      const c = _rc[r];
      if (c === 4) { if (!quads) quads = r; }
      else if (c === 3) { if (!trip1) trip1 = r; else if (!trip2) trip2 = r; }
      else if (c === 2) { if (!pair1) pair1 = r; else if (!pair2) pair2 = r; }
    }

    if (quads) {
      let k = 0;
      for (let r = 14; r >= 2; r--) if (r !== quads && _rc[r] > 0) { k = r; break; }
      return (7 << 20) | (quads << 16) | (k << 12);
    }
    if (trip1 && (trip2 || pair1)) {
      const pr = trip2 > pair1 ? trip2 : pair1;
      return (6 << 20) | (trip1 << 16) | (pr << 12);
    }
    if (flushSuit >= 0) {
      let score = (5 << 20), got = 0;
      const m = _sm[flushSuit];
      for (let r = 14; r >= 2 && got < 5; r--) {
        if (m & (1 << r)) { score |= r << (16 - 4 * got); got++; }
      }
      return score;
    }
    const stHigh = straightHighFromMask(rankMask);
    if (stHigh > 0) return (4 << 20) | (stHigh << 16);
    if (trip1) {
      let score = (3 << 20) | (trip1 << 16), got = 0;
      for (let r = 14; r >= 2 && got < 2; r--) {
        if (r !== trip1 && _rc[r] > 0) { score |= r << (12 - 4 * got); got++; }
      }
      return score;
    }
    if (pair1 && pair2) {
      let k = 0;
      for (let r = 14; r >= 2; r--) if (r !== pair1 && r !== pair2 && _rc[r] > 0) { k = r; break; }
      return (2 << 20) | (pair1 << 16) | (pair2 << 12) | (k << 8);
    }
    if (pair1) {
      let score = (1 << 20) | (pair1 << 16), got = 0;
      for (let r = 14; r >= 2 && got < 3; r--) {
        if (r !== pair1) {
          for (let c = 0; c < _rc[r] && got < 3; c++) { score |= r << (12 - 4 * got); got++; }
        }
      }
      return score;
    }
    let score = 0, got = 0;
    for (let r = 14; r >= 2 && got < 5; r--) {
      for (let c = 0; c < _rc[r] && got < 5; c++) { score |= r << (16 - 4 * got); got++; }
    }
    return score;
  };

  const RANGE_MIN = 0.02, RANGE_MAX = 1.0;
  const clampRange = (f) => Math.max(RANGE_MIN, Math.min(RANGE_MAX, f));

  const RAISE_POS_MULT = { UTG: 0.80, MP: 0.88, CO: 1.30, BTN: 1.30, SB: 1.05, BB: 0.90 };

  const narrowRangeFraction = (events, priors = {}, seatPos = null, riskyBoard = false) => {
    const vpip = priors.vpip ?? 0.35;
    const pfr = priors.pfr ?? 0.12;
    const afq = priors.afq ?? 0.35;
    const handRaiseLevel = priors.handRaiseLevel ?? 0;
    let frac = 1.0;
    let acted = false;
    for (const ev of events || []) {
      const { street, action } = ev;
      if (street === 'preflop') {
        if (action === 'raise') {
          const base = Math.max(pfr, 0.03) * (RAISE_POS_MULT[seatPos] ?? 1);
          frac = acted || frac < 1.0 ? clampRange(Math.min(frac, Math.max(base, 0.03)) * 0.45)
                       : clampRange(Math.max(base, 0.04));
          acted = true;
        } else if (action === 'call') {
          const cap = Math.max(vpip, 0.08);

          frac = clampRange(Math.min(frac, handRaiseLevel >= 2 ? cap * 0.65 : cap));
          acted = true;
        } else if (action === 'check') {
          acted = true;
        }
      } else {
        if (action === 'raise' || action === 'bet') {
          const mult = Math.max(0.35, Math.min(0.75, 0.35 + 0.7 * afq));
          frac = clampRange(frac * (riskyBoard ? mult * 0.75 : mult));
        } else if (action === 'call') {
          frac = clampRange(frac * (riskyBoard ? 0.62 : 0.80));
        }
      }
    }
    return clampRange(frac);
  };

  const bankrollAdvice = (bankrollTotal, currentBuyIn, sessionNet, opts = {}) => {
    const stopLossBuyIns = opts.stopLossBuyIns ?? 2;
    const out = {
      maxBuyInConservative: Math.floor(bankrollTotal / 40) || 0,
      maxBuyInStandard: Math.floor(bankrollTotal / 25) || 0,
      maxBuyInAggressive: Math.floor(bankrollTotal / 15) || 0,
      stopLossAmount: 0, stopLossHit: false,
      stakeWarning: null
    };
    if (currentBuyIn > 0) {
      out.stopLossAmount = Math.round(currentBuyIn * stopLossBuyIns);
      out.stopLossHit = sessionNet <= -out.stopLossAmount;
      if (bankrollTotal > 0 && currentBuyIn > out.maxBuyInStandard) {
        out.stakeWarning = currentBuyIn > out.maxBuyInAggressive
          ? 'Stakes far above your bankroll. The risk of ruin is high: move down.'
          : 'Stakes sit above the 25-buy-in guideline. Consider a smaller table.';
      }
    }
    return out;
  };

            const sessionVariance = (deltas) => {
    const d = (deltas || []).map(x => Number(x) || 0).filter(x => x !== 0);
    const n = d.length;
    if (n < 2) return null;
    const mean = d.reduce((a, b) => a + b, 0) / n;
    const variance = d.reduce((a, b) => a + (b - mean) * (b - mean), 0) / (n - 1);
    return { n, mean, sigma: Math.sqrt(variance) };
  };
  const bankrollRiskRead = (deltas, bankrollTotal) => {
    const v = sessionVariance(deltas);
    if (!v || v.n < 30) return null;
    if (!(bankrollTotal > 0)) return null;
    if (v.sigma <= 0) return { ...v, ror: v.mean > 0 ? 0 : 1, note: 'degenerate variance' };
    if (v.mean <= 0) return { ...v, ror: 1, note: 'non-positive win rate: ruin is certain if nothing changes' };
    const ror = Math.exp((-2 * v.mean * bankrollTotal) / (v.sigma * v.sigma));
    return { ...v, ror: Math.min(1, ror) };
  };

  const tiltCheck = (recentDeltas, buyIn) => {
    if (!recentDeltas || recentDeltas.length < 3) return null;
    const last = recentDeltas.slice(-6);
    let streak = 0;
    for (let i = last.length - 1; i >= 0; i--) {
      if (last[i] < 0) streak++; else break;
    }
    const recentLoss = last.reduce((a, d) => a + Math.min(0, d), 0);
    if (streak >= 4) return `You've lost ${streak} hands in a row. Variance is normal, but check you're not tilting.`;
    if (buyIn > 0 && recentLoss <= -buyIn * 1.5) return 'Fast losses detected (>1.5 buy-ins over recent hands). Consider a short break.';
    return null;
  };

  const estimateHandScore = ({ won, handType = 0, opponents = 1, showdown = false, bb = 100, felted = false }) => {
    if (!won) return 0;
    const typeWeight = Math.pow(handType + 1, 1.6);
    const oppWeight = 1 + 0.30 * Math.max(0, opponents - 1);
    const streetWeight = showdown ? 2.0 : 0.6;
    const stakeWeight = Math.max(1, Math.log10(Math.max(10, bb)));
    const feltBonus = felted ? 1.5 : 1;
    return Math.round(25 * typeWeight * oppWeight * streetWeight * stakeWeight * feltBonus);
  };

  const sampleConfidence = (n) => Math.min(0.99, n / (n + 25));

  const decayFactor = (msSinceSeen, halfLifeDays = 14) => {
    if (!msSinceSeen || msSinceSeen <= 0) return 1;
    const days = msSinceSeen / 86400000;
    return Math.pow(0.5, days / halfLifeDays);
  };

  const PRIOR_RATE = 0.30;
  const PRIOR_WEIGHT = 20;
  const smoothedRate = (successes, trials, priorRate = PRIOR_RATE, priorWeight = PRIOR_WEIGHT) => (
    (successes + priorRate * priorWeight) / (trials + priorWeight)
  );

  const profileTier = (hands) => {
    if (!hands || hands < 10) return 'unknown';
    if (hands < 30) return 'tentative';
    if (hands < 75) return 'developing';
    return 'established';
  };
  const TIER_LABELS = {
    unknown: 'Insufficient sample',
    tentative: 'Low confidence',
    developing: 'Developing profile',
    established: 'Established local profile'
  };

  const NOIR_CSS = `
    :root {

      --tnp-bg: #0A090A;
      --tnp-surface: #141014;
      --tnp-raised: #1C1418;
      --tnp-bg-hover: #271B20;
      --tnp-border: #2B2126;
      --tnp-border-hi: #4A2E36;

      --tnp-text: #E9E2E5;
      --tnp-text-hi: #FAF6F8;
      --tnp-muted: #B5A6AD;
      --tnp-text-faint: #B8ABB2;
      --tnp-ink: #FFFFFF;
      --tnp-ink-on-bright: #201614;
      --tnp-accent-text: #EE6B77;

      --tnp-accent-1: #D83B49;
      --tnp-accent-2: #F2A9B2;
      --tnp-danger: #FF5A5A;
      --tnp-success: #3ECF7A;
      --tnp-amber: #F0B45B;
      --tnp-neutral: #9BA6B4;

      --tnp-act-fold: #FF5A5A;
      --tnp-act-check: var(--tnp-neutral);
      --tnp-act-call: #57A8FF;
      --tnp-act-raise: #3ECF7A;

      --tnp-glass-fill: rgba(255, 255, 255, .04);
      --tnp-glass-edge: rgba(255,255,255,.14);
      --tnp-blur: 10px;

      --tnp-font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      --tnp-font-mono: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, "Liberation Mono", Menlo, monospace;
      --tnp-fw-label: 500;
      --tnp-fw-emph: 600;
      --tnp-fw-display: 700;
      --tnp-fz-display: 18px;
      --tnp-fz-stat-touch: 14px;

      --tnp-fz-2xs: 12px;
      --tnp-fz-xs: 12px;
      --tnp-fz-sm: 12.5px;
      --tnp-fz-md: 12.5px;
      --tnp-fz-stat: 13.5px;
      --tnp-lh-tight: 1.2;
      --tnp-lh-body: 1.45;
      --tnp-lh-loose: 1.5;
    }

    #tnp-dossier,
    #tnp-dossier * { box-sizing: border-box; }

    #tnp-dossier {
      position: fixed;
      bottom: 20px;
      right: 20px;
      width: 348px;
      background: var(--tnp-surface);
      border: 1px solid var(--tnp-border);
      border-radius: 12px;
      color: var(--tnp-text);
      font-family: var(--tnp-font);
      font-size: var(--tnp-fz-md);
      line-height: 1.45;
      font-variant-numeric: tabular-nums;
      font-feature-settings: 'tnum';
      z-index: 999999;
      box-shadow: 0 10px 28px rgba(0,0,0,.4), 0 2px 6px rgba(0,0,0,.28);
      display: flex;
      flex-direction: column;
      user-select: none;
      cursor: default;
      contain: layout style paint;
      max-height: 90vh;
      overflow-y: auto;
      scrollbar-width: thin;
      scrollbar-color: var(--tnp-border) transparent;
    }
    #tnp-dossier::-webkit-scrollbar { width: 8px; }
    #tnp-dossier::-webkit-scrollbar-thumb { background: var(--tnp-border); border-radius: 4px; border: 2px solid var(--tnp-surface); }
    #tnp-dossier::-webkit-scrollbar-track { background: transparent; }

    #tnp-dossier.tnp-minimized {
      display: inline-flex !important;
      width: max-content !important;
      height: auto !important;
      min-width: 0 !important;
      min-height: 0 !important;
      max-height: none !important;
      flex: 0 0 auto !important;
      align-self: flex-start !important;
      overflow: hidden !important;
    }
    #tnp-dossier.tnp-minimized #tnp-body {
      display: none !important;
      height: 0 !important;
      min-height: 0 !important;
      max-height: 0 !important;
      margin: 0 !important;
      padding: 0 !important;
      border: 0 !important;
      overflow: hidden !important;
    }

    #tnp-header {
      padding: 9px 12px;
      background: var(--tnp-surface);
      border-bottom: 1px solid var(--tnp-border);
      border-radius: 12px 12px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 10px;
      cursor: grab;
      touch-action: none;
      -webkit-user-select: none;
      user-select: none;
      position: relative;
      z-index: 1;
      flex-shrink: 0;
    }
    #tnp-header:active { cursor: grabbing; }

    .tnp-title-wrap { display: flex; flex-direction: column; gap: 2px; min-width: 0; }

    .tnp-title {
      font-weight: var(--tnp-fw-emph);
      text-transform: uppercase;
      letter-spacing: 0.1em;
      color: var(--tnp-text-hi);
      font-size: var(--tnp-fz-sm);
      display: flex;
      align-items: baseline;
      gap: 7px;
      white-space: nowrap;
    }

    .tnp-version {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-text-faint);
      font-weight: 400;
      letter-spacing: 0.04em;
    }

    .tnp-header-actions { display: flex; gap: 6px; align-items: center; }

    .tnp-badge {
      background: var(--tnp-raised);
      padding: 3px 8px;
      font-size: var(--tnp-fz-2xs);
      border-radius: 5px;
      color: var(--tnp-muted);
      font-weight: var(--tnp-fw-emph);
      letter-spacing: 0.04em;
    }
    .tnp-badge-success { background: var(--tnp-success); color: var(--tnp-ink-on-bright); }
    .tnp-badge-warning { background: var(--tnp-amber); color: var(--tnp-ink-on-bright); }
    .tnp-badge-danger { background: var(--tnp-danger); color: var(--tnp-ink-on-bright); }

    #tnp-status-chip {
      background: transparent;
      color: var(--tnp-muted);
      font-size: var(--tnp-fz-2xs);
      letter-spacing: 0.08em;
      text-transform: uppercase;
      font-weight: var(--tnp-fw-label);
      white-space: nowrap;
      display: inline-flex;
      align-items: center;
    }
    #tnp-status-chip::before {

      content: '';
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: currentColor;
      margin-right: 5px;
      flex-shrink: 0;
    }

    #tnp-health-badge {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: var(--tnp-amber);
      cursor: help;
      flex-shrink: 0;
    }

    #tnp-toggle {
      cursor: pointer;
      color: var(--tnp-muted);
      width: 34px;
      height: 34px;
      padding: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: transparent;
      border: none;
      border-radius: 7px;
      font-family: var(--tnp-font);
      transition: color 150ms ease, background 150ms ease;
      touch-action: manipulation;
      -webkit-tap-highlight-color: transparent;
      -webkit-user-select: none;
      user-select: none;
    }
    #tnp-toggle::after {
      content: '';
      width: 7px;
      height: 7px;
      border-right: 1.5px solid currentColor;
      border-bottom: 1.5px solid currentColor;
      transform: rotate(45deg);
      margin-top: 3px;
      transition: transform 150ms ease, margin-top 150ms ease;
    }
    #tnp-dossier.tnp-minimized #tnp-toggle::after {
      transform: rotate(-135deg);
      margin-top: -2px;
    }
    #tnp-toggle:hover { color: var(--tnp-text-hi); background: var(--tnp-bg-hover); }
    #tnp-toggle:active { color: var(--tnp-accent-text); }

    #tnp-body {
      padding: 10px 12px 12px;
      display: flex;
      flex-direction: column;
      position: relative;
      z-index: 1;
    }

    #tnp-folded-overlay {
      text-align: center;
      padding: 18px 10px;
      color: var(--tnp-muted);
      font-size: var(--tnp-fz-md);
      letter-spacing: 0.2em;
      font-weight: 600;
      text-transform: uppercase;
    }

    .tnp-row {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 10px;
      padding: 2px 0;
    }

    .tnp-label {
      color: var(--tnp-muted);
      font-size: var(--tnp-fz-xs);
      text-transform: uppercase;
      letter-spacing: 0.07em;
      flex-shrink: 0;
      font-weight: var(--tnp-fw-label);
    }

    .tnp-value {
      min-width: 0;
      max-width: 70%;
      overflow-wrap: anywhere;
      font-family: var(--tnp-font-mono);
      font-size: var(--tnp-fz-md);
      font-weight: var(--tnp-fw-label);
      color: var(--tnp-text-hi);
      text-align: right;
    }

    .tnp-accent { color: var(--tnp-accent-2); }
    .tnp-danger { color: var(--tnp-danger); }
    .tnp-success { color: var(--tnp-success); }

    .tnp-cards-display {
      display: flex;
      gap: 5px;
      align-items: center;
      font-size: var(--tnp-fz-stat);
      font-weight: var(--tnp-fw-emph);
    }

    .tnp-card-mini {
      width: 24px;
      height: 33px;
      background: var(--tnp-raised);
      border-radius: 5px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: var(--tnp-fw-emph);
      font-size: var(--tnp-fz-stat);
      box-shadow: 0 1px 2px rgba(0,0,0,.4);
    }

    .tnp-card-red { color: var(--tnp-danger); }
    .tnp-card-black { color: var(--tnp-text-hi); }

    .tnp-empty-card {
      background: var(--tnp-bg);
      border: none;
      color: transparent;
      box-shadow: none;
    }

    .tnp-dom-card {
      flex: 0 0 auto;
      overflow: hidden;
      border-radius: 4px;
      box-shadow: 0 1px 2px rgba(0,0,0,.4);
      line-height: 0;
    }
    .tnp-dom-card > * {
      margin: 0 !important;
      transform-origin: top left !important;
    }

    .tnp-equity-bar {
      width: 100%;
      height: 6px;
      background: var(--tnp-raised);
      border-radius: 999px;
      overflow: hidden;
      margin-top: 2px;
      position: relative;
    }

    .tnp-equity-fill {
      height: 100%;
      background: linear-gradient(90deg, #7A1220, var(--tnp-accent-1));
      width: 0%;
      border-radius: 999px;
      transition: width 180ms cubic-bezier(.2,.8,.2,1);
    }

    .tnp-equity-ci {
      position: absolute;
      top: 0;
      height: 100%;
      background: rgba(242, 169, 178, 0.16);
      border-left: 1px solid rgba(242, 169, 178, 0.45);
      border-right: 1px solid rgba(242, 169, 178, 0.45);
      transition: left 180ms cubic-bezier(.2,.8,.2,1), width 180ms cubic-bezier(.2,.8,.2,1);
    }

    .tnp-equity-tick {
      position: absolute;
      top: -3px;
      bottom: -3px;
      width: 2px;
      margin-left: -1px;
      background: var(--tnp-text-hi);
      opacity: 0.8;
      display: none;
      pointer-events: none;
      transition: left 180ms cubic-bezier(.2,.8,.2,1);
    }

    .tnp-hidden { display: none !important; }

    .tnp-tabs {
      display: flex;
      flex-wrap: wrap;
      gap: 2px;
      border-bottom: 1px solid var(--tnp-border);
    }

    .tnp-tab {
      flex: 1;
      padding: 5px 5px 6px;
      text-align: center;
      font-size: var(--tnp-fz-xs);
      text-transform: uppercase;
      letter-spacing: 0.07em;
      font-weight: 600;
      cursor: pointer;
      color: var(--tnp-muted);
      background: transparent;
      border: none;
      border-bottom: 2px solid transparent;
      margin-bottom: -1px;
      transition: color 150ms ease, border-color 150ms ease;
    }
    .tnp-tab:hover { color: var(--tnp-text); }
    .tnp-tab.active,
    .tnp-tab[aria-selected="true"] { color: var(--tnp-text-hi); border-bottom-color: var(--tnp-accent-1); }

    .tnp-panel { display: none; }
    .tnp-panel.active { display: flex; flex-direction: column; gap: 8px; }

    .tnp-divider {
      border: none;
      height: 1px;
      background: var(--tnp-border);
      margin: 5px 0;
    }

    .tnp-stat-grid {
      display: grid;

      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 6px;
    }

    .tnp-stat-box {
      background: var(--tnp-raised);
      border-radius: 8px;
      padding: 6px 9px 7px;
      text-align: left;
    }
    .tnp-stat-box .tnp-stat-label {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
      text-transform: uppercase;
      letter-spacing: 0.07em;
      font-weight: var(--tnp-fw-label);
      line-height: var(--tnp-lh-tight);
      white-space: nowrap;
    }
    .tnp-stat-box .tnp-stat-val {
      font-family: var(--tnp-font-mono);
      font-size: var(--tnp-fz-stat);
      font-weight: var(--tnp-fw-emph);
      color: var(--tnp-text-hi);
      margin-top: 1px;
      line-height: var(--tnp-lh-tight);
    }

    .tnp-ledger-row {
      display: grid;

      grid-template-columns: minmax(0, 1fr) 118px 76px;
      align-items: baseline;
      gap: 8px;
      padding: 4px 2px;
      border-bottom: 1px solid var(--tnp-border);
      font-size: var(--tnp-fz-xs);
    }
    .tnp-ledger-row:last-child { border-bottom: none; }
    .tnp-ledger-name {
      color: var(--tnp-text);
      font-weight: 600;
      white-space: nowrap;
    }
    .tnp-ledger-count {
      color: var(--tnp-text-faint);
      font-size: var(--tnp-fz-2xs);
      white-space: nowrap;
      text-align: right;
    }
    .tnp-ledger-net {
      font-family: var(--tnp-font-mono);
      font-weight: var(--tnp-fw-emph);
      font-size: var(--tnp-fz-xs);
      white-space: nowrap;
      text-align: right;
    }
    .tnp-session-unknown { color: var(--tnp-muted) !important; opacity: 0.75; }

    .tnp-history-row {
      display: grid;
      grid-template-columns: minmax(0, 1fr) auto auto auto;
      gap: 10px;
      align-items: baseline;
      padding: 3px 0;
      font-family: var(--tnp-font-mono);
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
    }
    .tnp-history-row .tnp-history-net { color: var(--tnp-text-hi); text-align: right; white-space: nowrap; }
    .tnp-history-row .tnp-history-tail { color: var(--tnp-text-faint); text-align: right; white-space: nowrap; }

    #tnp-stat-guide {
      background: var(--tnp-bg);
      border-radius: 8px;
      padding: 8px 10px;
      display: flex;
      flex-direction: column;
      gap: 6px;
    }
    .tnp-guide-row {
      display: grid;
      grid-template-columns: 60px minmax(0, 1fr);
      gap: 10px;
      align-items: baseline;
      font-size: var(--tnp-fz-xs);
      color: var(--tnp-muted);
      line-height: var(--tnp-lh-loose);
    }
    .tnp-guide-row b {
      color: var(--tnp-text-hi);
      font-size: var(--tnp-fz-2xs);
      font-weight: var(--tnp-fw-emph);
      white-space: nowrap;
    }

    .tnp-heat-line {
      font-size: var(--tnp-fz-xs);
      text-transform: uppercase;
      letter-spacing: 0.07em;
      color: var(--tnp-muted);
      font-weight: var(--tnp-fw-label);
    }
    .tnp-heat-line b { color: var(--tnp-text-hi); font-weight: var(--tnp-fw-emph); }

    .tnp-player-row {
      display: flex;
      align-items: center;
      gap: 7px;
      padding: 6px 9px;
      background: var(--tnp-raised);
      border-radius: 8px;
      transition: background 120ms ease;
    }
    .tnp-player-row:hover { background: var(--tnp-bg-hover); }

    .tnp-player-badge {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      width: 22px;
      height: 22px;
      border-radius: 50%;
      font-size: var(--tnp-fz-2xs);
      font-weight: var(--tnp-fw-emph);
      border: 2px solid transparent;
      background: transparent;
      letter-spacing: 0.02em;
    }

    .tnp-player-name {
      flex: 1;
      font-size: var(--tnp-fz-sm);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }
    .tnp-player-name:hover { text-decoration: underline; color: var(--tnp-text-hi); }

    .tnp-player-stats {
      font-family: var(--tnp-font-mono);
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-text-faint);
    }

    .tnp-exploit-hint {

      font-size: var(--tnp-fz-xs);
      color: var(--tnp-text);
      padding: 6px 9px;
      background: rgba(217, 59, 73, 0.08);
      border: 1px solid var(--tnp-border);
      border-radius: 6px;
      line-height: var(--tnp-lh-loose);
    }

    .tnp-setting-row {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;
      padding: 3px 0;
      gap: 10px;
    }

    .tnp-quality-btns {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
    }
    .tnp-quality-btn {
      padding: 5px 11px;
      font-size: var(--tnp-fz-xs);
      background: var(--tnp-raised);
      border: none;
      border-radius: 7px;
      cursor: pointer;
      color: var(--tnp-muted);
      font-family: var(--tnp-font);
      font-weight: var(--tnp-fw-label);
      transition: color 120ms ease, background 120ms ease;
    }
    .tnp-quality-btn:hover { color: var(--tnp-text-hi); background: var(--tnp-bg-hover); }
    .tnp-quality-btn.active { background: var(--tnp-accent-1); color: var(--tnp-ink); font-weight: var(--tnp-fw-emph); }

    .tnp-checkbox {
      width: 14px;
      height: 14px;
      cursor: pointer;
      accent-color: var(--tnp-accent-1);
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
    }
    .tnp-checkbox:focus { outline: none; border-color: var(--tnp-border-hi); }

    .tnp-text-btn {
      padding: 5px 11px;
      font-size: var(--tnp-fz-xs);
      background: var(--tnp-raised);
      border: none;
      border-radius: 7px;
      cursor: pointer;
      color: var(--tnp-muted);
      font-family: var(--tnp-font);
      font-weight: var(--tnp-fw-label);
      transition: color 120ms ease, background 120ms ease;
    }
    .tnp-text-btn:hover { color: var(--tnp-text-hi); background: var(--tnp-bg-hover); }

    @keyframes tnp-flash {
      0% { box-shadow: 0 10px 28px rgba(0,0,0,.4), 0 2px 6px rgba(0,0,0,.28), 0 0 0 0 rgba(217,59,73,.55); }
      50% { box-shadow: 0 10px 28px rgba(0,0,0,.4), 0 2px 6px rgba(0,0,0,.28), 0 0 0 6px rgba(217,59,73,0); }
      100% { box-shadow: 0 10px 28px rgba(0,0,0,.4), 0 2px 6px rgba(0,0,0,.28), 0 0 0 0 rgba(217,59,73,0); }
    }
    .tnp-flash { animation: tnp-flash 0.8s ease-out 2; }

    @keyframes tnp-pulse {
      0% { box-shadow: 0 0 0 0 var(--tnp-accent-1); }
      100% { box-shadow: 0 0 0 4px transparent; }
    }
    .tnp-pulse { animation: tnp-pulse 400ms ease-out; }

    .tnp-card-highlight {

      box-shadow: 0 0 0 2px var(--tnp-accent-2) !important;
      border-radius: 4px !important;
    }

    .tnp-seat-badge {
      position: absolute;
      top: -8px;
      right: -8px;
      z-index: 999;
      pointer-events: auto;
      cursor: pointer;
    }

    .tnp-notes-input {
      width: 100%;
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
      border-radius: 8px;
      color: var(--tnp-text);
      font-size: var(--tnp-fz-sm);
      font-family: var(--tnp-font);
      padding: 6px 8px;
      resize: vertical;
      min-height: 46px;
      line-height: var(--tnp-lh-loose);
      transition: border-color 120ms ease;
    }
    .tnp-notes-input:focus { outline: none; border-color: var(--tnp-accent-1); }

    #tnp-action-banner {
      display: none;
      flex-direction: column;
      gap: 4px;
      padding: 10px 12px;
      border-radius: 10px;
      border: 1px solid var(--tnp-glass-edge);
      background: var(--tnp-raised);
      color: var(--tnp-text-hi);
      text-align: center;
    }
    #tnp-action-banner.tnp-banner-active { display: flex; }
    .tnp-banner-action {
      font-size: var(--tnp-fz-display);
      font-weight: var(--tnp-fw-display);
      letter-spacing: 0.12em;
      text-transform: uppercase;
      line-height: 1.15;
      color: var(--tnp-text-hi);
    }
    .tnp-banner-sub {
      font-size: var(--tnp-fz-xs);
      color: var(--tnp-muted);
      font-weight: 400;
      line-height: var(--tnp-lh-body);
      white-space: pre-line;
    }
    .tnp-banner-sub .tnp-legal-floor {
      color: var(--tnp-success);
      font-weight: var(--tnp-fw-emph);
    }
    .tnp-banner-sub .tnp-legal-unverified {
      color: var(--tnp-amber);
      font-weight: var(--tnp-fw-emph);
    }

    .tnp-banner-raise .tnp-banner-action { color: var(--tnp-act-raise); }
    .tnp-banner-call .tnp-banner-action { color: var(--tnp-act-call); }
    .tnp-banner-check .tnp-banner-action { color: var(--tnp-act-check); }
    .tnp-banner-fold { background: rgba(255, 90, 90, 0.10); }
    .tnp-banner-fold .tnp-banner-action { color: var(--tnp-act-fold); }

    button.tnp-details-toggle {
      background: transparent;
      border: none;
      font-family: var(--tnp-font);
    }
    .tnp-details-toggle {
      font-size: var(--tnp-fz-xs);
      color: var(--tnp-muted);
      cursor: pointer;
      text-transform: uppercase;
      letter-spacing: 0.07em;
      user-select: none;
      font-weight: var(--tnp-fw-emph);
      transition: color 120ms ease;
      padding: 4px 0;
      min-height: 24px;
    }
    .tnp-details-toggle:focus-visible {
      outline: 2px solid var(--tnp-accent-2);
      outline-offset: 1px;
    }
    .tnp-details-toggle:hover { color: var(--tnp-accent-text); }
    .tnp-details-toggle::after {

      content: '';
      display: inline-block;
      width: 5px;
      height: 5px;
      margin-left: 6px;
      border-right: 1.5px solid currentColor;
      border-bottom: 1.5px solid currentColor;
      transform: rotate(45deg);
      vertical-align: 1px;
      opacity: .7;
    }
    .tnp-details-toggle.tnp-toggle-open::after {
      transform: rotate(-135deg);
      vertical-align: 0;
    }

    .tnp-range-chips {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 5px;
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
    }
    .tnp-range-lead {
      color: var(--tnp-muted);
      text-transform: uppercase;
      letter-spacing: 0.07em;
      font-weight: var(--tnp-fw-label);
    }
    .tnp-range-chip {
      background: rgba(255, 255, 255, 0.05);
      border: none;
      border-radius: 5px;
      padding: 3px 8px;
      color: var(--tnp-muted);
    }

    .tnp-input {
      width: 116px;
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
      border-radius: 7px;
      color: var(--tnp-text);
      font-size: var(--tnp-fz-sm);
      font-family: var(--tnp-font-mono);
      padding: 5px 9px;
      text-align: right;
      transition: border-color 120ms ease;
    }
    .tnp-input:focus { outline: none; border-color: var(--tnp-accent-1); }

    .tnp-warn-box {
      font-size: var(--tnp-fz-xs);
      padding: 7px 10px;
      border-radius: 8px;
      border: 1px solid var(--tnp-border);
      background: rgba(255, 90, 90, 0.09);
      color: var(--tnp-text);
      line-height: var(--tnp-lh-loose);
    }
    .tnp-caution-box {
      font-size: var(--tnp-fz-xs);
      padding: 7px 10px;
      border-radius: 8px;
      border: 1px solid var(--tnp-border);
      background: rgba(224, 166, 75, 0.09);
      color: var(--tnp-text);
      line-height: var(--tnp-lh-loose);
    }
    .tnp-info-box {
      font-size: var(--tnp-fz-xs);
      padding: 8px 10px;
      border-radius: 8px;
      border: 1px solid var(--tnp-border);
      background: rgba(155, 166, 180, 0.08);
      color: var(--tnp-muted);
      line-height: var(--tnp-lh-loose);
    }

    #tnp-parser-banner {
      display: none;
      font-size: var(--tnp-fz-xs);
      padding: 7px 9px;
      border-radius: 8px;
      border: 1px solid var(--tnp-border);
      background: rgba(255, 90, 90, 0.08);
      color: var(--tnp-text);
      line-height: 1.45;
    }
    #tnp-parser-banner.tnp-banner-active { display: flex; justify-content: space-between; gap: 8px; align-items: center; }

    #tnp-pause-overlay {
      text-align: center;
      padding: 18px 10px;
      color: var(--tnp-amber);
      font-size: var(--tnp-fz-sm);
      letter-spacing: 0.04em;
      font-weight: 600;
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: center;
    }
    #tnp-body-content.tnp-paused > *:not(#tnp-pause-overlay) { opacity: 0.35; pointer-events: none; }

    .tnp-timeline { display: flex; gap: 5px; align-items: center; }
    .tnp-timeline-step {
      flex: 1;
      text-align: center;
      font-size: var(--tnp-fz-2xs);
      text-transform: uppercase;
      letter-spacing: 0.04em;
      font-weight: var(--tnp-fw-emph);
      padding: 4px 2px;
      border-radius: 5px;
      background: var(--tnp-bg);
      color: var(--tnp-text-faint);
    }
    .tnp-timeline-step.tnp-timeline-done { color: var(--tnp-muted); }
    .tnp-timeline-step.tnp-timeline-now {
      color: var(--tnp-ink);
      background: var(--tnp-accent-1);
      font-weight: var(--tnp-fw-display);
    }

    #tnp-why-panel {
      font-size: var(--tnp-fz-xs);
      color: var(--tnp-muted);
      background: var(--tnp-bg);
      border-radius: 8px;
      padding: 8px 10px;
      line-height: var(--tnp-lh-loose);
      display: none;
    }
    #tnp-why-panel.tnp-banner-active { display: block; }
    #tnp-why-panel b { color: var(--tnp-text); }

    .tnp-tier-tag {
      font-size: var(--tnp-fz-2xs);
      text-transform: uppercase;
      letter-spacing: 0.04em;
      border: none;
      border-radius: 5px;
      padding: 3px 7px;
      color: var(--tnp-muted);
      background: var(--tnp-bg);
      white-space: nowrap;
      font-weight: var(--tnp-fw-emph);
    }
    .tnp-tier-tag.tnp-tier-tentative { color: var(--tnp-amber); }
    .tnp-tier-tag.tnp-tier-developing { color: var(--tnp-accent-2); }
    .tnp-tier-tag.tnp-tier-established { color: var(--tnp-success); }

    .tnp-freshness { font-size: var(--tnp-fz-2xs); color: var(--tnp-text-faint); }

    #tnp-dossier.tnp-mode-compact #tnp-full-body { display: none !important; }
    #tnp-dossier.tnp-mode-compact #tnp-compact-body { display: flex !important; }
    #tnp-dossier.tnp-mode-compact { width: 276px; }
    #tnp-dossier.tnp-mode-compact .tnp-tabs { display: none !important; }
    #tnp-dossier.tnp-mode-minimal #tnp-full-body { display: none !important; }
    #tnp-dossier.tnp-mode-minimal #tnp-compact-body { display: none !important; }
    #tnp-dossier.tnp-mode-minimal #tnp-minimal-body { display: flex !important; }
    #tnp-dossier.tnp-mode-minimal { width: 204px; }
    #tnp-dossier.tnp-mode-minimal .tnp-tabs { display: none !important; }
    #tnp-compact-body, #tnp-minimal-body { display: none; flex-direction: column; gap: 7px; }

    #tnp-minimal-body { padding: 10px 12px; }
    .tnp-minimal-row { display: flex; justify-content: space-between; align-items: center; font-size: var(--tnp-fz-sm); }
    .tnp-minimal-status { font-size: var(--tnp-fz-2xs); text-transform: uppercase; letter-spacing: 0.08em; font-weight: var(--tnp-fw-emph); }

    #tnp-compact-body { padding: 10px 12px; }
    .tnp-mode-restore {

      align-self: flex-end;
      padding: 3px 9px;
      font-size: var(--tnp-fz-2xs);
    }
    .tnp-compact-grid { display: grid; grid-template-columns: 1fr auto; gap: 4px 10px; font-size: var(--tnp-fz-md); }
    .tnp-compact-grid .tnp-label { font-size: var(--tnp-fz-xs); }
    .tnp-compact-grid .tnp-value { font-size: var(--tnp-fz-md); }

    #tnp-dossier.tnp-hc {
      --tnp-text: #FFFFFF;
      --tnp-text-hi: #FFFFFF;
      --tnp-muted: #E3DADE;
      --tnp-text-faint: #C6BAC0;
      --tnp-border: #70525A;
      --tnp-border-hi: #97717C;
      --tnp-surface: #000000;
      --tnp-raised: #1C1013;
      --tnp-bg: #000000;
      --tnp-bg-hover: #2A161B;
      --tnp-accent-1: #FF6B77;
      --tnp-ink: #14090B;
      --tnp-accent-2: #FFC2C9;
      --tnp-neutral: #C3CBD6;
      --tnp-act-fold: #FF7B7B;
      --tnp-act-call: #6FB6FF;
      --tnp-act-raise: #5CE08D;
    }

    #tnp-dossier.tnp-hc .tnp-stat-box,
    #tnp-dossier.tnp-hc .tnp-player-row,
    #tnp-dossier.tnp-hc .tnp-badge,
    #tnp-dossier.tnp-hc .tnp-tier-tag,
    #tnp-dossier.tnp-hc #tnp-stat-guide,
    #tnp-dossier.tnp-hc #tnp-why-panel,
    #tnp-dossier.tnp-hc .tnp-timeline-step { border: 1px solid var(--tnp-border); }

    #tnp-dossier.tnp-opaque,
    #tnp-dossier.tnp-opaque #tnp-action-banner {
      backdrop-filter: none !important;
      -webkit-backdrop-filter: none !important;
      background: var(--tnp-surface);
    }

    .tnp-tab[role="tab"] {
      background: transparent;
      border: none;
      border-bottom: 2px solid transparent;
      font-family: var(--tnp-font);
      min-height: 32px;
    }
    .tnp-tab[role="tab"]:focus-visible,
    #tnp-toggle:focus-visible,
    #tnp-header:focus-visible,
    .tnp-seat-badge:focus-visible,
    .tnp-text-btn:focus-visible,
    .tnp-quality-btn:focus-visible {
      outline: 2px solid var(--tnp-accent-2);
      outline-offset: 1px;
    }
    .tnp-tab[role="tab"][aria-selected="true"] { color: var(--tnp-text-hi); border-bottom-color: var(--tnp-accent-1); }
    .tnp-tab[role="tab"].active { color: var(--tnp-text-hi); border-bottom-color: var(--tnp-accent-1); }

    button.tnp-seat-badge {
      background: transparent;
      border: none;
      padding: 0;
      font-family: var(--tnp-font);
    }

    .tnp-inventory-row {
      display: flex;
      justify-content: space-between;
      gap: 8px;
      font-size: var(--tnp-fz-xs);
      color: var(--tnp-muted);
      padding: 3px 0;
      border-bottom: 1px dotted var(--tnp-border);
    }
    .tnp-inventory-row:last-child { border-bottom: none; }
    .tnp-inventory-row b { color: var(--tnp-text); font-weight: 600; }

    .tnp-mode-btns { display: flex; gap: 6px; }
    .tnp-mode-btns .tnp-quality-btn { flex: 1; text-align: center; }

    #tnp-dossier.tnp-pda {
      width: min(420px, calc(100vw - 16px));
      max-height: min(82vh, 760px);
      right: 8px;

      top: calc(8px + env(safe-area-inset-top, 0px));
      bottom: auto;
    }
    #tnp-dossier.tnp-pda #tnp-body { padding: 11px 12px 13px; }
    #tnp-dossier.tnp-pda #tnp-header { padding: 11px 12px 10px; }
    #tnp-dossier.tnp-pda #tnp-toggle { min-width: 34px; min-height: 34px; }
    #tnp-dossier.tnp-pda .tnp-tabs {
      overflow-x: auto;
      scrollbar-width: none;
      -webkit-overflow-scrolling: touch;
    }
    #tnp-dossier.tnp-pda .tnp-tabs::-webkit-scrollbar { display: none; }
    #tnp-dossier.tnp-pda .tnp-tab {
      flex: 0 0 auto;
      min-width: 64px;
      min-height: 40px;
      padding: 9px 8px;
      font-size: var(--tnp-fz-2xs);
    }
    #tnp-dossier.tnp-pda .tnp-stat-grid {
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 6px;
    }
    #tnp-dossier.tnp-pda .tnp-stat-box { min-width: 0; padding: 6px 8px 7px; }
    #tnp-dossier.tnp-pda .tnp-stat-box .tnp-stat-label { font-size: var(--tnp-fz-2xs); line-height: var(--tnp-lh-tight); }
    #tnp-dossier.tnp-pda .tnp-stat-box .tnp-stat-val { font-size: var(--tnp-fz-stat-touch); }
    #tnp-dossier.tnp-pda .tnp-text-btn,
    #tnp-dossier.tnp-pda .tnp-quality-btn {
      min-height: 38px;
      padding: 9px 12px;
    }
    #tnp-dossier.tnp-pda .tnp-setting-row { gap: 10px; align-items: center; }
    #tnp-dossier.tnp-pda .tnp-setting-row .tnp-label { white-space: normal; }
    #tnp-dossier.tnp-pda .tnp-input { width: 122px; min-height: 36px; }

    @media (max-width: 480px) {

      #tnp-action-banner .tnp-banner-sub { display: none; }
      #tnp-dossier,
      #tnp-dossier.tnp-pda {
        width: calc(100vw - 16px) !important;
        max-width: calc(100vw - 16px);

        top: calc(8px + env(safe-area-inset-top, 0px)) !important;
        bottom: auto !important;
        right: 8px !important;
        left: 8px !important;

        max-height: 82vh;
      }
      #tnp-dossier .tnp-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
      #tnp-dossier .tnp-tab { min-height: 40px; padding: 9px 7px; }
      #tnp-dossier .tnp-stat-box { padding: 7px 7px 8px; }
      #tnp-dossier .tnp-stat-val { font-size: var(--tnp-fz-stat-touch) !important; }
      #tnp-dossier .tnp-text-btn, #tnp-dossier .tnp-quality-btn { min-height: 38px; padding: 9px 12px; }
      #tnp-dossier #tnp-toggle { min-width: 34px; min-height: 34px; }
    }
    @media (max-width: 768px) and (min-width: 481px) {
      #tnp-dossier { width: min(348px, calc(100vw - 24px)); }
    }

    #tnp-dossier { font-size: calc(var(--tnp-fz-md) * var(--tnp-scale, 1)); }

    @media (prefers-reduced-motion: reduce) {
      .tnp-pulse { animation: none; }
      .tnp-flash { animation: none; }
      .tnp-equity-fill, .tnp-equity-ci, .tnp-equity-tick { transition: none; }
    }

    .tnp-outs-draws { color: var(--tnp-accent-2); }
    .tnp-site-card.tnp-out-eq { outline: 1px solid rgba(105, 200, 160, 0.75); }
    .tnp-card-mini.tnp-out-eq { outline: 1px solid rgba(105, 200, 160, 0.75); }
    .tnp-replay-bar { display: flex; align-items: center; justify-content: space-between; gap: 6px; }
    .tnp-replay-bar .tnp-value { font-size: var(--tnp-fz-xs); color: var(--tnp-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .tnp-replay-cf { display: flex; flex-direction: column; gap: 3px; margin-top: 4px; }
    .tnp-replay-cf-row { display: flex; justify-content: space-between; gap: 8px; font-size: var(--tnp-fz-xs); color: var(--tnp-text); }
    .tnp-replay-cf-row span:first-child { color: var(--tnp-muted); }
    .tnp-replay-actions { display: flex; flex-direction: column; gap: 2px; margin-top: 4px; }
    .tnp-replay-action { font-size: var(--tnp-fz-2xs); color: var(--tnp-text-faint); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .tnp-timeline button.tnp-timeline-step { cursor: pointer; font-family: inherit; }
    .tnp-drill-answers { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
    .tnp-drill-btn { flex: 1 1 70px; min-width: 64px; padding: 6px 8px; border-radius: 8px; border: 1px solid var(--tnp-border-hi); background: var(--tnp-raised); color: var(--tnp-text); font-size: var(--tnp-fz-xs); cursor: pointer; }
    .tnp-drill-btn:hover { background: var(--tnp-bg-hover); }
    .tnp-diag-table { display: flex; flex-direction: column; gap: 3px; }
    .tnp-diag-row { display: flex; align-items: baseline; gap: 6px; font-size: var(--tnp-fz-2xs); flex-wrap: wrap; }
    .tnp-diag-status { flex: 0 0 38px; font-weight: 600; letter-spacing: 0.03em; }
    .tnp-diag-component { flex: 0 0 auto; color: var(--tnp-text); font-weight: 600; }
    .tnp-diag-detail { flex: 1 1 120px; color: var(--tnp-muted); overflow-wrap: anywhere; }

`;

  const NOIR_UI2_CSS = `
    :root {
      --tnp-r-outer: 10px;
      --tnp-r-inner: 7px;
      --tnp-elev: 0 10px 30px rgba(0, 0, 0, .45), 0 2px 8px rgba(0, 0, 0, .4);
      --tnp-focus: 0 0 0 2px rgba(216, 59, 73, .9);
    }

    #tnp-dossier {
      border-radius: var(--tnp-r-outer);
      box-shadow: var(--tnp-elev), inset 0 1px 0 var(--tnp-glass-edge);
    }

    #tnp-dossier button:focus-visible,
    #tnp-dossier input:focus-visible,
    #tnp-dossier textarea:focus-visible,
    #tnp-dossier [tabindex]:focus-visible {
      outline: none;
      box-shadow: var(--tnp-focus);
    }

    .tnp-tabs {
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
      border-radius: var(--tnp-r-inner);
      padding: 3px;
      gap: 2px;
    }
    .tnp-tab {
      border-radius: 5px;
      padding: 4px 10px;
      transition: background .14s ease-out, color .14s ease-out;
    }
    .tnp-tab:hover { background: var(--tnp-bg-hover); }
    .tnp-tab.active,
    .tnp-tab[aria-selected="true"] {
      background: var(--tnp-raised);
      color: var(--tnp-text-hi);
      box-shadow: inset 0 -2px 0 var(--tnp-accent-1), inset 0 1px 0 var(--tnp-glass-edge);
    }

    .tnp-stat-box {
      border: 1px solid var(--tnp-border);
      border-radius: var(--tnp-r-inner);
      transition: border-color .14s ease-out;
    }
    .tnp-stat-box:hover { border-color: var(--tnp-border-hi); }
    .tnp-stat-box .tnp-stat-label {
      text-transform: uppercase;
      letter-spacing: .05em;
    }

    .tnp-freshness { color: var(--tnp-muted); }
    .tnp-history-net { font-weight: var(--tnp-fw-emph); }

    #tnp-dossier .tnp-value,
    #tnp-dossier .tnp-stat-val,
    #tnp-dossier .tnp-ledger-count,
    #tnp-dossier .tnp-ledger-net,
    #tnp-dossier .tnp-history-net,
    #tnp-dossier .tnp-history-tail,
    #tnp-dossier .tnp-spark-now,
    #tnp-dossier .tnp-meter-val {
      font-variant-numeric: tabular-nums;
      font-feature-settings: "tnum" 1;
    }

    .tnp-compact-grid {
      display: grid;
      grid-template-columns: auto 1fr;
      gap: 2px 10px;
      justify-items: end;
      text-align: right;
    }
    .tnp-compact-grid .tnp-label { justify-self: start; text-align: left; }
    .tnp-minimal-row {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 8px;
    }
    .tnp-minimal-status { color: var(--tnp-muted); font-size: var(--tnp-fz-xs); }

    .tnp-equity-bar {
      height: 10px;
      border-radius: 5px;
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
    }
    .tnp-equity-fill { border-radius: 5px; }

    .tnp-tier-tag {
      border-radius: 999px;
      padding: 1px 8px;
      border: 1px solid var(--tnp-border);
    }

    .tnp-table-card {
      background: var(--tnp-raised);
      border: 1px solid var(--tnp-border);
      border-radius: var(--tnp-r-inner);
      padding: 10px 12px;
      display: grid;
      gap: 6px;
    }
    .tnp-table-card > div {
      font-size: var(--tnp-fz-md);
      line-height: var(--tnp-lh-body);
    }
    .tnp-idpill:empty { display: none; }

    .tnp-pill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 2px 9px;
      border-radius: 999px;
      font-size: var(--tnp-fz-2xs);
      font-weight: var(--tnp-fw-emph);
      letter-spacing: .05em;
      text-transform: uppercase;
      border: 1px solid transparent;
      white-space: nowrap;
    }
    .tnp-pill-ok     { color: var(--tnp-success); border-color: rgba(62, 207, 122, .7);  background: rgba(62, 207, 122, .1); }
    .tnp-pill-warn   { color: var(--tnp-amber);   border-color: rgba(240, 180, 91, .7); background: rgba(240, 180, 91, .1); }
    .tnp-pill-dim    { color: var(--tnp-muted);   border-color: var(--tnp-border);        background: var(--tnp-glass-fill); }
    .tnp-toast.tnp-toast-info .tnp-toast-dot { background: var(--tnp-neutral); }

    .tnp-spark {
      display: grid;
      gap: 4px;
      padding: 8px 10px;
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
      border-radius: var(--tnp-r-inner);
    }
    .tnp-spark-head {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 8px;
    }
    .tnp-spark-cap {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
      letter-spacing: .04em;
      text-transform: uppercase;
    }
    .tnp-spark-now { font-size: var(--tnp-fz-sm); font-weight: var(--tnp-fw-emph); }
    .tnp-spark-now.tnp-up { color: var(--tnp-success); }
    .tnp-spark-now.tnp-down { color: var(--tnp-danger); }
    .tnp-spark-now.tnp-flat { color: var(--tnp-muted); }
    .tnp-spark-svg { display: block; width: 100%; height: 34px; }
    .tnp-spark-note {
      font-size: var(--tnp-fz-xs);
      color: var(--tnp-text-faint);
      padding: 2px 0 6px;
    }

    .tnp-meters { display: grid; gap: 6px; margin-top: 6px; }
    .tnp-meter-row {
      display: grid;
      grid-template-columns: 86px 1fr 84px;
      align-items: center;
      gap: 8px;
    }
    .tnp-meter-label {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
      text-transform: uppercase;
      letter-spacing: .04em;
    }
    .tnp-meter-track {
      height: 6px;
      border-radius: 3px;
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
      overflow: hidden;
    }
    .tnp-meter-fill {
      display: block;
      height: 100%;
      border-radius: 3px;
      background: var(--tnp-neutral);
      min-width: 2px;
      transition: width .2s ease-out;
    }
    .tnp-meter-row.tnp-over .tnp-meter-fill { background: var(--tnp-amber); }
    .tnp-meter-row.tnp-dead .tnp-meter-fill { background: var(--tnp-danger); }
    .tnp-meter-val {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
      text-align: right;
    }
    .tnp-meter-total {
      border-top: 1px solid var(--tnp-border);
      padding-top: 6px;
      margin-top: 2px;
    }
    .tnp-meter-pool {
      margin-top: 6px;
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
      line-height: var(--tnp-lh-body);
    }

    .tnp-inventory-row {
      display: grid;
      gap: 2px;
      padding: 6px 0;
      border-bottom: 1px dashed var(--tnp-border);
    }
    .tnp-inventory-row:last-child { border-bottom: 0; }
    .tnp-inventory-row b { font-size: var(--tnp-fz-sm); font-weight: var(--tnp-fw-emph); }
    .tnp-inventory-row span { font-size: var(--tnp-fz-xs); color: var(--tnp-muted); }

    .tnp-toasts {
      position: absolute;
      right: 10px;
      bottom: 10px;
      z-index: 40;
      display: flex;
      flex-direction: column;
      gap: 6px;
      width: min(300px, calc(100% - 20px));
      pointer-events: none;
    }
    .tnp-toast {
      pointer-events: auto;
      display: grid;
      grid-template-columns: auto 1fr auto;
      gap: 8px;
      align-items: start;
      background: var(--tnp-raised);
      border: 1px solid var(--tnp-border);
      border-radius: var(--tnp-r-inner);
      padding: 8px 10px;
      font-size: var(--tnp-fz-sm);
      line-height: var(--tnp-lh-body);
      color: var(--tnp-text);
      box-shadow: var(--tnp-elev);
      animation: tnp-toast-in .16s ease-out;
    }
    .tnp-toast.tnp-toast-ok .tnp-toast-dot { background: var(--tnp-success); }
    .tnp-toast.tnp-toast-warn .tnp-toast-dot { background: var(--tnp-amber); }
    .tnp-toast.tnp-toast-info .tnp-toast-dot { background: var(--tnp-neutral); }
    .tnp-toast.tnp-toast-out {
      opacity: 0;
      transform: translateY(4px);
      transition: opacity .18s ease-out, transform .18s ease-out;
    }
    .tnp-toast-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: var(--tnp-neutral);
      margin-top: 6px;
    }
    .tnp-toast-x {
      background: none;
      border: 0;
      color: var(--tnp-muted);
      cursor: pointer;
      font-size: var(--tnp-fz-md);
      line-height: 1;
      padding: 2px 4px;
      border-radius: 4px;
    }
    .tnp-toast-x:hover { color: var(--tnp-text-hi); background: var(--tnp-bg-hover); }
    @keyframes tnp-toast-in {
      from { opacity: 0; transform: translateY(6px); }
      to   { opacity: 1; transform: none; }
    }

    #tnp-dossier.tnp-hc .tnp-toast { background: #000; border-color: var(--tnp-border-hi); }
    #tnp-dossier.tnp-hc .tnp-spark,
    #tnp-dossier.tnp-hc .tnp-meter-track { background: #000; }
    #tnp-dossier.tnp-pda .tnp-toasts { bottom: 16px; }
    #tnp-dossier.tnp-pda .tnp-spark-svg { height: 26px; }
    @media (max-width: 480px) {
      .tnp-toasts { width: calc(100% - 20px); }
      .tnp-spark-svg { height: 26px; }
    }
    @media (prefers-reduced-motion: reduce) {
      .tnp-tab,
      .tnp-stat-box,
      .tnp-meter-fill,
      .tnp-toast,
      .tnp-toast.tnp-toast-out {
        transition: none;
        animation: none;
      }
      .tnp-toast { opacity: 1; transform: none; }
    }

    #tnp-dossier label.tnp-label[for] { cursor: pointer; }

    .tnp-decision {
      display: flex;
      flex-direction: column;
      gap: 6px;
      background: var(--tnp-bg);
      border: 1px solid var(--tnp-border);
      border-radius: 8px;
      padding: 7px 8px;
    }
    .tnp-decision.tnp-hidden { display: none; }
    .tnp-decision .tnp-stat-box { padding: 4px 7px 5px; }
    .tnp-decision-verdict {
      border-radius: 6px;
      padding: 4px 8px;
      font-size: var(--tnp-fz-xs);
      font-weight: var(--tnp-fw-emph);
      text-align: center;
      letter-spacing: 0.02em;
      border: 1px solid transparent;
    }
    .tnp-verdict-ok {
      background: rgba(62, 207, 122, 0.12);
      color: var(--tnp-success);
      border-color: rgba(62, 207, 122, 0.35);
    }
    .tnp-verdict-bad {
      background: rgba(255, 90, 90, 0.10);
      color: var(--tnp-danger);
      border-color: rgba(255, 90, 90, 0.32);
    }
    .tnp-verdict-neutral {
      background: rgba(155, 166, 180, 0.08);
      color: var(--tnp-muted);
      border-color: var(--tnp-border);
    }
    .tnp-decision #tnp-d-ev.tnp-d-pos { color: var(--tnp-success); }
    .tnp-decision #tnp-d-ev.tnp-d-neg { color: var(--tnp-danger); }
    .tnp-decision #tnp-d-gap.tnp-d-pos { color: var(--tnp-success); }
    .tnp-decision #tnp-d-gap.tnp-d-neg { color: var(--tnp-danger); }

    .tnp-outs-cards {
      display: flex;
      flex-wrap: wrap;
      gap: 3px;
      align-items: center;
    }
    .tnp-outs-cards:empty { display: none; }
    .tnp-outs-cards .tnp-out-chip, .tnp-outs-cards .tnp-site-card { transform: scale(0.78); transform-origin: top left; margin-right: -6px; }
    .tnp-outs-cards .tnp-card-mini.tnp-out-chip { width: 19px; height: 26px; font-size: 11px; border-radius: 3px; }
    .tnp-card-mini.tnp-card-noasset { outline: 1px dashed var(--tnp-border-hi); outline-offset: -1px; }
    .tnp-outs-cards .tnp-card-mini {
      width: 20px;
      height: 28px;
      font-size: 11px;
      border-radius: 3px;
      box-shadow: none;
      background: var(--tnp-raised);
      border: 1px solid var(--tnp-border);
    }
    .tnp-outs-cards .tnp-card-mini.tnp-out-dirty {
      opacity: 0.55;
      border-color: rgba(240, 180, 91, 0.7);
    }
    .tnp-outs-more, .tnp-outs-count {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-text-faint);
      margin-left: 3px;
    }

    .tnp-chart-box { margin-top: 4px; }
    .tnp-chart-box canvas { max-height: 150px; }

    .tnp-card-mini.tnp-card-back {
      background: #241c20;
      border: 1px solid var(--tnp-border-hi);
    }
    .tnp-site-card {
      width: 20px;
      height: 28px;
      overflow: hidden;
      position: relative;
      border-radius: 2px;
      flex: 0 0 auto;
      background: #0d0b0d;
    }
    .tnp-site-card.tnp-out-dirty { opacity: 0.55; outline: 1px solid rgba(240, 180, 91, 0.7); }
    .tnp-outs-cards { gap: 2px; }

    .tnp-ev-gauge {
      position: relative;
      height: 10px;
      border-radius: 6px;
      background: rgba(255, 255, 255, .06);
      overflow: hidden;
      margin: 4px 0 2px 0;
    }
    .tnp-ev-gauge-fill {
      height: 100%;
      width: 0;
      border-radius: 6px;
      background: var(--tnp-success);
      transition: width .3s ease;
    }
    .tnp-ev-gauge-fill.tnp-ev-neg { background: var(--tnp-danger); }
    .tnp-ev-gauge-fill.tnp-ev-marginal { background: var(--tnp-amber); }
    .tnp-ev-gauge-req {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 2px;
      background: #fff;
      box-shadow: 0 0 3px rgba(255,255,255,.8);
    }

    .tnp-decision-row {
      display: flex;
      align-items: baseline;
      gap: 6px;
      flex-wrap: wrap;
      font-size: var(--tnp-fz-2xs);
      padding: 3px 0;
      border-bottom: 1px solid rgba(255,255,255,.04);
    }
    .tnp-decision-meta { color: var(--tnp-text); font-weight: var(--tnp-fw-emph); white-space: nowrap; }
    .tnp-decision-why { color: var(--tnp-muted); flex: 1 1 120px; }
    .tnp-verdict {
      font-size: 9px;
      letter-spacing: .4px;
      border-radius: 4px;
      padding: 1px 5px;
      font-weight: var(--tnp-fw-display);
    }
    .tnp-verdict-good { background: rgba(62, 207, 122, .16); color: var(--tnp-success); }
    .tnp-verdict-marginal { background: rgba(240, 180, 91, .16); color: var(--tnp-amber); }
    .tnp-verdict-expensive { background: rgba(255, 90, 90, .16); color: var(--tnp-danger); }

    .tnp-last-decision {
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-muted);
      margin-top: 2px;
      min-height: 0;
    }
    .tnp-last-decision:not(:empty) { padding: 3px 0; }



    .tnp-diag-integrity { margin-top: 8px; }
    .tnp-integrity { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
    .tnp-integrity-item { font-size: var(--tnp-fz-2xs); color: var(--tnp-text-faint); }
    .tnp-integrity-item::before { content: "\\2022"; margin-right: 3px; color: var(--tnp-border-hi); }
    .tnp-integrity-note { margin-top: 4px; font-size: var(--tnp-fz-2xs); color: var(--tnp-text-faint); line-height: 1.5; }
    .tnp-player-trend {
      grid-column: 1 / -1;
      font-size: var(--tnp-fz-2xs);
      color: var(--tnp-text-faint);
      line-height: 1.5;
    }
    .tnp-player-row { display: grid; grid-template-columns: 30px 1fr auto auto; gap: 4px 6px; align-items: center; }
`;

  let mySeat = null;
  let uiElement = null;
  let isMinimized = false;
  let minimizedBodyEl = null;
  let minimizedBodyPlaceholder = null;
  let minimizedStyleBackup = null;
  let suppressNextToggleClick = false;
  let dragPos = { x: 0, y: 0 };
  let userFoldedThisHand = false;
  let lastHoleKey = '';
  let handEvidence = {
    key: '', messages: [], heroName: '', heroVoluntary: false, heroWon: false, heroShowed: false
  };
  let replayCurrent = null;
  let replayLog = [];
  let replayCursor = 0;
  let replayStreetCursor = 0;
  const REPLAY_LOG_CAP = 25;
  let drillState = { active: null, answered: null, score: { seen: 0, matched: 0 } };
  let drillSeq = 0;
  const perfWatch = { supported: false, installed: false, longTasks: 0, totalLongMs: 0, worstLongMs: 0, lastLongAt: 0 };
  const installPerfWatch = () => {
    if (perfWatch.installed) return;
    try {
      if (typeof PerformanceObserver !== 'function') return;
      const po = new PerformanceObserver((list) => {
        try {
          for (const entry of list.getEntries()) {
            if (entry && entry.entryType === 'longtask') {
              perfWatch.longTasks++;
              perfWatch.totalLongMs += entry.duration || 0;
              if ((entry.duration || 0) > perfWatch.worstLongMs) perfWatch.worstLongMs = entry.duration || 0;
              perfWatch.lastLongAt = Date.now();
            }
          }
        } catch { }
      });
      po.observe({ entryTypes: ['longtask'] });
      perfWatch.supported = true;
      perfWatch.installed = true;
    } catch { }
  };
  let lastRecAt = 0;
  let lastRecIntent = '';
  let lastComputeMs = 0;
  let lastHeroSeatOk = null;
  let observerLastMutationAt = 0;
  let mcJobId = 0;
  let activeTab = 'analysis';
  let prevHeroTurn = false;

  let pendingSessionTableCtx = null;

  const SETTINGS_KEY = 'tnp_settings_v2';
  const DEFAULT_SETTINGS = {
    cardHighlight: true,
    turnFlash: false,
    profileAdjusted: true,
    showHUD: true,
    showExploit: true,
    actionBanner: true,
    panelPos: null,

    displayMode: 'full',

    fontScale: 1.0,
    highContrast: false,
    reducedTransparency: false,
    panelOpacity: 1.0,
    noPreFlopMode: false,
    detailsCollapsed: true,
    profileRetentionDays: 60,
    maxProfiles: 400,
    lastNoticedVersion: '',
    strategyProfile: 'balanced',
    hudEnabled: true
  };
  let settings = { ...DEFAULT_SETTINGS };

  const normalizeSettings = (raw) => {
    const s = { ...DEFAULT_SETTINGS };
    if (!raw || typeof raw !== 'object') return s;
    for (const key of Object.keys(DEFAULT_SETTINGS)) {
      if (!(key in raw)) continue;
      const v = raw[key];
      switch (typeof DEFAULT_SETTINGS[key]) {
        case 'boolean': s[key] = v === true || v === 1 || v === 'true'; break;
        case 'number':
          s[key] = Number.isFinite(Number(v)) ? Number(v) : DEFAULT_SETTINGS[key];
          break;
        case 'string': s[key] = typeof v === 'string' ? v : DEFAULT_SETTINGS[key]; break;
        default: s[key] = v ?? DEFAULT_SETTINGS[key];
      }
    }
    if (!['full', 'compact', 'minimal'].includes(s.displayMode)) s.displayMode = 'full';
    if (!['tight', 'balanced', 'aggressive'].includes(s.strategyProfile)) s.strategyProfile = 'balanced';
    if (![0.9, 1.0, 1.1].includes(s.fontScale)) s.fontScale = 1.0;
    s.panelOpacity = Math.max(0.7, Math.min(1, Number.isFinite(s.panelOpacity) ? s.panelOpacity : 1));
    s.profileRetentionDays = Math.max(7, Math.min(365, Math.round(s.profileRetentionDays) || 90));
    s.maxProfiles = Math.max(50, Math.min(2000, Math.round(s.maxProfiles) || 800));
    return s;
  };

  const quarantineCorruptSegment = (key, raw, error) => {
    try {
      twarn(`[TNP] Stored data for "${key}" was unreadable and has been reset.`, error?.message || error);
      const backupKey = `${key}.corrupt-${Date.now()}`;
      if (typeof localStorage !== 'undefined') localStorage.setItem(backupKey, String(raw ?? ''));
    } catch {  }
  };

  const readJsonSegment = (key, fallback) => {
    try {
      const raw = localStorage.getItem(key);
      if (raw === null || raw === '') return fallback;
      return JSON.parse(raw);
    } catch (err) {
      let raw = null;
      try { raw = localStorage.getItem(key); } catch { }
      quarantineCorruptSegment(key, raw, err);
      return fallback;
    }
  };

  try {
    settings = normalizeSettings({ ...settings, ...readJsonSegment(SETTINGS_KEY, {}) });
  } catch {  }

  const serializeSettings = () => {
    const json = JSON.stringify(settings);
    return [SETTINGS_KEY, json];
  };
  const saveSettings = () => { queueSave('settings'); };

  const STORAGE_KEYS = {
    settings: SETTINGS_KEY,
    profiles: 'tnp_profiles_v2',
    notes: 'tnp_notes_v2',
    lifetime: 'tnp_lifetime_v1',
    bankroll: 'tnp_bankroll_v1',
    hero: 'tnp_hero_v1',
    session: 'tnp_session_v1',
    heal: 'tnp_heal_v1'
  };
  const usingPdaStorage = () => typeof PDA_storage !== 'undefined' && PDA_storage && typeof PDA_storage.loadAll === 'function';

  const persistFns = {};
  const registerPersist = (category, fn) => { persistFns[category] = fn; };
  registerPersist('settings', (returnPayload = false) => serializeSettings());

  const SAVE_DEBOUNCE_MS = {
    settings: 250,
    profiles: 1500,
    notes: 400,
    lifetime: 1000,
    bankroll: 1000,
    hero: 1200,
    session: 1000,
    heal: 5000
  };
  const saveTimers = {};
  const dirtyCategories = new Set();

  const flushSave = (category) => {
    const fn = persistFns[category];
    if (!fn) return;
    try {

      enforceCategoryBudget(category);

      const [key, value] = fn(true);
      if (!key) return;
      if (usingPdaStorage()) {
        PDA_storage.set(key, value).catch(err => {
          if (err && (err.code === 'QuotaExceeded' || /quota|full/i.test(String(err?.message || err)))) {

            const actions = emergencyShrink();
            PDA_storage.set(key, value).catch(err2 => {
              twarn(`[TNP] PDA storage quota stayed full after shrinking ${actions.join(', ') || 'nothing'}. `
                + 'Data is kept in memory only; clear old HUD data in Setup.');
            });
          } else {
            twarn('[TNP] PDA storage write failed:', err?.message || err);
          }
        });
      }
      if (idbPrimary && category !== 'settings') {
        storageState.bytes[key] = value.length;
        TNP6.putKv('tnp_' + key, value);
        return;
      }
      if (!safeSetItem(key, value)) return;
      if (STORAGE_MIRROR_CATEGORIES.has(category)) {
        try { TNP6.putKv('mirror_' + key, value); } catch { }
      }
    } catch (err) {

      twarn(`[TNP] Could not persist ${category}:`, err?.message || err);
    }
  };

  const queueSave = (category) => {
    dirtyCategories.add(category);
    if (saveTimers[category]) clearTimeout(saveTimers[category]);
    saveTimers[category] = setTimeout(() => {
      saveTimers[category] = null;
      dirtyCategories.delete(category);
      flushSave(category);
    }, SAVE_DEBOUNCE_MS[category] ?? 800);
  };

  const flushAllSaves = (reason = 'explicit') => {
    for (const category of Object.keys(persistFns)) {
      if (saveTimers[category]) { clearTimeout(saveTimers[category]); saveTimers[category] = null; }
      if (dirtyCategories.has(category)) { dirtyCategories.delete(category); flushSave(category); }
    }
    void reason;
  };

  const storage = {
    available: () => usingPdaStorage(),
    backendName: () => usingPdaStorage() ? 'PDA native storage' : 'browser localStorage',
    async loadPdaOverlay() {
      if (!usingPdaStorage()) return;
      const load = async (key, apply) => {
        try {
          const raw = await PDA_storage.get(key, null);
          if (raw === null || raw === undefined || raw === '') return;
          const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
          apply(parsed);
        } catch (err) {
          let rawPda = null;
          try { rawPda = typeof raw === 'string' ? raw : JSON.stringify(raw); } catch { }
          quarantineCorruptSegment(key, rawPda, err);
        }
      };
      await load(STORAGE_KEYS.settings, (v) => { settings = normalizeSettings({ ...settings, ...v }); });
      await load(STORAGE_KEYS.profiles, (v) => { if (v && typeof v === 'object') profiles = loadProfilesFrom(v); });
      await load(STORAGE_KEYS.notes, (v) => { if (v && typeof v === 'object') playerNotes = v; });
      await load(STORAGE_KEYS.lifetime, (v) => { if (v && typeof v === 'object') lifetime = { ...lifetime, ...v }; });
      await load(STORAGE_KEYS.bankroll, (v) => { bankroll = normalizeBankrollState({ ...bankroll, ...v }); });
      await load(STORAGE_KEYS.hero, (v) => { if (v && typeof v === 'object') heroStats = normalizeHeroStats(v); });

      await load(STORAGE_KEYS.session, (v) => {
        const savedHands = Number(v?.session?.handsPlayed) || 0;
        if (!(session.handsPlayed > savedHands)) restoreSavedSession(v);
      });
    },

    async removeAll() {
      if (usingPdaStorage()) {
        try { await PDA_storage.setMany(Object.fromEntries(Object.values(STORAGE_KEYS).map(k => [k, null]))); }
        catch (err) { twarn('[TNP] PDA clear failed:', err?.message || err); }
      }
      try {

        for (const key of Object.values(STORAGE_KEYS)) localStorage.removeItem(key);
        if (typeof localStorage !== 'undefined') {
          const doomed = [];
          for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key && /^tnp_.+\.corrupt-\d+$/.test(key)) doomed.push(key);
          }
          for (const key of doomed) localStorage.removeItem(key);
        }
        storageState.degraded.clear();
        updateHealthBadge();
      } catch {  }
    }
  };

  const STORAGE_BUDGETS = Object.freeze({
    settings: 6 * 1024,
    profiles: 128 * 1024,
    notes: 48 * 1024,
    lifetime: 2 * 1024,
    bankroll: 16 * 1024,
    hero: 24 * 1024,
    session: 12 * 1024,
    heal: 32 * 1024
  });
  const STORAGE_TOTAL_BUDGET = 320 * 1024;

        const STORAGE_MIRROR_CATEGORIES = new Set(['profiles', 'notes', 'hero']);
  let idbPrimary = false;

  const ORIGIN_POOL_SOFT_LIMIT = 4.5 * 1024 * 1024;
  const ORIGIN_POOL_CHECK_MS = 60 * 1000;
  let _originPoolCache = { at: 0, bytes: 0 };
  const originPoolBytes = () => {
    const now = Date.now();
    if (now - _originPoolCache.at < 30 * 1000) return _originPoolCache.bytes;
    let total = 0;
    try {
      for (let i = 0; i < localStorage.length; i++) {
        const k = localStorage.key(i);
        if (k) total += k.length + (localStorage.getItem(k) || '').length;
      }
    } catch {  }
    _originPoolCache = { at: now, bytes: total };
    return total;
  };
  const NOTES_MAX_ROWS = 400;
  const QUARANTINE_KEEP_PER_KEY = 2;
  const QUARANTINE_MAX_AGE_MS = 7 * 86400000;

  const CATEGORY_BY_KEY = {};
  for (const [cat, key] of Object.entries(STORAGE_KEYS)) CATEGORY_BY_KEY[key] = cat;

  const storageState = {
    degraded: new Set(),
    lastQuotaAt: 0,
    bytes: {},
    lastWriteOk: {},
    shrunkCategories: new Set(),
    shrinks: 0,
    lastAction: ''
  };

  const keyBytes = (key) => {
    try { return (localStorage.getItem(key) || '').length; } catch { return 0; }
  };
  const refreshStorageBytes = () => {
    for (const key of Object.values(STORAGE_KEYS)) storageState.bytes[key] = keyBytes(key);
    return storageState.bytes;
  };

  const storageBudgetReport = (bytesMap = {}) => {
    const rows = [];
    let total = 0;
    for (const [cat, key] of Object.entries(STORAGE_KEYS)) {
      const used = Math.max(0, bytesMap[key] | 0);
      const budget = STORAGE_BUDGETS[cat] ?? Infinity;
      total += used;
      rows.push({ category: cat, used, budget, over: used > budget, pct: budget ? Math.round(used / budget * 100) : 0 });
    }
    return { rows, total, totalBudget: STORAGE_TOTAL_BUDGET, totalOver: total > STORAGE_TOTAL_BUDGET };
  };

  let inShrinkRetry = false;
  const degradeOnce = (category, err) => {
    if (storageState.degraded.has(category)) return;
    storageState.degraded.add(category);
    twarn(`[TNP] "${category}" could not be persisted even after shrinking (${err?.message || err}). `
      + 'The HUD keeps working from memory this session; clearing old HUD data in Setup frees the pool.');
    updateHealthBadge();
  };
  const safeSetItem = (key, json) => {
    if (typeof localStorage === 'undefined') return false;
    try {
      localStorage.setItem(key, json);
      storageState.bytes[key] = json.length;
      storageState.lastWriteOk[key] = true;
      if (storageState.degraded.delete(CATEGORY_BY_KEY[key] ?? key)) updateHealthBadge();
      return true;
    } catch (err) {
      const isQuota = !!(err && (err.name === 'QuotaExceededError' || err.code === 22 || /quota|full/i.test(String(err?.message || err))));
      const category = CATEGORY_BY_KEY[key] ?? key;
      storageState.lastWriteOk[key] = false;
      if (!isQuota && usingPdaStorage()) return false;
      if (!isQuota) { degradeOnce(category, err); return false; }
      storageState.lastQuotaAt = Date.now();
      if (inShrinkRetry) { degradeOnce(category, err); return false; }
      inShrinkRetry = true;
      try {
        const actions = emergencyShrink();

        const cats = new Set(storageState.shrunkCategories);
        cats.add(category);
        for (const cat of cats) {
          if (!persistFns[cat]) continue;
          try { persistFns[cat](true); } catch {  }
        }
        if (storageState.lastWriteOk[key]) {
          twarn(`[TNP] Storage refused a write; shrank ${actions.join(', ') || 'nothing'}, re-serialized the shrunk state, retried once, succeeded.`);
          return true;
        }
        degradeOnce(category, err);
        return false;
      } finally { inShrinkRetry = false; }
    }
  };

  const emergencyShrink = () => {
    const actions = [];
    storageState.shrunkCategories = new Set();
    const did = (cat, label) => { actions.push(label); storageState.shrinks++; storageState.shrunkCategories.add(cat); };

    if (sweepQuarantine() > 0) actions.push('old error backups');

    if (Object.keys(profiles).length > 24) {
      let guard = 0;
      while (JSON.stringify(profiles).length > 12 * 1024 && Object.keys(profiles).length > 24 && guard++ < 10) {
        const ids = Object.keys(profiles).sort((a, b) => (Number(profiles[a]?.lastSeen) || 0) - (Number(profiles[b]?.lastSeen) || 0));
        const drop = Math.max(4, Math.ceil(ids.length / 3));
        for (let i = 0; i < drop && i < ids.length; i++) delete profiles[ids[i]];
      }
      did('profiles', `profiles → ${Object.keys(profiles).length} rows`);
    }

    if (Object.keys(playerNotes).length > 24) {
      let guard = 0;
      while (JSON.stringify(playerNotes).length > 8 * 1024 && Object.keys(playerNotes).length > 24 && guard++ < 10) {
        const ids = Object.keys(playerNotes);
        const drop = Math.max(4, Math.ceil(ids.length / 3));
        for (let i = 0; i < drop && i < ids.length; i++) delete playerNotes[ids[i]];
      }
      did('notes', `notes → ${Object.keys(playerNotes).length} rows`);
    }

    if (heroStats?.ring?.length > 160) {
      heroStats.ring = heroStats.ring.slice(-160);
      did('hero', 'hero ledger → 160');
    }

    if (Array.isArray(bankroll.history) && bankroll.history.length > 24) {
      bankroll.history = bankroll.history.slice(-24);
      did('bankroll', 'bankroll history → 24');
    }

    if (healStore.features && Object.keys(healStore.features).length > 24) {
      const feats = Object.keys(healStore.features);
      for (let i = 0; i < feats.length - 24; i++) delete healStore.features[feats[i]];
      did('heal', 'heal fingerprints → 24');
    }

    if (session.recentDeltas && session.recentDeltas.length > 20) {
      session.recentDeltas = session.recentDeltas.slice(-20);
      did('session', 'session deltas → 20');
    }
    if (recordedSessionHandKeys && recordedSessionHandKeys.size > 60) {
      recordedSessionHandKeys = new Set(Array.from(recordedSessionHandKeys).slice(-60));
      did('session', 'session hand keys → 60');
    }
    storageState.lastAction = actions.join(', ');
    return actions;
  };

  const pruneProfilesToBytes = (budget) => {
    let guard = 0;
    while (guard++ < 24) {
      const json = JSON.stringify(profiles);
      if (json.length <= budget || Object.keys(profiles).length <= 24) break;
      const ids = Object.keys(profiles).sort((a, b) => (Number(profiles[a]?.lastSeen) || 0) - (Number(profiles[b]?.lastSeen) || 0));
      const drop = Math.max(4, Math.ceil(ids.length / 4));
      for (let i = 0; i < drop && i < ids.length; i++) delete profiles[ids[i]];
    }
  };

  const trimNotesToBytes = (budget) => {
    let guard = 0;
    while (guard++ < 16) {
      const json = JSON.stringify(playerNotes);
      if (json.length <= budget || Object.keys(playerNotes).length <= 24) break;
      const ids = Object.keys(playerNotes);
      const drop = Math.max(4, Math.ceil(ids.length / 4));
      for (let i = 0; i < drop && i < ids.length; i++) delete playerNotes[ids[i]];
    }
    const ids = Object.keys(playerNotes);
    if (ids.length > NOTES_MAX_ROWS) {
      for (let i = 0; i < ids.length - NOTES_MAX_ROWS; i++) delete playerNotes[ids[i]];
    }
  };

  const enforceCategoryBudget = (category) => {
    if (storageState.degraded.has(category)) return;
    const budget = STORAGE_BUDGETS[category];
    if (!budget) return;
    try {
      if (category === 'profiles') pruneProfilesToBytes(budget);
      else if (category === 'notes') trimNotesToBytes(budget);
      else if (category === 'hero') {
        let guard = 0;
        while (heroStats?.ring?.length > 80 && JSON.stringify(heroStats).length > budget && guard++ < 8) {
          heroStats.ring = heroStats.ring.slice(-Math.max(80, Math.floor(heroStats.ring.length * 3 / 4)));
        }
      } else if (category === 'bankroll') {
        let guard = 0;
        while ((bankroll.history?.length ?? 0) > 12 && JSON.stringify(bankroll).length > budget && guard++ < 8) {
          bankroll.history = bankroll.history.slice(-Math.max(12, Math.floor(bankroll.history.length * 3 / 4)));
        }
      } else if (category === 'heal') {
        let guard = 0;
        while (Object.keys(healStore.features ?? {}).length > 12 && JSON.stringify(healStore).length > budget && guard++ < 8) {
          const feats = Object.keys(healStore.features);
          for (let i = 0; i < 8 && i < feats.length; i++) delete healStore.features[feats[i]];
        }
      }

    } catch {  }
  };

  const sweepQuarantine = () => {
    if (typeof localStorage === 'undefined') return 0;
    let removed = 0, removedBytes = 0;
    try {
      const byBase = new Map();
      const keys = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (!key || !/^tnp_.+\.corrupt-\d+$/.test(key)) continue;
        keys.push(key);
      }
      for (const key of keys) {
        const baseEnd = key.lastIndexOf('.corrupt-');
        const base = key.slice(0, baseEnd);
        const ts = Number(key.slice(baseEnd + 9)) || 0;
        const size = (localStorage.getItem(key) || '').length;
        const list = byBase.get(base) ?? [];
        list.push({ key, ts, size });
        byBase.set(base, list);
      }
      const now = Date.now();
      const doomed = new Set();
      let keptBytes = 0;
      for (const list of byBase.values()) {
        list.sort((a, b) => b.ts - a.ts);
        for (let i = 0; i < list.length; i++) {
          if (i >= QUARANTINE_KEEP_PER_KEY || now - list[i].ts > QUARANTINE_MAX_AGE_MS) {
            doomed.add(list[i].key);
          } else {
            keptBytes += list[i].size;
          }
        }
      }
      if (keptBytes > 16 * 1024) {

        const kept = [];
        for (const list of byBase.values()) {
          for (let i = 0; i < Math.min(QUARANTINE_KEEP_PER_KEY, list.length); i++) kept.push(list[i]);
        }
        kept.sort((a, b) => a.ts - b.ts);
        for (const e of kept) {
          if (keptBytes <= 16 * 1024) break;
          doomed.add(e.key);
          keptBytes -= e.size;
        }
      }
      for (const key of doomed) {
        try {
          removedBytes += (localStorage.getItem(key) || '').length;
          localStorage.removeItem(key);
          removed++;
        } catch {  }
      }
      if (removed > 0) {
        tinfo(`[TNP] Storage cleanup: removed ${removed} old unreadable-data backup(s), ~${removedBytes} bytes freed.`);
      }
    } catch {  }
    return removed;
  };

  let gameState = {
    holeCards: [], boardCards: [], activeOpponents: 0, street: 'Preflop',
    evalResult: null, equity: null, equityCI: null, handTypeDist: null,
    isCalculating: false, mcSamples: 0, lastStateHash: '', lastCardHash: '',
    equityMethod: null,
    equityTrialsComplete: false,
    equityMandatedTrials: 1000000,
    equityCached: false,
    exactEquity: null,
    exactSamples: 0,
    potStale: false,
    equityProvisional: false,
    readIssues: null,
    tableAdjust: null,
    preflopOpp: null,
    flopCtx: null,
    winSplit: null,
    mcWorkers: 0,
    mcElapsedMs: 0,
    pot: 0, toCall: 0, toCallUnknown: false, userFolded: false, heroStack: 0,
    effStack: 0, effStackSource: '',
    boardTexture: [], betSizing: null,
    position: 'MP', raiseLevel: 0, outs: null, bbAmount: 0, potOdds: 0, raiseReliable: true,
    boardRiskRead: null,
    oppAggressive: false,
    occupiedSeats: 0
  };

  const PROFILES_KEY = 'tnp_profiles_v2';
  let rawProfiles = {};
  try { rawProfiles = readJsonSegment(PROFILES_KEY, {}) || {}; } catch {  }

  const PROFILE_COUNT_KEYS = ['handsObserved', 'vpipCount', 'pfrCount', 'postAgg', 'postTotal', 'sawFlopCount',
    'wentToShowdownCount', 'wonAtShowdownCount', 'threeBetCount', 'threeBetOpp', 'foldTo3BetCount',
    'foldTo3BetOpp', 'cbetCount', 'cbetOpp', 'foldToCbetCount', 'foldToCbetOpp', 'limpCount',
    'raiseSizeSum', 'raiseSizeCount', 'riverBetFaced', 'riverBetFolded',
    'openRaiseCount', 'openRaiseOpp', 'blindFoldVsOpenCount', 'blindFoldVsOpenOpp',
    'postAggActions', 'postCallActions'];

  const UI_LABEL_NAME_RE = /^(?:(?:current|local|server|torn|game|start|next)\s+(?:time|date|blinds?|levels?)|(?:small|big)\s+blinds?|dealer\s+button|take\s+(?:a\s+)?seat|join\s+(?:the\s+)?(?:table|game)|current\s+(?:hand|pot)|(?:pot|table)\s+(?:size|info)|(?:action|game)\s+log|hand\s+history|players?\s+online|waiting\s+for\s+players?)$/i;

  const CLOCK_READOUT_RE = /\d{1,2}:\d{2}(?::\d{2})?|\b\d{1,2}\s*[ap]m\b/i;

  const ZERO_WIDTH_JUNK_RE = /[\u200B-\u200D\uFEFF\u2060]/g;

  const PURE_NUMBER_TEXT_RE = /^[\s$,.()\d\u2026+-]+$/;

  const UI_LABEL_SQUASH_PHRASES = [
    'currenttime', 'currentdate', 'currentblind', 'currentblinds', 'currentlevel', 'currentlevels',
    'localtime', 'localdate', 'servertime', 'serverdate', 'starttime', 'startdate', 'nexttime', 'nextdate',
    'nextblind', 'nextblinds', 'nextlevel', 'nextlevels',
    'smallblind', 'bigblind', 'dealerbutton',
    'takeaseat', 'takeseat', 'takethisseat', 'jointhetable', 'jointable', 'jointhegame', 'joingame',
    'currenthand', 'currentpot', 'actionlog', 'gamelog', 'handhistory', 'playersonline', 'waitingforplayers',
    'emptyseat', 'openseat', 'seatopen'
  ];

  const UI_LABEL_EXACT_PHRASES = ['torn', 'blinds', 'gametime', 'gamedate', 'potsize', 'tableinfo', 'tablesize'];

  const squashNameText = (name) => String(name ?? '')
    .replace(ZERO_WIDTH_JUNK_RE, '')
    .toLowerCase()
    .replace(/[^a-z0-9]/g, '');

  const isPlausiblePlayerName = (name) => {
    const raw = String(name ?? '');
    if (!raw || raw.length > 30) return false;
    const text = raw.replace(/\s+/g, ' ').trim();
    if (!text) return false;

    if (/[$,]/.test(text)) return false;
    if (UI_LABEL_NAME_RE.test(text)) return false;
    if (CLOCK_READOUT_RE.test(text)) return false;
    if (PURE_NUMBER_TEXT_RE.test(text)) return false;
    const squashed = squashNameText(text);
    if (!squashed) return false;

    if (UI_LABEL_SQUASH_PHRASES.some(phrase => squashed.includes(phrase))) return false;
    if (UI_LABEL_EXACT_PHRASES.includes(squashed)) return false;
    return true;
  };

  const normalizeProfiles = (raw) => {
    const out = {};
    if (!raw || typeof raw !== 'object') return out;
    for (const [id, rec] of Object.entries(raw)) {
      if (!rec || typeof rec !== 'object' || typeof rec.name !== 'string') continue;

      if (!isPlausiblePlayerName(rec.name)) continue;
      const p = {
        name: rec.name,
        aggStreet: (rec.aggStreet && typeof rec.aggStreet === 'object') ? rec.aggStreet
          : { flop: { agg: 0, total: 0 }, turn: { agg: 0, total: 0 }, river: { agg: 0, total: 0 } },
        lastSeen: Number.isFinite(Number(rec.lastSeen)) ? Number(rec.lastSeen) : Date.now(),
        noteTags: Array.isArray(rec.noteTags) ? rec.noteTags.filter(t => typeof t === 'string').slice(0, 8) : []
      };
      for (const k of PROFILE_COUNT_KEYS) p[k] = Number.isFinite(Number(rec[k])) ? Number(rec[k]) : 0;
      if (p.handsObserved < 0) p.handsObserved = 0;
      out[id] = p;
    }
    return out;
  };

  let sweptProfileRows = 0;
  const loadProfilesFrom = (raw) => {
    const before = (raw && typeof raw === 'object') ? Object.keys(raw).length : 0;
    const cleaned = normalizeProfiles(raw);
    sweptProfileRows += Math.max(0, before - Object.keys(cleaned).length);
    return cleaned;
  };
  let profiles = loadProfilesFrom(rawProfiles);

  let lastProfilesJsonWritten = null;

  const serializeProfiles = () => {
    const json = JSON.stringify(profiles);
    lastProfilesJsonWritten = json;
    return [PROFILES_KEY, json];
  };
  registerPersist('profiles', (returnPayload = false) => serializeProfiles());
  const saveProfiles = () => { queueSave('profiles'); };

  const NOTES_KEY = 'tnp_notes_v2';
  let playerNotes = {};
  try { playerNotes = readJsonSegment(NOTES_KEY, {}) || {}; } catch {  }

  const normalizeNotes = (raw) => {
    const out = {};
    if (!raw || typeof raw !== 'object') return out;
    for (const [id, note] of Object.entries(raw)) {
      if (typeof id !== 'string' || !id) continue;
      if (typeof note !== 'string') continue;
      if (note.length > 4000) continue;
      out[id] = note;
    }

    const ids = Object.keys(out);
    if (ids.length > NOTES_MAX_ROWS) {
      for (let i = 0; i < ids.length - NOTES_MAX_ROWS; i++) delete out[ids[i]];
    }
    return out;
  };
  playerNotes = normalizeNotes(playerNotes);

  const serializeNotes = () => {
    const json = JSON.stringify(playerNotes);
    return [NOTES_KEY, json];
  };
  registerPersist('notes', (returnPayload = false) => serializeNotes());
  const saveNotes = () => { queueSave('notes'); };

  const HERO_LEDGER_CAP = 400;
  const HERO_STATS_KEY = 'tnp_hero_v1';

  const freshHeroStats = () => ({
    hands: 0, vpip: 0, pfr: 0, limp: 0,
    postAgg: 0, postTotal: 0, postAggActions: 0, postCallActions: 0,
    sawFlop: 0, wtsd: 0, wsd: 0,
    openOpp: 0, openRaise: 0,
    ring: []
  });

  const normalizeHeroStats = (raw) => {
    const out = freshHeroStats();
    if (!raw || typeof raw !== 'object') return out;
    const num = (v) => Number.isFinite(Number(v)) ? Math.max(0, Math.floor(Number(v))) : 0;
    out.hands = num(raw.hands);
    out.vpip = Math.min(out.hands, num(raw.vpip));
    out.pfr = Math.min(out.hands, num(raw.pfr));
    out.limp = Math.min(out.hands, num(raw.limp));
    out.postAgg = num(raw.postAgg);
    out.postTotal = Math.max(out.postAgg, num(raw.postTotal));
    out.postAggActions = num(raw.postAggActions);
    out.postCallActions = num(raw.postCallActions);
    out.sawFlop = Math.min(out.hands, num(raw.sawFlop));
    out.wtsd = Math.min(out.sawFlop, num(raw.wtsd));
    out.wsd = Math.min(out.wtsd, num(raw.wsd));
    out.openOpp = Math.min(out.hands, num(raw.openOpp));
    out.openRaise = Math.min(out.openOpp, num(raw.openRaise));
    if (Array.isArray(raw.ring)) {
      const seen = new Set();
      for (const rec of raw.ring) {
        if (!rec || typeof rec !== 'object') continue;
        const t = Number(rec.t);
        const net = Number(rec.net);
        if (!Number.isInteger(t) || t < 0 || t > 9) continue;
        if (!Number.isFinite(net) || Math.abs(net) > 1e12) continue;
        const ts = Number(rec.ts);
        const entry = { t, net, ts: Number.isFinite(ts) ? ts : Date.now() };
        const key = `${t}|${net}|${entry.ts}`;
        if (seen.has(key)) continue;
        seen.add(key);
        out.ring.push(entry);
      }
      out.ring.sort((a, b) => a.ts - b.ts);
      out.ring = out.ring.slice(-HERO_LEDGER_CAP);
    }
    return out;
  };

  const heroLedgerApply = (stats, rec) => {
    if (!stats || !rec) return stats;
    const t = Number(rec.t), net = Number(rec.net);
    if (!Number.isInteger(t) || t < 0 || t > 9 || !Number.isFinite(net) || Math.abs(net) > 1e12) return stats;
    stats.ring.push({ t, net, ts: Number.isFinite(Number(rec.ts)) ? Number(rec.ts) : Date.now() });
    if (stats.ring.length > HERO_LEDGER_CAP) stats.ring = stats.ring.slice(-HERO_LEDGER_CAP);
    return stats;
  };

  let heroStats = null;
  try { heroStats = normalizeHeroStats(readJsonSegment(HERO_STATS_KEY, null)); } catch { heroStats = freshHeroStats(); }

  const serializeHeroStats = () => {
    const json = JSON.stringify(heroStats);
    return [HERO_STATS_KEY, json];
  };
  registerPersist('hero', (returnPayload = false) => serializeHeroStats());
  const saveHeroStats = () => { queueSave('hero'); };

  const freshSession = () => ({
    startStack: 0,
    currentStack: 0,
    handsPlayed: 0,
    handsVPIP: 0,
    handsVPIPKnown: 0,
    netChips: 0,
    stackKnown: false,
    stackDeltaKnown: false,
    biggestWin: 0,
    biggestLoss: 0,
    startTime: Date.now(),
    handsWon: 0,
    outcomeKnownHands: 0,
    showdownWins: 0,
    scoreEst: 0,
    recentDeltas: [],
    pendingNet: 0,
    capacityHint: 0,
    lastHandHeroWon: false,
    rebuys: 0,
    netSeries: []
  });
  let session = freshSession();

  let recordedSessionHandKeys = new Set();
  let bootSessionRestored = false;

  let lastAwardSignature = '';

  const LIFETIME_KEY = 'tnp_lifetime_v1';
  let lifetime = {
    handsPlayed: 0, handsWon: 0, showdownWins: 0,
    netChips: 0, scoreEst: 0, bestHandType: 0, sessions: 0
  };
  try { lifetime = { ...lifetime, ...readJsonSegment(LIFETIME_KEY, {}) }; } catch {  }
  const normalizeLifetime = (raw) => {
    const base = { handsPlayed: 0, handsWon: 0, showdownWins: 0, netChips: 0, scoreEst: 0, bestHandType: 0, sessions: 0 };
    if (!raw || typeof raw !== 'object') return base;
    const out = { ...base };
    for (const k of Object.keys(base)) out[k] = Number.isFinite(Number(raw[k])) ? Number(raw[k]) : base[k];
    out.bestHandType = Math.max(0, Math.min(9, Math.round(out.bestHandType)));
    return out;
  };
  lifetime = normalizeLifetime(lifetime);

  const serializeLifetime = () => {
    const json = JSON.stringify(lifetime);
    return [LIFETIME_KEY, json];
  };
  registerPersist('lifetime', (returnPayload = false) => serializeLifetime());
  const saveLifetime = () => { queueSave('lifetime'); };

  const BANKROLL_KEY = 'tnp_bankroll_v1';
  let bankroll = {
    total: 0,
    stopLossBuyIns: 2,
    sessionGoal: 0,
    history: []
  };
  try { bankroll = { ...bankroll, ...readJsonSegment(BANKROLL_KEY, {}) }; } catch {  }
  const serializeBankroll = () => {
    const json = JSON.stringify(bankroll);
    return [BANKROLL_KEY, json];
  };
  registerPersist('bankroll', (returnPayload = false) => serializeBankroll());
  const saveBankroll = () => { queueSave('bankroll'); };

  let lastHeroEvalType = 0;

  const domHealth = {};
  const DOM_HEALTH_LABELS = {
    seats: 'player seats', log: 'action log', holeCards: 'hole cards',
    pot: 'pot size', buttons: 'action buttons', stack: 'hero stack'
  };
  const DOM_HEALTH_LIMITS = { stack: 30 };
  const reportDom = (key, found, expected = true) => {
    let h = domHealth[key];
    if (!h) h = domHealth[key] = { misses: 0, warned: false, ok: true };
    if (!expected) {
      h.misses = 0; h.warned = false; h.ok = true;
      updateHealthBadge();
      return;
    }
    if (found) {
      if (h.warned) tinfo(`[TNP] Recovered: ${DOM_HEALTH_LABELS[key] ?? key} detected again.`);
      h.misses = 0; h.warned = false; h.ok = true;
    } else {
      h.misses++;
      const missLimit = DOM_HEALTH_LIMITS[key] ?? 15;
      if (h.misses >= missLimit && !h.warned) {
        twarn(`[TNP] Could not find ${DOM_HEALTH_LABELS[key] ?? key} for ${h.misses} consecutive checks. `
          + 'Torn may have changed its page structure.');
        h.warned = true; h.ok = false;
      }
    }
    updateHealthBadge();
  };
  const updateHealthBadge = () => {
    const badge = document.getElementById('tnp-health-badge');
    const broken = Object.keys(domHealth).filter(k => domHealth[k].warned);
    const storageIssues = [];
    if (typeof storageState !== 'undefined' && storageState.degraded.size) {
      storageIssues.push(`storage full: ${Array.from(storageState.degraded).join(', ')} kept in memory only`);
    }
    if (badge) {
      if (broken.length || storageIssues.length) {
        badge.classList.remove('tnp-hidden');
        badge.title = ['Could not read from the table: ' + broken.map(k => DOM_HEALTH_LABELS[k] ?? k).join(', ')]
          .concat(storageIssues).join(' · ');
      } else {
        badge.classList.add('tnp-hidden');
      }
    }

    const banner = document.getElementById('tnp-parser-banner');
    if (banner) banner.classList.toggle('tnp-banner-active', broken.length > 0);
    if (broken.length) setHudStatus('parser-issue');
    else if (hudStatus === 'parser-issue') setHudStatus('ready');
  };

  let handTracker = {
    bbAmount: 0,
    processedMsgs: new Set(),
    fallbackSigs: new Set(),
    lastHandSig: null
  };

        const pipelineStats = {
    awardWindows: 0, handsRecorded: 0, heroHands: 0,
    actionsParsed: 0, actionsAttributed: 0, nameMisses: 0, lastHandAt: 0
  };

  let seenAwardLines = new Set();

  const SESSION_BRIDGE_MS = 30 * 60 * 1000;
  const SESSION_KEY = STORAGE_KEYS.session;
  const sessionSavedState = () => ({
    session: { ...session, recentDeltas: (session.recentDeltas ?? []).slice(-40) },
    savedAt: Date.now(),
    handKeys: Array.from(recordedSessionHandKeys).slice(-120),
    seenAwards: Array.from(seenAwardLines).slice(-12),
    lastAwardSignature,
    lastHoleKey,
    lastHandSig: handTracker.lastHandSig ?? '',
    processedSigs: Array.from(handTracker.processedMsgs).slice(-12),
    fallbackSigs: Array.from(handTracker.fallbackSigs).slice(-12),

    table: tableContextSnapshot()
  });
  const serializeSessionState = () => {
    const json = JSON.stringify(sessionSavedState());
    return [SESSION_KEY, json];
  };
  registerPersist('session', (returnPayload = false) => serializeSessionState());
  const saveSession = () => { queueSave('session'); };

  const restoreSavedSession = (saved) => {
    if (!saved || typeof saved !== 'object') return false;
    const savedAt = Number(saved.savedAt);
    const age = Number.isFinite(savedAt) ? Date.now() - savedAt : Infinity;
    if (!(age >= 0) || age > SESSION_BRIDGE_MS) return false;
    const s = saved.session && typeof saved.session === 'object' ? saved.session : null;
    if (!s) return false;
    session = { ...freshSession(), ...s };
    for (const k of ['startStack', 'currentStack', 'handsPlayed', 'handsVPIP', 'handsVPIPKnown',
      'netChips', 'biggestWin', 'biggestLoss', 'handsWon', 'outcomeKnownHands',
      'showdownWins', 'scoreEst', 'startTime', 'pendingNet', 'capacityHint', 'rebuys']) {
      session[k] = Number.isFinite(Number(session[k])) ? Number(session[k]) : 0;
    }
    session.startTime = session.startTime > 0 ? session.startTime : Date.now();
    session.stackKnown = session.stackKnown === true;
    session.stackDeltaKnown = session.stackDeltaKnown === true;
    session.lastHandHeroWon = session.lastHandHeroWon === true;
    session.heroAwayAt = 0;
    session.zeroRiseAt = 0;
    session.wasAway = false;
    session.zeroStreak = 0;
    session.recentDeltas = Array.isArray(session.recentDeltas) ? session.recentDeltas.slice(-40) : [];
    session.netSeries = Array.isArray(session.netSeries)
      ? session.netSeries
        .filter(p => p && Number.isFinite(Number(p.net)))
        .map(p => ({ h: Number(p.h) || 0, net: Number(p.net) }))
        .slice(-400)
      : [];
    if (Array.isArray(saved.handKeys)) {
      recordedSessionHandKeys = new Set(saved.handKeys.filter(k => typeof k === 'string').slice(-120));
    }
    if (Array.isArray(saved.seenAwards)) {
      seenAwardLines = new Set(saved.seenAwards.filter(l => typeof l === 'string').slice(-12));
    }
    if (typeof saved.lastAwardSignature === 'string') lastAwardSignature = saved.lastAwardSignature;
    if (typeof saved.lastHoleKey === 'string') lastHoleKey = saved.lastHoleKey;
    if (typeof saved.lastHandSig === 'string') handTracker.lastHandSig = saved.lastHandSig;
    if (Array.isArray(saved.processedSigs)) {
      handTracker.processedMsgs = new Set(saved.processedSigs.filter(x => typeof x === 'string').slice(-12));
    }
    if (Array.isArray(saved.fallbackSigs)) {
      handTracker.fallbackSigs = new Set(saved.fallbackSigs.filter(x => typeof x === 'string').slice(-12));
    } else {
      handTracker.fallbackSigs = new Set();
    }
    tinfo(`[TNP] Session restored from before the ${age < 5000 ? 'reload' : 'page load'} `
      + `(${session.handsPlayed} hand${session.handsPlayed === 1 ? '' : 's'} on record, `
      + `${Math.round(age / 1000)}s ago).`);

    if (saved.table && typeof saved.table === 'object' && typeof saved.table.name === 'string') {
      pendingSessionTableCtx = saved.table;
      try { adoptSessionTableCtx(saved.table); } catch {  }
    }
    return true;
  };
  try {
    bootSessionRestored = restoreSavedSession(readJsonSegment(SESSION_KEY, null)) === true;
  } catch {  }

  const isTornPDA = () => {
    if (/TornPDA|Torn PDA/i.test(navigator.userAgent)) return true;

    if (window.flutter_inappwebview && typeof window.flutter_inappwebview.callHandler === 'function') return true;

    if (typeof window.PDA_httpGet === 'function') return true;

    return !!document.querySelector('[class*="mobileTable"], [class*="pdaTable"], [data-mobile="true"]');
  };
  const _pdaCache = { val: null, checkedAt: 0 };
  const isMobile = () => {

    const now = Date.now();
    if (_pdaCache.val === null || (!_pdaCache.val && now - _pdaCache.checkedAt < 30000)) {
      _pdaCache.val = isTornPDA();
      _pdaCache.checkedAt = now;
    }
    return _pdaCache.val === true;
  };

  const activity = {
    documentVisible: typeof document !== 'undefined' && document.visibilityState === 'visible',
    windowFocused: typeof document !== 'undefined' && (typeof document.hasFocus !== 'function' || document.hasFocus()),
    lastTrustedAt: 0,
    pdaKnown: false,
    pdaActive: true,
    pdaWebViewVisible: true
  };
  const TRUSTED_INTERACTION_MS = 10 * 60 * 1000;
  let pauseOverlayShown = false;

  const isPdaBridgeAvailable = () => (
    typeof window !== 'undefined'
    && !!window.flutter_inappwebview
    && typeof window.flutter_inappwebview.callHandler === 'function'
  );

  const isTableObservationAllowed = () => (
    runtimeActive
    && isHoldemSurface()
    && activity.documentVisible
    && activity.windowFocused !== false
    && (!activity.pdaKnown || (activity.pdaActive && activity.pdaWebViewVisible))
    && activity.lastTrustedAt > 0
    && (Date.now() - activity.lastTrustedAt) <= TRUSTED_INTERACTION_MS
  );

  const haltObservation = () => {
    mcJobId++;
    computeQueued = false;
    prevHeroTurn = false;
  };

  const pauseMessage = () => {
    if (!activity.documentVisible) return 'Paused: the page is hidden.';
    if (activity.windowFocused === false) return 'Paused: this window lost focus.';
    if (activity.pdaKnown && !activity.pdaActive) return 'Paused: switch back to this tab.';
    if (activity.pdaKnown && !activity.pdaWebViewVisible) return 'Paused: bring the table into view.';
    if (!(activity.lastTrustedAt > 0)) return 'Paused: click or tap the table once so live reading can begin.';
    if ((Date.now() - activity.lastTrustedAt) > TRUSTED_INTERACTION_MS) return 'Paused: no recent interaction. Click the table to resume.';
    return 'Paused: open and focus the table to resume.';
  };

  const applyPauseState = () => {
    const allowed = isTableObservationAllowed();
    if (!allowed && !pauseOverlayShown) {
      pauseOverlayShown = true;
    } else if (allowed && pauseOverlayShown) {
      pauseOverlayShown = false;
    }
    const overlay = document.getElementById('tnp-pause-overlay');
    if (overlay) {
      if (!allowed) {
        const msgEl = overlay.querySelector('#tnp-pause-msg');
        if (msgEl) setText(msgEl, pauseMessage());
        overlay.classList.remove('tnp-hidden');
      } else {
        overlay.classList.add('tnp-hidden');
      }
    }
    const bodyContent = document.getElementById('tnp-body-content');
    if (bodyContent) bodyContent.classList.toggle('tnp-paused', !allowed);
    const banner = document.getElementById('tnp-action-banner');
    if (banner) banner.setAttribute('aria-live', allowed ? 'polite' : 'off');
    if (!allowed) setHudStatus('paused');
    else if (hudStatus === 'paused') setHudStatus('ready');
    return allowed;
  };

  const applyPdaTabState = (state = {}) => {
    if (typeof state.isActiveTab !== 'boolean' || typeof state.isWebViewVisible !== 'boolean') return;
    activity.pdaKnown = true;
    activity.pdaActive = state.isActiveTab;
    activity.pdaWebViewVisible = state.isWebViewVisible;
    if (!isTableObservationAllowed()) {
      haltObservation();
      applyPauseState();
      return;
    }
    applyPauseState();
    void computeState();
  };

  let visibilityHandler = null;
  let tabStateHandler = null;
  let focusHandler = null;
  let blurHandler = null;
  let trustedHandler = null;
  let activityGuardsInstalled = false;

  const installActivityGuards = () => {
    if (activityGuardsInstalled) return;
    activityGuardsInstalled = true;

    visibilityHandler = () => {
      activity.documentVisible = document.visibilityState === 'visible';
      if (!isTableObservationAllowed()) {
        haltObservation();
        applyPauseState();
        flushAllSaves('visibility-hidden');
        return;
      }
      applyPauseState();
      void computeState();
    };
    document.addEventListener('visibilitychange', visibilityHandler);

    focusHandler = () => {
      activity.windowFocused = true;
      if (!isTableObservationAllowed()) { applyPauseState(); return; }
      applyPauseState();
      void computeState();
    };
    blurHandler = () => {
      activity.windowFocused = false;
      haltObservation();
      applyPauseState();
      flushAllSaves('window-blur');
    };
    window.addEventListener('focus', focusHandler);
    window.addEventListener('blur', blurHandler);

    trustedHandler = (e) => {
      if (e && e.isTrusted === false) return;
      activity.lastTrustedAt = Date.now();
    };
    for (const type of ['pointerdown', 'mousedown', 'keydown', 'touchstart']) {
      try { document.addEventListener(type, trustedHandler, { passive: true, capture: true }); } catch (e) { }
    }

    tabStateHandler = (event) => applyPdaTabState(event?.detail ?? {});
    window.addEventListener('tornpda:tabState', tabStateHandler);

    if (isPdaBridgeAvailable()) {
      try {
        Promise.resolve(
          window.flutter_inappwebview.callHandler('PDA_getTabState')
        ).then(applyPdaTabState).catch(() => {  });
      } catch {  }
    }

    window.addEventListener('pagehide', pageHideFlushHandler);
  };

  const pageHideFlushHandler = () => flushAllSaves('pagehide');

  const uninstallActivityGuards = () => {
    if (visibilityHandler) { document.removeEventListener('visibilitychange', visibilityHandler); visibilityHandler = null; }
    if (tabStateHandler) { window.removeEventListener('tornpda:tabState', tabStateHandler); tabStateHandler = null; }
    if (focusHandler) { window.removeEventListener('focus', focusHandler); focusHandler = null; }
    if (blurHandler) { window.removeEventListener('blur', blurHandler); blurHandler = null; }
    if (trustedHandler) {
      for (const type of ['pointerdown', 'mousedown', 'keydown', 'touchstart']) {
        try { document.removeEventListener(type, trustedHandler, { capture: true }); } catch (e) { }
      }
      trustedHandler = null;
    }
    window.removeEventListener('pagehide', pageHideFlushHandler);
    activityGuardsInstalled = false;
  };

  const HUD_STATUS = {
    ready:          { label: 'Ready',       color: 'var(--tnp-success)',  detail: 'Table detected, waiting for cards.' },
    live:           { label: 'Live',        color: 'var(--tnp-accent-2)', detail: 'Reading the table.' },
    computing:      { label: 'Computing',   color: 'var(--tnp-accent-text)', detail: 'Estimating equity.' },
    paused:         { label: 'Paused',      color: 'var(--tnp-amber)',    detail: 'Table hidden or not focused.' },
    'parser-issue': { label: 'Read issue',  color: 'var(--tnp-danger)',   detail: 'Table markup unreadable; advice stays off until it reads clean.' },
    folded:         { label: 'Folded',      color: 'var(--tnp-muted)',    detail: 'You folded; no equity this hand.' }
  };
  let hudStatus = 'ready';
  let hudStatusDetail = '';
  const domHealthBroken = () => Object.keys(domHealth).some(k => domHealth[k].warned);
  const setHudStatus = (state, detail = '') => {
    if (!HUD_STATUS[state]) state = 'ready';

    if (hudStatus === 'parser-issue' && state !== 'parser-issue' && state !== 'paused'
      && domHealthBroken()) return;
    if (hudStatus === state && hudStatusDetail === detail) return;
    hudStatus = state;
    hudStatusDetail = detail;
    renderStatusChip();

    renderActionBanner();
  };
  const renderStatusChip = () => {
    const chip = document.getElementById('tnp-status-chip');
    if (!chip) return;
    const def = HUD_STATUS[hudStatus];
    setText(chip, def.label);
    chip.style.color = def.color;
    chip.title = hudStatusDetail || def.detail;
  };

  const isElementVisible = (el) => {
    if (!el) return false;
    if (el.offsetParent === null && el.tagName !== 'BODY') return false;
    const style = window.getComputedStyle(el);
    return style.display !== 'none'
      && style.visibility !== 'hidden'
      && parseFloat(style.opacity) >= 0.1
      && !el.disabled
      && el.getAttribute('aria-hidden') !== 'true';
  };

  const getClassString = (el) => typeof el.className === 'string' ? el.className : '';
  const classContains = (el, substring) => getClassString(el).toLowerCase().includes(substring.toLowerCase());

  const SELECTORS = {
    pokerRoot: [

      '[class*="holdemWrapper"]',
      '[class*="tContainer___"]',
      '[class*="tableWrap___"]',
      '[data-game="holdem"]',
      '[data-table="poker"]',
      '[class*="holdem"]',
      '[class*="pokerTable"]',
      '[class*="pokerGame"]',
      '[class*="communityCards"]',
      '[class*="playerMeGateway___"]',
      '[class*="actionLog"]',
      '[data-zone="board"]'
    ],
    ownSeatMarker: [

      '[class*="self___"]',
      '[class*="selfPlayer"]',
      '[class*="playerMe"]',
      '[class*="myPlayer"]',
      '[class*="hero"]',
      '[data-self="true"]',
      '[data-is-me="true"]',
      '[class*="playerMeGateway___"]'
    ],

    actionLog: [

      '[aria-label="Game log"]',
      '[class*="messagesList"]',
      '[class*="logListContainer"]',
      '[class*="message___"]',
      '[class*="messagesWrap"]',
      '[class*="actionLog"]',
      '[class*="handHistory"]',
      '[class*="gameHistory"]',
      '[class*="log___"]',
      '[class*="logContent"]',
      '[class*="eventLog"]',
      '[class*="logContainer"]',
      '[class*="log"]',
      '[class*="chatLog"]',
      '[class*="gameLog"]',
      '[class*="handLog"]',
      '[class*="history"]',
      '[class*="messages___"]',
      '[class*="chatBox"]'
    ],
    board: [

      '[class*="communityCards"] [role="img"][aria-label]',
      '[class*="communityCards"] [class*="card"], [class*="communityCards"] [class*="front"] > div[role="img"], [class*="communityCards"] [class*="front___"] > div',
      '[class*="communityCards"] [class*="cardFace"], [class*="communityCards"] [data-card]',
      '[class*="board"] [class*="card"], [class*="tableCards"] [class*="card"], ' +
        '[class*="community"] [class*="card"], [class*="sharedCards"] [class*="card"], ' +
        '[class*="boardCards"] [class*="card"], [class*="flop"] [class*="card"], ' +
        '[class*="turn"] [class*="card"], [class*="river"] [class*="card"], ' +
        '[class*="boardArea"] [class*="card"], [class*="centerCards"] [class*="card"], ' +
        '[class*="publicCards"] [class*="card"], [data-zone="board"] [class*="card"]',
      '[class*="board"] [class*="front___"] > div, [class*="tableCards"] [class*="front___"] > div, ' +
        '[class*="community"] [class*="front___"] > div, [class*="sharedCards"] [class*="front___"] > div'
    ]
  };

  const selectorStats = {};

          const LOG_FEED_CONTAINER_SEL = '[aria-label="Game log"], [class*="messagesList"], [class*="logListContainer"], [class*="messageWrap"], [class*="messagesWrap"], [class*="chatLog"], [class*="chatBox"], [class*="logs___"]';
  const insideLogFeed = (el) => {
    try { return !!(el && typeof el.closest === 'function' && el.closest(LOG_FEED_CONTAINER_SEL)); }
    catch { return false; }
  };

  const recordSelectorHit = (feature, index) => {
    const s = selectorStats[feature] ??= { hits: [], lastHitIndex: -1, lastHitAt: 0 };
    s.hits[index] = (s.hits[index] ?? 0) + 1;
    s.lastHitIndex = index;
    s.lastHitAt = Date.now();
  };
  const recordSelectorMiss = (feature) => {
    const s = selectorStats[feature] ??= { hits: [], lastHitIndex: -1, lastHitAt: 0 };
    s.lastHitAt = 0;
  };
  const selectorConfidence = (feature, primaryHits) => {
    const s = selectorStats[feature];
    if (!s) return primaryHits > 0 ? 1 : 0;
    const total = s.hits.reduce((a, b) => a + (b ?? 0), 0);
    if (total === 0) return 0;
    const primary = s.hits[0] ?? 0;
    return Math.round((primary / total) * 100) / 100;
  };
  const buildParserReport = () => Object.keys(SELECTORS).map((feature) => {
    const s = selectorStats[feature];
    return {
      feature,
      candidates: SELECTORS[feature].length,
      primaryWins: s?.hits[0] ?? 0,
      totalHits: s ? s.hits.reduce((a, b) => a + (b ?? 0), 0) : 0,
      lastWinnerIndex: s?.lastHitIndex ?? -1,
      confidence: selectorConfidence(feature, 0)
    };
  });

  const HEAL_VOLATILE_TOKEN_RE = /^(?:active|default|folded|winner|enter|exit|enteractive|exitactive|current|old|won|state|thinking|disabled|selected|hover|focus|open|closed|visible|hidden|pressed|checked|highlighted|loading|moving|animat)/i;
  const stripVolatileClasses = (cls) => String(cls ?? '')
    .split(/\s+/).filter(Boolean)
    .filter((t) => !HEAL_VOLATILE_TOKEN_RE.test(t.replace(/___.*$/, '')))
    .join(' ');
  const cleanHealText = (s) => String(s ?? '')
    .replace(/[\t]/g, ' ').replace(/[\n\r]/g, '').replace(/ +/g, ' ').trim().slice(0, 64);

  const fingerprintOf = (el) => {
    try {
      const ownText = cleanHealText(
        Array.from(el.childNodes ?? [])
          .filter((n) => n.nodeType === 3)
          .map((n) => n.textContent).join(' ')
      );
      const attrs = {};
      for (const a of el.attributes ?? []) {
        const v = String(a.value ?? '').trim();
        if (v) attrs[a.name] = a.name === 'class' ? stripVolatileClasses(v) : v;
      }
      const path = [];
      for (let n = el; n && n.nodeType === 1 && path.length < 8; n = n.parentElement)
        path.unshift(n.tagName.toLowerCase());
      const p = el.parentElement;
      return {
        tag: el.tagName.toLowerCase(),
        text: ownText || null,
        attrs,
        path,
        parentTag: p ? p.tagName.toLowerCase() : null,
        parentClass: p ? stripVolatileClasses(getClassString(p)) : null,
        siblingTags: p ? Array.from(p.children).filter((c) => c !== el).map((c) => c.tagName.toLowerCase()) : [],
        childTags: Array.from(el.children ?? []).map((c) => c.tagName.toLowerCase())
      };
    } catch { return null; }
  };

  const simRatio = (a, b) => {
    if (!a && !b) return 1;
    if (!a || !b) return 0;
    if (a === b) return 1;
    const A = String(a), B = String(b);

    if (A.length > 256 || B.length > 256) return A === B ? 1 : 0.3;
    const mins = A.length <= B.length ? A : B, maxs = A.length <= B.length ? B : A;
    let prev = new Uint16Array(mins.length + 1);
    for (let i = 1; i <= maxs.length; i++) {
      const cur = new Uint16Array(mins.length + 1);
      const ch = maxs[i - 1];
      for (let j = 1; j <= mins.length; j++)
        cur[j] = ch === mins[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
      prev = cur;
    }
    return (2 * prev[mins.length]) / (A.length + B.length);
  };

  const fingerprintSimilarity = (a, b) => {
    if (!a || !b) return 0;
    let score = 0, checks = 0;
    score += a.tag === b.tag ? 1 : 0; checks++;
    if (a.text) { score += simRatio(a.text, b.text || ''); checks++; }
    const aKeys = Object.keys(a.attrs ?? {}).sort().join('\u0001');
    const bKeys = Object.keys(b.attrs ?? {}).sort().join('\u0001');
    score += 0.5 * simRatio(aKeys, bKeys) + 0.5 * simRatio(
      Object.values(a.attrs ?? {}).sort().join('\u0001'),
      Object.values(b.attrs ?? {}).sort().join('\u0001'));
    checks++;
    for (const attr of ['class', 'id', 'data-name', 'aria-label']) {
      if (a.attrs?.[attr]) { score += simRatio(a.attrs[attr], b.attrs?.[attr] ?? ''); checks++; }
    }
    score += simRatio((a.path ?? []).join('/'), (b.path ?? []).join('/')); checks++;
    if (a.parentTag && b.parentTag) {
      score += a.parentTag === b.parentTag ? 1 : 0; checks++;
      score += simRatio(a.parentClass ?? '', b.parentClass ?? ''); checks++;
    }
    if (a.siblingTags?.length) {
      score += simRatio(a.siblingTags.join(','), (b.siblingTags ?? []).join(',')); checks++;
    }
    if (a.childTags?.length) {
      score += simRatio(a.childTags.join(','), (b.childTags ?? []).join(',')); checks++;
    }
    return checks ? score / checks : 0;
  };

  let healStore = { features: {} };
  try {
    const savedHeal = readJsonSegment(STORAGE_KEYS.heal, {});
    if (savedHeal && typeof savedHeal === 'object' && typeof savedHeal.features === 'object')
      healStore = { features: savedHeal.features };
  } catch {  }
  const healTelemetry = { attempts: 0, heals: 0, rejections: 0, lastHealAt: 0, lastFeature: '' };
  const serializeHeal = () => {
    const json = JSON.stringify(healStore);
    return [STORAGE_KEYS.heal, json];
  };
  registerPersist('heal', () => serializeHeal());
  const healSaveQueued = () => { try { queueSave('heal'); } catch {  } };
  const healLastAttempt = {};
  const HEAL_RETRY_MS = 15000;
  const HEAL_THRESHOLD = 0.42;
  const HEAL_MAX_FEATURES = 40;

  const healRemember = (feature, el) => {
    if (!el || el.closest?.('#tnp-dossier')) return;
    const fp = fingerprintOf(el);
    if (!fp) return;
    const prev = healStore.features[feature];
    healStore.features[feature] = { fp, savedAt: Date.now(), heals: prev?.heals ?? 0 };
    const keys = Object.keys(healStore.features);
    if (keys.length > HEAL_MAX_FEATURES) {
      keys.sort((x, y) => healStore.features[x].savedAt - healStore.features[y].savedAt)
        .slice(0, keys.length - HEAL_MAX_FEATURES)
        .forEach((k) => { delete healStore.features[k]; });
    }
    healSaveQueued();
  };

  const healLocate = (feature, rootEl) => {
    const entry = healStore.features[feature];
    if (!entry?.fp) return [];
    const now = Date.now();
    if (now - (healLastAttempt[feature] ?? 0) < HEAL_RETRY_MS) return [];
    healLastAttempt[feature] = now;
    healTelemetry.attempts++;
    healTelemetry.lastFeature = feature;
    const scope = rootEl && rootEl.querySelectorAll ? rootEl : document.body;
    if (!scope) return [];
    let best = 0; const buckets = new Map();
    try {
      const all = scope.querySelectorAll('*');
      for (const el of all) {
        if (el.closest?.('#tnp-dossier')) continue;
        const s = fingerprintSimilarity(entry.fp, fingerprintOf(el));
        if (s < best) continue;
        if (s > best) { best = s; buckets.clear(); }
        if (buckets.size < 8) buckets.set(el, s);
      }
    } catch {  }
    if (best < HEAL_THRESHOLD) { healTelemetry.rejections++; return []; }
    healTelemetry.heals++;
    healTelemetry.lastHealAt = Date.now();
    const healed = Array.from(buckets.keys());
    healTelemetry.lastResult = {
      feature,
      best: Math.round(best * 1000) / 1000,
      count: buckets.size,
      sample: healed[0] ? String(healed[0].textContent ?? '').replace(/\s+/g, ' ').slice(0, 50) : null,
      tag: healed[0] ? healed[0].tagName : null,
      cls: healed[0] ? String(healed[0].className ?? '').slice(0, 60) : null
    };

    const lead = healed[0];
    healStore.features[feature] = { fp: fingerprintOf(lead), savedAt: Date.now(), heals: (entry.heals ?? 0) + 1 };
    healSaveQueued();
    tinfo(`[TNP] Healed anchor "${feature}" at ${(best * 100).toFixed(0)}% similarity after a selector miss.`);
    return healed;
  };

  const SUIT_LOOKUP = { hearts: '♥', diamonds: '♦', spades: '♠', clubs: '♣', heart: '♥', diamond: '♦', spade: '♠', club: '♣', h: '♥', d: '♦', s: '♠', c: '♣' };
  const RANK_WORDS = { 'two':'2', 'three':'3', 'four':'4', 'five':'5', 'six':'6', 'seven':'7', 'eight':'8', 'nine':'9', 'ten':'T', 'jack':'J', 'queen':'Q', 'king':'K', 'ace':'A' };

  const parseCardFromText = (text) => {
    if (!text) return null;
    const lower = text.toLowerCase().trim();

    const m = lower.match(/(10|[2-9]|two|three|four|five|six|seven|eight|nine|ten|jack|queen|king|ace)\s+of\s+(hearts?|diamonds?|spades?|clubs?)/i);
    if (m) {
      const rank = m[1] === '10' || m[1] === 'ten' ? 'T' : (RANK_WORDS[m[1]] ?? m[1]).toUpperCase();
      const suit = SUIT_LOOKUP[m[2].toLowerCase().replace(/s$/, '')];
      if (rank && suit) return `${rank}${suit}`;
    }

    const short = lower.match(/^([2-9TJQKA])([hdsc])$/i);
    if (short) return `${short[1].toUpperCase()}${SUIT_LOOKUP[short[2]]}`;
    return null;
  };

  const CARD_TEXT_RE = /\b(10|two|three|four|five|six|seven|eight|nine|ten|jack|queen|king|ace|[2-9])\s+of\s+(hearts?|diamonds?|spades?|clubs?)\b/gi;
  const extractCardStrings = (el) => {
    if (!el) return [];
    const out = [];
    const seen = new Set();
    const aria = el.getAttribute('aria-label') ?? '';
    CARD_TEXT_RE.lastIndex = 0;
    let m;
    while ((m = CARD_TEXT_RE.exec(aria)) !== null) {
      const c = parseCardFromText(m[0]);
      if (c && !seen.has(c)) { seen.add(c); out.push(c); }
    }
    if (out.length) return out.slice(0, 2);
    const single = extractCardString(el);
    return single ? [single] : [];
  };

  const extractCardString = (el) => {
    if (!el) return null;
    const cls = getClassString(el);
    const aria = el.getAttribute('aria-label') ?? '';
    const combined = `${cls} ${aria}`;

    for (const token of (el.classList ?? [])) {
      const m = token.match(/^(hearts|diamonds|spades|clubs)-(10|[2-9]|[TJQKA])(?:___|$)/i);
      if (m) {
        const rank = m[2] === '10' ? 'T' : m[2].toUpperCase();
        const suit = SUIT_LOOKUP[m[1].toLowerCase()];
        return `${rank}${suit}`;
      }
    }

    const textCard = parseCardFromText(aria);
    if (textCard) return textCard;

    const titleCard = parseCardFromText(el.getAttribute('title') ?? '');
    if (titleCard) return titleCard;

    const dataRank = el.getAttribute('data-rank') ?? el.getAttribute('data-card-rank');
    const dataSuit = el.getAttribute('data-suit') ?? el.getAttribute('data-card-suit');
    if (dataRank && dataSuit) {
      const r = dataRank.toUpperCase().replace('10', 'T');
      const s = SUIT_LOOKUP[dataSuit.toLowerCase().replace(/s$/, '')];
      if (r && s) return `${r}${s}`;
    }

    let suit = null;
    if (/heart|♥/i.test(combined)) suit = '♥';
    else if (/diamond|♦/i.test(combined)) suit = '♦';
    else if (/spade|♠/i.test(combined)) suit = '♠';
    else if (/club|♣/i.test(combined)) suit = '♣';

    let rank = null;
    if (/\b(ten|10)\b/i.test(combined) || /(?:^|[_-])10(?:[_\-]|$)/.test(cls)) rank = 'T';
    else if (/\bace\b/i.test(combined) || (/(?:^|[_-])a(?:[_\\-]|$)/.test(cls) && !/all|action/i.test(cls))) rank = 'A';
    else if (/\bking\b/i.test(combined) || /(?:^|[_-])k(?:[_\\-]|$)/.test(cls)) rank = 'K';
    else if (/\bqueen\b/i.test(combined) || /(?:^|[_-])q(?:[_\\-]|$)/.test(cls)) rank = 'Q';
    else if (/\bjack\b/i.test(combined) || (/(?:^|[_-])j(?:[_\\-]|$)/.test(cls) && !/jackpot/i.test(cls))) rank = 'J';
    else {
      const ariaMatch = aria.match(/\b([2-9]|two|three|four|five|six|seven|eight|nine)\b/i);
      if (ariaMatch) {
        rank = RANK_WORDS[ariaMatch[1].toLowerCase()] ?? ariaMatch[1];
      } else {
        const clsMatch = cls.match(/(?:^|[_\\-])([2-9])(?:[_\\-]|$)/);
        if (clsMatch) rank = clsMatch[1];
      }
    }

    return (rank && suit) ? `${rank}${suit}` : null;
  };

  const hasSeatStateClass = (el) => {
    if (!el || !el.classList) return false;
    for (const token of el.classList) {
      if (/^(?:opponent|self)___/i.test(token)) return true;
    }
    return false;
  };

  const dedupeByPlayerId = (seats) => {
    const byPlayerId = new Map();
    const oneSeatPerPlayer = [];
    for (const el of seats) {
      const pid = el.id && /^player-/i.test(el.id) ? el.id : null;
      if (!pid) { oneSeatPerPlayer.push(el); continue; }
      const kept = byPlayerId.get(pid);
      if (!kept) { byPlayerId.set(pid, el); oneSeatPerPlayer.push(el); continue; }
      const keptHasIndex = seatPositionIndex(kept) !== null;
      const elHasIndex = seatPositionIndex(el) !== null;
      if (elHasIndex && !keptHasIndex) {
        oneSeatPerPlayer[oneSeatPerPlayer.indexOf(kept)] = el;
        byPlayerId.set(pid, el);
      }
    }
    return oneSeatPerPlayer;
  };

  const scanAllSeats = () => {
    const candidates = [];
    let scope = document;
    try {
      const root = document.querySelector(
        '[class*="holdemWrapper"], [class*="tContainer___"], [class*="tableWrap___"], ' +
        '[data-game="holdem"], [data-table="poker"], [class*="pokerTable"], [class*="pokerGame"], ' +
        '[class*="communityCards"], [class*="playerMeGateway___"]'
      );
      if (root) scope = root;
    } catch { }

    candidates.push(...scope.querySelectorAll('[class*="opponent"], [class*="self___"]'));

    candidates.push(...scope.querySelectorAll('[id^="player-"]'));
    candidates.push(...scope.querySelectorAll(
      '[class*="playerWrapper"], [class*="seat"], [class*="playerSeat"], ' +
      '[class*="seatContainer"], [class*="playerSlot"], [class*="tableSeat"], ' +
      '[class*="pokerSeat"], [data-seat]'
    ));

    if (candidates.length === 0) {

      try {
        const healedSeats = healLocate('seats', document.body);
        if (healedSeats.length) candidates.push(...healedSeats);
      } catch {  }
    }

    if (candidates.length === 0) {

      candidates.push(...Array.from(document.querySelectorAll(
        '[class*="player"]:not([class*="playerCount"]):not([class*="playersOnline"])'
      )).filter(el =>
        !el.closest?.('[class*="playerMeGateway"], [class*="betPanel"], [class*="betOptions"], [class*="panelPositioner"]')
        && seatHasPlayerFurniture(el)));
    }

    const arr = Array.from(new Set(candidates)).filter(el =>

      !el.closest('#tnp-dossier') && !/tnp-/i.test(getClassString(el))
      && !insideLogFeed(el)
      && !insideChatMessageRow(el));

    const stateClassSeats = arr.filter(hasSeatStateClass);

    if (stateClassSeats.length > 0) {
      const deduped = stateClassSeats.filter(a =>
        !stateClassSeats.some(b => b !== a && a.contains(b))
      );
      if (deduped.length > 0) return dedupeByPlayerId(deduped);
    }

    const filtered = arr.filter(a => !arr.some(b => b !== a && a.contains(b)));
    const outer = filtered.length > 0 ? filtered : arr;

    const seen = new Set();
    const out = [];
    for (const el of outer) {
      if (seen.has(el)) continue;
      const nameEls = Array.from(el.querySelectorAll('[class*="name"], [class*="playerName"], .name'))
        .filter(n => !n.closest('#tnp-dossier') && !/tnp-/i.test(getClassString(n)))
        .filter(n => !insideLogFeed(n) && !insideChatMessageRow(n));
      if (nameEls.length >= 2) {
        for (const n of nameEls) {
          const seatEl = n.parentElement ?? n;
          if (!seen.has(seatEl)) { seen.add(seatEl); out.push(seatEl); }
        }
        continue;
      }
      seen.add(el);
      out.push(el);
    }
    const seatsFinal = dedupeByPlayerId(out);
    if (seatsFinal.length) {
      const anchorSeat = seatsFinal.find((s) => /^player-\d+$/.test(s.id || '')) ?? seatsFinal[0];
      healRemember('seats', anchorSeat);
    }
    return seatsFinal;
  };

  let _seatsScanCache = { at: 0, seats: null };
  const getAllSeats = () => {
    const now = Date.now();
    if (_seatsScanCache.seats && now - _seatsScanCache.at <= 250) return _seatsScanCache.seats;
    const seats = scanAllSeats();
    _seatsScanCache = { at: now, seats };
    return seats;
  };

  const SEAT_FURNITURE_SEL =
    'a[href*="profiles.php"], [class*="playerName"], [class*="userName"], ' +
    '[class*="displayName"], [class*="nick"], [data-name], [data-xid], [data-player-id], ' +
    '[class*="stack"], [class*="chips"], [class*="cash"], [class*="balance"], ' +
    '[class*="chipCount"], [class*="chipStack"], [class*="playerChips"], ' +
    '[class*="amount"], [class*="value"], [class*="money"], [class*="bankroll"], ' +
    '[class*="avatar"], [class*="timer"], [class*="holeCard"], [class*="playingCard"], ' +
    '[class*="folded"], [class*="sittingOut"], [class*="vacant"]';

  const seatHasPlayerFurniture = (seat) => {
    try { return !!seat.querySelector(SEAT_FURNITURE_SEL); }
    catch { return false; }
  };

  const getPlayerName = (seat) => {
    if (!seat) return null;
    if (insideLogFeed(seat)) return null;
    if (insideChatMessageRow(seat)) return null;

    let tornUid = null;
    try {
      const seatIdEl = /^player-\d+$/.test(seat.id || '')
        ? seat
        : seat.querySelector('[id^="player-"]');
      tornUid = seatIdEl?.id?.match(/^player-(\d+)$/)?.[1] ?? null;
    } catch {  }

    const seatPlayerId = (name) => (tornUid
      ? { id: `xid:${tornUid}`, name }
      : { id: `name:${name}`, name });
    const profileLink = seat.querySelector('a[href*="profiles.php"]');
    if (profileLink) {
      const xidMatch = profileLink.href.match(/XID=(\d+)/i);
      const name = profileLink.textContent.trim();

      if (xidMatch && isPlausiblePlayerName(name)) return { id: `xid:${xidMatch[1]}`, name };
      if (name && isPlausiblePlayerName(name)) return seatPlayerId(name);
    }

    if (isMobile()) {
      const pdaLink = seat.querySelector('a[href*="XID"], a[data-xid], [data-player-id], [data-xid]');
      if (pdaLink) {
        const xid = pdaLink.getAttribute('data-xid') || pdaLink.getAttribute('data-player-id')
          || (pdaLink.href?.match(/XID=(\d+)/i)?.[1]);
        const name = pdaLink.getAttribute('data-player-name') || pdaLink.textContent.trim();
        if (xid && isPlausiblePlayerName(name || `Player ${xid}`)) return { id: `xid:${xid}`, name: name || `Player ${xid}` };
        if (name && isPlausiblePlayerName(name)) return seatPlayerId(name);
      }

      const pdaNameEl = seat.querySelector(
        '[class*="playerName"], [class*="userName"], [class*="displayName"], ' +
        '[class*="nick"], [data-name]'
      );
      if (pdaNameEl) {
        const name = pdaNameEl.getAttribute('data-name') || pdaNameEl.textContent.trim();
        if (name && name.length > 1 && name.length < 30 && isPlausiblePlayerName(name)) return seatPlayerId(name);
      }
    }

    const nameEl = seat.querySelector('[class*="name"], [class*="playerName"], .name');
    if (nameEl) {
      const name = nameEl.textContent.trim();
      if (name && name.length > 1 && name.length < 30 && isPlausiblePlayerName(name)) {
        return seatPlayerId(name);
      }
    }
    const text = (seat.textContent ?? '').trim().split('\n')[0].trim();
    if (text && text.length > 1 && text.length < 30
      && seatHasPlayerFurniture(seat) && isPlausiblePlayerName(text)) {
      return seatPlayerId(text);
    }

    let anc = seat.parentElement, hops = 0;
    while (anc && hops < 3 && !anc.closest('#tnp-dossier') && !insideLogFeed(anc)) {
      const cands = anc.querySelectorAll('[class*="name"], [class*="playerName"], .name');
      if (cands.length === 1) {
        const name = cands[0].textContent.trim();
        if (name && name.length > 1 && name.length < 30 && isPlausiblePlayerName(name)) {
          return seatPlayerId(name);
        }
      }
      if (cands.length > 1) break;
      anc = anc.parentElement;
      hops++;
    }
    return null;
  };

  const isSeatContainer = (el) => {

    if (!el) return false;
    const seats = getAllSeats();
    let n = 0;
    for (const s of seats) {
      if (s !== el && el.contains(s) && ++n >= 2) return true;
    }
    return false;
  };

  const findOwnSeatScan = () => {

    mySeat = null;

                    try {
      if (!cachedPageHeroIdentity) cachedPageHeroIdentity = heroIdentityFromPage();
      const heroHint = cachedHeroIdentity || cachedPageHeroIdentity;
      const hintXid = heroXidOf(heroHint)
        ?? (() => {
          try {
            const wsHeroId = TNP6?.live?.heroId;
            return (wsHeroId !== null && wsHeroId !== undefined) ? String(wsHeroId) : null;
          } catch (e) { return null; }
        })();
      if (hintXid) {
        const byId = document.getElementById('player-' + hintXid);
        if (byId && !byId.closest('#tnp-dossier') && !insideLogFeed(byId) && !insideChatMessageRow(byId)) {
          mySeat = byId;
          return mySeat;
        }
      }
    } catch {  }

    const SEAT_ANCESTOR_SEL =
      '[id^="player-"], [class*="playerWrapper"], [class*="seat"], ' +
      '[class*="playerSeat"], [class*="seatContainer"], [class*="playerSlot"], ' +
      '[class*="tableSeat"], [class*="pokerSeat"], [data-seat], ' +
      '[class*="playerMeGateway___"], [class*="opponent"], [class*="self___"]';

    let meMarker = null;
    for (let i = 0; i < SELECTORS.ownSeatMarker.length; i++) {

      const matches = document.querySelectorAll(SELECTORS.ownSeatMarker[i]);
      for (const m of matches) {
        if (m.closest?.('#tnp-dossier')) continue;
        if (insideLogFeed(m)) continue;
        if (/(?:opponent|self)___/i.test(getClassString(m)) && !hasSeatStateClass(m)) continue;
        meMarker = m;
        break;
      }
      if (meMarker) { recordSelectorHit('ownSeatMarker', i); break; }
    }
    if (!meMarker) recordSelectorMiss('ownSeatMarker');

    if (meMarker) {

      const markerIsSeat = hasSeatStateClass(meMarker)
        || /^player-/i.test(meMarker.id ?? '');
      const direct = meMarker.closest(SEAT_ANCESTOR_SEL);
      if (direct && direct !== meMarker && !isSeatContainer(direct)) {
        mySeat = direct;
        return mySeat;
      }
      if (markerIsSeat && !isSeatContainer(meMarker)) {

        if (meMarker.id) {
          const mirror = getAllSeats().find(s =>
            s !== meMarker && s.id === meMarker.id
            && !s.contains(meMarker) && !meMarker.contains(s));
          if (mirror) { mySeat = mirror; return mySeat; }
        }
        mySeat = meMarker;
        return mySeat;
      }

      for (const seat of getAllSeats()) {
        if (seat === meMarker || seat.contains(meMarker)) {
          mySeat = seat;
          return mySeat;
        }
      }

      mySeat = null;
      return mySeat;
    }

    const allHands = document.querySelectorAll('[class*="hand___"], [class*="hand"], [class*="holeCards"]');
    const visibleSeats = [];
    const cleaned = getAllSeats();
    for (const hand of allHands) {
      if (hand.closest('[class*="communityCards"]')) continue;
      const faceUp = hand.querySelector('[role="img"]:not([aria-label*="face down"])');
      if (faceUp && extractCardString(faceUp)) {
        let seat = cleaned.find(s => s === hand || s.contains(hand));
        if (!seat) seat = hand.closest(SEAT_ANCESTOR_SEL) ?? hand.parentElement ?? hand;
        if (!visibleSeats.includes(seat)) visibleSeats.push(seat);
      }
    }
    if (visibleSeats.length === 1) mySeat = visibleSeats[0];
    return mySeat;
  };

        let _ownSeatCache = { at: 0, seat: null, has: false };
  const findOwnSeat = () => {
    const now = Date.now();
    if (_ownSeatCache.has && now - _ownSeatCache.at <= 250) {
      mySeat = _ownSeatCache.seat;
      return _ownSeatCache.seat;
    }
    const seat = findOwnSeatScan();
    _ownSeatCache = { at: now, seat, has: true };
    return seat;
  };

  let cachedHeroIdentity = null;
  let cachedPageHeroIdentity = null;
        const heroIdentityFromPage = () => {
    try {
      const sidebar = document.querySelector('.sidebar, [class*="sidebar"]');
      const scopes = sidebar ? [sidebar, document] : [document];
      for (const scope of scopes) {
        const links = scope.querySelectorAll('a[href*="profiles.php?XID="]');
        for (const link of links) {
          if (link.closest('#tnp-dossier')) continue;
          if (link.closest('[class*="opponent"], [class*="self___"], [class*="playerWrapper"], [aria-label="Game log"], [class*="logListContainer"], [class*="messagesList"], [class*="message___"], [class*="messageWrap"], [class*="chatBox"]')) continue;
          if (insideChatMessageRow(link)) continue;
          const name = (link.textContent ?? '').trim();
          const xid = String(link.getAttribute('href') ?? '').match(/XID=(\d+)/i)?.[1];
          if (name && isPlausiblePlayerName(name)) {
            return { id: xid ? `xid:${xid}` : `name:${name}`, name, xid: xid || null };
          }
        }
      }
    } catch {  }
    return null;
  };
  const heroXidOf = (hero) => {
    if (!hero) return null;
    if (hero.xid) return String(hero.xid);
    const id = String(hero.id ?? '');
    return id.startsWith('xid:') ? id.slice(4) : null;
  };

  const getHeroIdentity = () => {
    const heroSeat = findOwnSeat();
    const fromSeat = heroSeat ? getPlayerName(heroSeat) : null;
    if (fromSeat) { cachedHeroIdentity = fromSeat; return fromSeat; }

    if (cachedHeroIdentity) return cachedHeroIdentity;
    const fromPage = heroIdentityFromPage();
    if (fromPage) { cachedHeroIdentity = fromPage; }
    return fromPage;
  };

          const isOwnPlayerSeat = (seat, me = null) => {
    if (!seat) return false;
    if (me && (seat === me || seat.contains(me) || me.contains(seat))) return true;
    let hero = cachedHeroIdentity || null;
    if (seat.id && /^player-\d+$/i.test(seat.id)) {
      if (!hero) hero = heroIdentityFromPage();
      if (!hero) {
        try {
          const wsHeroId = TNP6?.live?.heroId;
          if (wsHeroId !== null && wsHeroId !== undefined) hero = { id: `xid:${wsHeroId}`, name: '' };
        } catch (e) { }
      }
      const heroXid = heroXidOf(hero);
      if (heroXid && seat.id === 'player-' + heroXid) return true;
    }
    const player = getPlayerName(seat);
    if (!player) return false;
    if (!hero) hero = cachedHeroIdentity || getHeroIdentity();
    if (!hero) return false;
    return player.id === hero.id || (!!hero.name && samePlayer(player.name, hero.name));
  };

  const seatTextOf = (seat) => (seat.textContent ?? '')
    .replace(/(\d)([A-Za-z])/g, '$1 $2')
    .replace(/([A-Za-z])(\d)/g, '$1 $2')
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .toLowerCase();

  const isSeatEmpty = (seat) => {
    const seatText = seatTextOf(seat);
    return /\b(?:take\s*(?:a\s+)?seat|join\s*(?:the\s+)?(?:table|game)?|vacant|open\s*seat|empty|sit\s*down)\b/i.test(seatText);
  };

  const isSeatFolded = (seat) => {
    if (seat.querySelector('[class*="folded"]')) return true;
    if (classContains(seat, 'folded')) return true;
    const allEls = seat.querySelectorAll('*');
    for (const el of allEls) {
      if (/folded/i.test(getClassString(el))) return true;
    }

    try {
      const op = parseFloat(window.getComputedStyle(seat).opacity);
      if (op > 0 && op <= 0.2) return true;
    } catch {  }
    return false;
  };

  const seatHasCards = (seat) => {
    const cards = seat.querySelectorAll(
      '[class*="hand___"], [class*="card"], [class*="Card"], [class*="cardFace"], [class*="cardBack"], ' +
      '[class*="holeCard"], [class*="handCard"], [class*="playingCard"], ' +
      '[class*="front___"], [class*="back___"], [data-card], [data-card-id], ' +
      '[role="img"][aria-label*="card" i], [role="img"][aria-label*="face down" i], ' +
      '[role="img"][aria-label*="back" i]'
    );
    for (const card of cards) {
      if (card.closest('[class*="communityCards"]')) continue;
      const cls = getClassString(card);
      if (/\b(empty|placeholder|slot|nocard|blank)\b/i.test(cls)) continue;
      return true;
    }
    return false;
  };

  const isSeatSittingOut = (seat) => {
    const t = seatTextOf(seat);
    return /\b(sitting\s*out|sat\s*out|away|waiting|not\s*in\s*hand)\b/i.test(t);
  };

  const SEAT_PLAYER_PATTERN   = /(?:opponent|self)___/i;
  const SEAT_INACTIVE_PATTERN = /(?:folded|sittingOut|away|waiting|vacant|empty)___/i;

  const isSeatInHand = (seat) => {
    if (!seat) return false;

    let el = seat, hops = 0;
    while (el && el.nodeType === 1 && hops < 5) {
      const cls = getClassString(el);
      if (SEAT_PLAYER_PATTERN.test(cls)) {

        return !SEAT_INACTIVE_PATTERN.test(cls);
      }
      el = el.parentElement;
      hops++;
    }

    return seatHasCards(seat);
  };

  const isOpponentActive = (seat) => {
    if (!seat) return false;
    if (isSeatEmpty(seat)) return false;
    if (isSeatSittingOut(seat)) return false;
    if (!isSeatInHand(seat)) return false;
    if (isSeatFolded(seat)) return false;
    return true;
  };

  const countActiveOpponents = () => {

    const seats = getAllSeats();
    const me = findOwnSeat();
    let count = 0;
    let dbg = { self: 0, empty: 0, sittingOut: 0, notInHand: 0, folded: 0 };
    for (const seat of seats) {
      if (isOwnPlayerSeat(seat, me)) { dbg.self++; continue; }
      if (isSeatEmpty(seat))        { dbg.empty++; continue; }
      if (isSeatSittingOut(seat))    { dbg.sittingOut++; continue; }
      if (!isSeatInHand(seat))      { dbg.notInHand++; continue; }
      if (isSeatFolded(seat))        { dbg.folded++; continue; }
      count++;
    }

    if (count === 0 && seats.length >= 2) {
      tdebug(`[TNP] countActiveOpponents=0 (seats=${seats.length} me=${me ? 'found' : 'null'} skip=${JSON.stringify(dbg)} mobile=${isMobile()})`);
    }
    return count;
  };

  const isCardVisible = (el) => {
    if (!el) return false;
    const aria = el.getAttribute('aria-label') ?? '';
    const cls = getClassString(el);
    if (/face\s*down|back|hidden|placeholder|empty|blank|slot/i.test(aria)) return false;
    if (/(?:^|[\s_\-])(back|hidden|facedown|empty|placeholder|blank|nocard)(?:[_\-]|$)/i.test(cls)) return false;

    const style = window.getComputedStyle(el);
    if (parseFloat(style.opacity) < 0.3) return false;
    if (style.display === 'none' || style.visibility === 'hidden') return false;
    return true;
  };

  const parseHoleCards = () => {


    const dataScope = document.querySelector('[data-player-cards]');
    const gateway = dataScope || document.querySelector('[class*="playerMeGateway___"]');
    if (gateway) {
      const cards = [];
      const faces = gateway.querySelectorAll('[class*="front___"] > div[role="img"], [class*="front___"] > div, [class*="cardFace"] > div, [class*="cardFace___"] > div');
      for (const el of faces) {
        if (el.closest?.('[class*="opponent"], [class*="playerPositioner"], [class*="communityCards"]')) continue;
        if (!isCardVisible(el)) continue;
        for (const card of extractCardStrings(el)) {
          if (!cards.includes(card)) cards.push(card);
        }
      }
      const distinct = [...new Set(cards)];
      if (distinct.length === 2) return distinct.slice(0, 2);
    }

    const seat = findOwnSeat();
    if (!seat) return [];
    const cardEls = seat.querySelectorAll(
      '[class*="card"], [class*="cardWrapper"] [role="img"], [class*="front"] > div[role="img"], ' +
      '[class*="holeCard"], [class*="hole-card"], [class*="handCard"], ' +
      '[class*="playerCard"], [data-card], [class*="cardFace"]'
    );
    const cards = [];
    const seen = new Set();
    for (const el of cardEls) {
      if (el.closest?.('[class*="communityCards"], [class*="board"], [class*="tableCards"]')) continue;
      if (!isCardVisible(el)) continue;
      for (const card of extractCardStrings(el)) {
        if (card && !seen.has(card)) {
          seen.add(card);
          cards.push(card);
        }
      }
    }
    const distinct = [...new Set(cards)];
    if (distinct.length !== 2) return [];
    return distinct.slice(0, 2);
  };

  const parseBoardCards = () => {

    const cards = [];
    const SUIT_MAP = { hearts: '♥', diamonds: '♦', spades: '♠', clubs: '♣' };

    const dataRoot = document.querySelector('[data-board-cards]');
    let els = [];
    if (dataRoot) {
      els = Array.from(dataRoot.querySelectorAll('div[role="img"][aria-label], [class*="card"]'))
        .filter(el => el.getAttribute('aria-hidden') !== 'true');
      if (els.length) recordSelectorHit('board', 0);
    }
    if (els.length === 0) {
      for (let i = 0; i < SELECTORS.board.length; i++) {
        const found = document.querySelectorAll(SELECTORS.board[i]);
        if (found.length > 0) {
          els = Array.from(found);
          recordSelectorHit('board', i + 1);
          break;
        }
      }
    }
    if (els.length === 0) recordSelectorMiss('board');

    if (els.length === 0) {
      const allCards = document.querySelectorAll(
        '[class*="card"], [role="img"][aria-label*=" of "], [class*="front"] > div[role="img"], ' +
        '[class*="cardFace"], [data-card]'
      );
      const valid = [];
      for (const c of allCards) {
        if (c.closest('#tnp-dossier')) continue;
        if (c.closest('[class*="opponent"], [id^="player-"], [class*="playerWrapper"], [class*="seat"], [class*="playerSeat"], [class*="handCard"], [class*="holeCard"], [class*="playerMeGateway"]')) continue;
        valid.push(c);
      }
      els = valid;
    }

    const seen = new Set();
    for (const el of els) {
      if (!isCardVisible(el)) continue;
      let card = null;
      for (const token of (el.classList ?? [])) {
        const m = token.match(/^(hearts|diamonds|spades|clubs)-(10|[2-9]|[TJQKA])(?:___|$)/i);
        if (m) {
          const rank = m[2] === '10' ? 'T' : m[2].toUpperCase();
          card = rank + SUIT_MAP[m[1].toLowerCase()];
          break;
        }
      }
      if (!card) card = extractCardString(el);
      if (card && !seen.has(card)) {
        seen.add(card);
        cards.push(card);
      }
      if (cards.length >= 5) break;
    }
    return cards;
  };

  const isPreActionButton = (buttonText) => {
    const normalized = buttonText.trim().toLowerCase();
    if (/\//.test(normalized)) return true;
    return /^(call\s+any|auto|pre-?action|fold\s+to\s+any|fold\s+any|check\s+to|sit\s+out|stand\s+up|leave\s+table|rebuy|add\s+chips)/i.test(normalized)
      || /\b(pre-?action|auto-?post|auto-?muck)\b/i.test(normalized);
  };

  const classifyButtonAction = (text) => {
    const lower = text.trim().toLowerCase();
    if (/^fold\b/.test(lower)) return 'fold';
    if (/^check\b/.test(lower)) return 'check';
    if (/^call\b/.test(lower)) return 'call';
    if (/^(raise|bet)\b/.test(lower)) return 'raise';
    if (/^all[- ]?in\b/.test(lower)) return 'raise';
    return null;
  };

  const scanActiveActionButtons = () => {
    const buttons = {
      fold: null, foldText: '', check: null, checkText: '',
      call: null, callText: '', raise: null, raiseText: '',
      hasFold: false, hasCheck: false, hasCall: false, hasRaise: false
    };
    const scoped = document.querySelectorAll('[class*="buttonsWrap"] button, [class*="buttonsWrap"] [role="button"]');
    const allButtons = scoped.length ? scoped : document.querySelectorAll('button, [role="button"]');
    const candidates = [];
    for (const b of allButtons) {
      if (!isElementVisible(b)) continue;
      if (b.closest('#tnp-dossier')) continue;
      if (/(?:^|\s)(?:queueable|queued)___/i.test(getClassString(b))) continue;
      if (b.closest('[class*="opponent"], [id^="player-"], [class*="playerWrapper"], [class*="playerStatus"], [class*="lastAction"], [class*="actionLog"], [class*="preAction"], [class*="pre-action"]')) continue;
      const fullText = (b.textContent ?? '').trim();
      if (!fullText) continue;
      const actionType = classifyButtonAction(fullText);
      if (!actionType) continue;
      if (isPreActionButton(fullText)) continue;
      const rect = b.getBoundingClientRect();
      candidates.push({ element: b, text: fullText, actionType, y: rect.top, hasDollar: /\$/.test(fullText) });
    }
    if (candidates.length === 0) return buttons;

    const anchor = candidates.find(b => b.hasDollar);
    let actionRow;
    if (anchor) {
      actionRow = candidates.filter(b => Math.abs(b.y - anchor.y) < 50);
    } else {
      candidates.sort((a, b) => b.y - a.y);
      const lowestY = candidates[0].y;
      actionRow = candidates.filter(b => Math.abs(b.y - lowestY) < 50);
      if (!actionRow.some(b => b.actionType === 'fold')) return buttons;
    }

    const distinctActions = new Set(actionRow.map(b => b.actionType)).size;
    if (distinctActions < 2 && !isHoldemSurface()) return buttons;

    for (const { element, text, actionType } of actionRow) {
      if (actionType === 'fold' && !buttons.hasFold) {
        buttons.fold = element; buttons.foldText = text; buttons.hasFold = true;
      } else if (actionType === 'check' && !buttons.hasCheck) {
        buttons.check = element; buttons.checkText = text; buttons.hasCheck = true;
      } else if (actionType === 'call' && !buttons.hasCall) {
        buttons.call = element; buttons.callText = text; buttons.hasCall = true;
      } else if (actionType === 'raise' && !buttons.hasRaise) {
        buttons.raise = element; buttons.raiseText = text; buttons.hasRaise = true;
      }
    }
    return buttons;
  };

  let _actionButtonsCache = { at: 0, buttons: null };
  const getActiveActionButtons = () => {
    const now = Date.now();
    if (_actionButtonsCache.buttons && now - _actionButtonsCache.at <= 250) return _actionButtonsCache.buttons;
    const buttons = scanActiveActionButtons();
    _actionButtonsCache = { at: now, buttons };
    return buttons;
  };

  const heroTurnFromStatus = () => {
    try {
      for (const el of document.querySelectorAll('[class*="statusWrapper"] [class*="status___"], [class*="status___"]')) {
        if (el.closest?.('#tnp-dossier')) continue;
        const t = (el.textContent || '').trim();
        if (/^your\s+turn/i.test(t)) return true;
        if (/is\s+thinking/i.test(t)) return false;
      }
    } catch { }
    return null;
  };
  const isHeroTurn = () => {
    const st = heroTurnFromStatus();
    if (st !== null) return st;
    const btns = getActiveActionButtons();
    return btns.hasFold || btns.hasCheck || btns.hasCall || btns.hasRaise;
  };

  const MAX_REASONABLE_STACK = 1e13;
  const isPlausibleStack = (v) => v > 0 && v <= MAX_REASONABLE_STACK;

  const isPlausibleDelta = (delta, prev) => {
    if (delta === 0) return false;
    if (prev <= 0) return isPlausibleStack(Math.abs(delta));
    if (Math.abs(delta) > MAX_REASONABLE_STACK) return false;
    if (Math.abs(delta) > prev * 1000) return false;
    return true;
  };

  const hasHeroFolded = (seat) => {
    if (!seat) return false;
    if (isSeatFolded(seat)) return true;
    const statusEls = seat.querySelectorAll('[class*="status"], [class*="state"], [class*="playerStatus"], [class*="action"], [class*="lastAction"], [class*="move"], [class*="tag"]');
    for (const el of statusEls) {
      const text = (el.textContent ?? '').trim();
      if (/\b(folded|mucked|timed\s+out)\b/i.test(text)) return true;
    }
    return false;
  };

  const parseTornNumber = (value) => {
    const raw = String(value ?? '').trim();
    if (!raw) return 0;

    const suffix = raw.match(/([kmbtp])\s*$/i)?.[1]?.toLowerCase() ?? '';
    const multiplier = suffix === 'k' ? 1e3 : suffix === 'm' ? 1e6 : suffix === 'b' ? 1e9
      : suffix === 't' ? 1e12 : suffix === 'p' ? 1e15 : 1;
    const numericText = raw
      .replace(/\u00a0/g, ' ')
      .replace(/,/g, '')
      .replace(/[kmbtp]\s*$/i, '')
      .replace(/[^0-9.]/g, '');
    if (!numericText || (numericText.match(/\./g) || []).length > 1) return 0;
    const numericValue = Number(numericText);
    return Number.isFinite(numericValue) ? Math.floor(numericValue * multiplier) : 0;
  };

  const parseNonNegativeDecimal = (value, fallback = 0) => {
    const text = String(value ?? '').replace(/,/g, '').trim();

    if (!text) return fallback;
    const numericValue = Number(text);
    return Number.isFinite(numericValue) && numericValue >= 0 ? numericValue : fallback;
  };

  const normalizeBankrollState = (state) => {
    const source = state && typeof state === 'object' ? state : {};
    const history = Array.isArray(source.history) ? source.history.map((entry) => ({
      ...entry,

      net: Number.isFinite(Number(String(entry?.net ?? '').replace(/,/g, '')))
        ? Number(String(entry?.net ?? '').replace(/,/g, ''))
        : 0,
      hands: parseNonNegativeDecimal(entry?.hands, 0),
      won: parseNonNegativeDecimal(entry?.won, 0),
      mins: parseNonNegativeDecimal(entry?.mins, 0)
    })) : [];
    return {
      ...source,
      total: parseTornNumber(source.total),
      stopLossBuyIns: parseNonNegativeDecimal(source.stopLossBuyIns, 2),
      sessionGoal: parseTornNumber(source.sessionGoal),
      history
    };
  };
  bankroll = normalizeBankrollState(bankroll);

  if (Array.isArray(bankroll.history) && bankroll.history.length > 50) {
    bankroll.history = bankroll.history.slice(-50);
  }
  saveBankroll();

  const readToCall = () => {

    try {
      const actionBtns = getActiveActionButtons();
      if (actionBtns.hasCall) {
        const amountMatch = actionBtns.callText.match(/call\s*\$?\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)/i);
        if (amountMatch) {
          const value = parseTornNumber(amountMatch[1]);
          return value > 0 ? value : null;
        }
        return null;
      }
      if (actionBtns.hasFold && !actionBtns.hasCheck) return null;
    } catch {  }
    return 0;
  };

  const readPotCandidate = (el, source, weight) => {
    if (!el || el.closest?.('#tnp-dossier')) return null;
    if (el.matches?.('button, [role="button"]') || el.closest?.('button, [role="button"]')) return null;
    if (el.closest?.('[class*="slider"], [class*="betSize"], [class*="betControl"], [class*="potential"]')) return null;
    const cls = getClassString(el);
    if (/potential|potion|depot|spot/i.test(cls)) return null;
    const dataValue = ['data-pot', 'data-pot-size', 'data-pot-amount']
      .map(attr => el.getAttribute?.(attr))
      .find(Boolean) || '';
    const text = [dataValue, el.getAttribute?.('aria-label') || '', el.getAttribute?.('title') || '', el.textContent || '']
      .join(' ').replace(/\s+/g, ' ').trim();
    if (!text || text.length > 80) return null;
    const explicit = text.match(/\b(?:total\s+)?pot\b[^0-9$]*\$?\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)/i);
    const money = text.match(/\$\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)/i);
    const bare = !explicit && !money ? text.match(/^([\d,]+(?:[.]?\d+)?[kmbtp]?)$/i) : null;
    const match = explicit || money || bare;
    if (!match) return null;
    const value = parseTornNumber(match[1]);

    if (value <= 0 || value > ANCHORED_POT_MAX) return null;
    let score = weight;
    if (explicit) score += 50;
    if (dataValue) score += 35;
    if (/pot/i.test(cls)) score += 20;
    if (money) score += 12;
    if (text.length <= 24) score += 8;
    try {
      const style = window.getComputedStyle(el);
      if (style.display !== 'none' && style.visibility !== 'hidden' && parseFloat(style.opacity) >= 0.1) score += 8;
    } catch {  }
    return { value, score, source, text };
  };

  const collectPotCandidates = () => {
    const candidates = [];
    const seen = new Set();
    const add = (el, source, weight) => {
      if (!el || seen.has(el)) return;
      seen.add(el);
      const candidate = readPotCandidate(el, source, weight);
      if (candidate) candidates.push(candidate);
    };
    const named = [
      ['[class*="potSize"]', 'potSize', 50], ['[class*="totalPot"]', 'totalPot', 52],
      ['[class*="potAmount"]', 'potAmount', 50], ['[class*="potValue"]', 'potValue', 48],
      ['[class*="potTotal"]', 'potTotal', 52], ['[class*="mainPot"]', 'mainPot', 48],
      ['[class*="pot___"]', 'potModule', 42], ['[class*="potDisplay"]', 'potDisplay', 45],
      ['[class*="potInfo"]', 'potInfo', 44], ['[data-pot]', 'dataPot', 56],
      ['[data-pot-size]', 'dataPotSize', 56], ['[data-pot-amount]', 'dataPotAmount', 56],
      ['[class*="potContainer"]', 'pdaPotContainer', 42], ['[class*="potWrapper"]', 'pdaPotWrapper', 42],
      ['[class*="chipPot"]', 'pdaChipPot', 40], ['[class*="potBar"]', 'pdaPotBar', 38],
      ['[class*="potLabel"]', 'pdaPotLabel', 44]
    ];
    for (const [selector, source, weight] of named) document.querySelectorAll(selector).forEach(el => add(el, source, weight));
    document.querySelectorAll('[class*="pot"], [class*="potTotal"], [class*="betPot"], [class*="gamePot"], [class*="tablePot"]').forEach(el => add(el, 'genericPot', 20));
    if (isMobile()) document.querySelectorAll('[class*="gameInfo"], [class*="tableInfo"], [class*="tableStatus"], [class*="gameStatus"]').forEach(el => add(el, 'pdaInfo', 12));
    return candidates.sort((a, b) => b.score - a.score || a.text.length - b.text.length);
  };

  let lastPotSource = '';
  let lastGoodPot = 0;

  const tableStakesRead = { sb: 0, bb: 0, at: 0 };

  const ANCHORED_POT_MAX = 1e13;
  const SR_SUMMARY_RE = /(\d+)\s+players at table\.\s*Your stack:\s*\$([\d,]+)\.\s*Pot:\s*\$([\d,]+)/i;
  let _srSummaryCache = { at: 0, val: null };
  const readSrSummary = (force = false) => {
    const now = Date.now();
    if (!force && _srSummaryCache.val && now - _srSummaryCache.at <= 250) return _srSummaryCache.val;
    let val = null;
    try {
      for (const el of document.querySelectorAll('[class*="srOnly"]')) {
        if (el.closest?.('#tnp-dossier')) continue;
        const m = (el.textContent || '').match(SR_SUMMARY_RE);
        if (m) {
          val = { players: parseInt(m[1], 10), heroStack: parseTornNumber(m[2]), pot: parseTornNumber(m[3]) };
          break;
        }
      }
    } catch { }
    _srSummaryCache = { at: now, val };
    return val;
  };
  const readTotalPotAnchored = () => {
    try {
      const wraps = document.querySelectorAll('[class*="totalPotWrap"]');
      for (const wrap of wraps) {
        if (wrap.closest?.('#tnp-dossier')) continue;
        const text = (wrap.textContent ?? '')
          .replace(/\s+/g, ' ')
          .replace(/([$\d,.]) (?=[A-Za-z])/g, '$1 ')
          .replace(/([$,\d])(?=[A-Za-z])/g, '$1 ')
          .trim();
        if (!text || text.length > 160) continue;

        const potM = text.match(/\bPOT:?\s*\$?\s*([\d,]+(?:\.\d+)?)([kmbtp]\b)?(?!\d)/i);
        const blindM = text.match(/\bBLINDS:?\s*\$?\s*([\d,]+(?:\.\d+)?)([kmbtp]\b)?(?!\d)\s*\/\s*\$?\s*([\d,]+(?:\.\d+)?)([kmbtp]\b)?(?!\d)/i);
        if (blindM) {
          const sb = parseTornNumber(blindM[1] + (blindM[2] ?? ''));
          const bb = parseTornNumber(blindM[3] + (blindM[4] ?? ''));
          if (bb > 0) { tableStakesRead.sb = sb; tableStakesRead.bb = bb; tableStakesRead.at = Date.now(); }
        }
        if (potM) {
          const val = parseTornNumber(potM[1] + (potM[2] ?? ''));
          if (val > 0 && val <= ANCHORED_POT_MAX) {
            lastPotSource = 'totalPotWrap';
            healRemember('pot', wrap);
            return val;
          }
        }
      }
    } catch {  }
    return 0;
  };
  const readPot = () => {

    try {

      const anchored = readTotalPotAnchored();
      if (anchored > 0) return anchored;
      const srPot = readSrSummary();
      if (srPot && srPot.pot > 0) {
        lastPotSource = 'sr summary';
        return srPot.pot;
      }
      const ranked = collectPotCandidates();
      if (ranked.length) {
        const top = ranked[0], second = ranked[1];

        if (second && second.score >= top.score - 10 && second.value > top.value * 1.6) {
          lastPotSource = 'ambiguous';
          return 0;
        }
        lastPotSource = ranked[0].source;
        return ranked[0].value;
      }

      const healedPot = healLocate('pot', document.body);
      for (const el of healedPot.slice(0, 3)) {
        const cand = readPotCandidate(el, 'heal', 46);
        if (cand && cand.value > 0) {
          lastPotSource = 'heal';
          return cand.value;
        }
      }

    } catch {  }
    lastPotSource = '';
    return 0;
  };

  const parseStackCandidate = (text) => {
    const valueText = String(text ?? '').replace(/\s+/g, ' ').trim();
    if (!valueText || valueText.length > 80) return 0;
    const money = valueText.match(/\$\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)/i);
    const bare = !money ? valueText.match(/^([\d,]+(?:[.]?\d+)?[kmbtp]?)$/i) : null;
    return parseTornNumber((money || bare)?.[1] ?? '');
  };

  const crossCheckReads = ({ pot = 0, toCall = 0, bb = 0, board = [], hole = [], potAmbiguous = false }) => {
    const hard = [];
    const soft = [];
    if (potAmbiguous) soft.push('two pot reads disagree');

    if (pot > 0 && bb > 0 && pot < bb) soft.push('pot below the big blind (side pot or misread)');
    if (toCall > 0 && pot > 0 && toCall > pot) hard.push('call exceeds the pot');
    if (board.length > 5) hard.push('board shows more than five cards');
    if (hole.length === 2 && hole[0] === hole[1]) hard.push('duplicate hole cards');
    if (hole.length === 2 && board.some(c => hole.includes(c))) hard.push('hole cards duplicated on board');
    return { hard, soft };
  };

  const LOBBY_ROW_CAP = 30;
  const LOBBY_RESCAN_MS = 400;
  const JOIN_PENDING_MS = 3 * 60 * 1000;
  const IDENTITY_TTL_MS = 8 * 60 * 60 * 1000;
  const TABLE_CTX_KEY = 'tnp_table_ctx_v1';

  const parseLobbySpeed = (raw) => {
    const s = String(raw ?? '').trim().replace(/s$/i, '');
    if (/^\d{1,3}$/.test(s)) {
      const n = parseInt(s, 10);
      return (n >= 5 && n <= 600) ? n : null;
    }
    if (/^fast$/i.test(s)) return 15;
    if (/^slow$/i.test(s)) return 30;
    return null;
  };

  const LOBBY_ARIA_RE = /^(Join|Unavailable) table (.+?), small blind (.+?) big blind (.+?), speed ([^,]+), players (\d+) of (\d+)$/;
  const parseLobbyAria = (text) => {
    const s = String(text ?? '').replace(/\s+/g, ' ').trim();
    const m = s.match(LOBBY_ARIA_RE);
    if (!m) return null;
    const sb = parseTornNumber(m[3]);
    const bb = parseTornNumber(m[4]);
    const speed = parseLobbySpeed(m[5]);
    const players = parseInt(m[6], 10);
    const maxplayers = parseInt(m[7], 10);
    if (!(bb > 0) || !(maxplayers >= 2) || !(players >= 0) || players > maxplayers) return null;
    return { name: m[2].trim(), dulled: m[1] === 'Unavailable', sb, bb, speed, players, maxplayers };
  };

  const parseLobbyPlayersCell = (text) => {
    const m = String(text ?? '').replace(/\s+/g, '').match(/^(\d+)\/(\d+)$/);
    if (!m) return null;
    const players = parseInt(m[1], 10), maxplayers = parseInt(m[2], 10);
    if (!(maxplayers >= 2) || players > maxplayers) return null;
    return { players, maxplayers };
  };

  const hasLobbyRowToken = (el, re) => {
    if (!el || !el.classList) return false;
    for (const t of el.classList) if (re.test(t)) return true;
    return false;
  };

  let lastGoodLobbyTable = null;
  const LOBBY_HEADER_TOKENS = ['name', 'stakes', 'speed', 'players'];
  const lobbyHeaderScore = (heads) => {
    if (!Array.isArray(heads) || !heads.length) return 0;
    const hit = (tok) => heads.some((h) => h && String(h).includes(tok));
    return LOBBY_HEADER_TOKENS.reduce((n, tok) => n + (hit(tok) ? 1 : 0), 0) / LOBBY_HEADER_TOKENS.length;
  };
  const findLobbyTables = () => {
    const out = [];
    for (const table of document.querySelectorAll('table')) {
      if (table.closest('#tnp-dossier')) continue;

      if (!isElementVisible(table)) continue;
      const heads = Array.from(table.querySelectorAll('thead th'))
        .map((th) => (th.textContent ?? '').trim().toLowerCase());
      if (heads.length < 4) continue;
      if (heads[0] === 'name' && heads[1] === 'stakes' && heads[2] === 'speed' && heads[3] === 'players') {
        out.push(table);
      }
    }
    if (out.length) {
      lastGoodLobbyTable = out[0];
      return out.slice(0, 2);
    }

    let best = null, bestScore = 0;
    for (const table of document.querySelectorAll('table')) {
      if (table.closest?.('#tnp-dossier')) continue;
      if (!isElementVisible(table)) continue;
      const heads = Array.from(table.querySelectorAll('thead th'))
        .map((th) => (th.textContent ?? '').trim().toLowerCase());
      if (heads.length < 2) continue;
      let score = lobbyHeaderScore(heads);
      if (table === lastGoodLobbyTable) score = Math.min(1, score + 0.25);
      if (score > bestScore) { bestScore = score; best = table; }
    }
    if (best && bestScore >= 0.75) {
      lastGoodLobbyTable = best;
      return [best];
    }
    return [];
  };

  const parseLobbyRows = (table) => {
    const rows = [];
    const trs = table.querySelectorAll('tbody tr');
    const cap = Math.min(trs.length, LOBBY_ROW_CAP);
    for (let i = 0; i < cap; i++) {
      const tr = trs[i];
      if (tr.closest('#tnp-dossier')) continue;
      const tds = tr.querySelectorAll('td');
      if (tds.length < 4) continue;
      const btn = tds[0].querySelector('button');
      const row = {
        name: String((btn ?? tds[0]).textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 40),
        current: hasLobbyRowToken(tr, /^current(?:___|$)/),
        dulled: hasLobbyRowToken(tr, /^dulled(?:___|$)/) || btn?.getAttribute('aria-disabled') === 'true',
        sb: 0, bb: 0, speed: null, players: 0, maxplayers: 0
      };
      const aria = btn ? parseLobbyAria(btn.getAttribute('aria-label')) : null;
      const cell = parseLobbyPlayersCell(tds[3].textContent);
      if (aria) {
        row.sb = aria.sb; row.bb = aria.bb;
        row.speed = aria.speed;
        row.players = aria.players; row.maxplayers = aria.maxplayers;
        if (aria.dulled) row.dulled = true;
      } else if (cell) {
        row.players = cell.players; row.maxplayers = cell.maxplayers;
        const stake = String(tds[1].textContent ?? '').split('/');
        if (stake.length === 2) { row.sb = parseTornNumber(stake[0]); row.bb = parseTornNumber(stake[1]); }
      }
      if (row.name) rows.push(row);
    }
    return rows;
  };

  let lobbyRows = [];
  let lobbySignature = '';
  let lobbyScannedAt = 0;
  const scanLobby = (force = false) => {
    const now = Date.now();
    if (!force && now - lobbyScannedAt < LOBBY_RESCAN_MS) return lobbyRows;
    lobbyScannedAt = now;
    const rows = [];
    for (const t of findLobbyTables()) rows.push(...parseLobbyRows(t));
    const sig = rows.map((r) => `${r.current ? '>' : ''}${r.name}|${r.players}/${r.maxplayers}|${r.bb}`).join(';');
    if (sig !== lobbySignature) {
      lobbySignature = sig;
      lobbyRows = rows;
      applyLobbyRows(rows);
    }
    return rows;
  };

  const tableIdentityState = {
    mode: 'none',
    name: '', seats: 0, players: 0, speed: null,
    source: '',
    wsTableId: null,
    at: 0
  };
  let pendingJoin = null;
  let stakesMismatchCount = 0;

              const TABLE_ART_URL_RE = /\/casino\/holdem\/images\/(?:tables|tables_colour)\/[^/"']+\/[^/"']*?_([a-z0-9_]+)\.png/i;
  let _tableArtCache = { at: 0, slug: null };
  const readTableArtSlug = (force = false) => {
    const now = Date.now();
    if (!force && now - _tableArtCache.at < 10000) return _tableArtCache.slug;
    let slug = null;
    try {
      for (const el of document.querySelectorAll('[style*="holdem/images/tables"]')) {
        if (el.closest?.('#tnp-dossier')) continue;
        const m = String(el.getAttribute('style') || '').match(TABLE_ART_URL_RE);
        if (m) { slug = m[1].toLowerCase(); break; }
      }
      if (!slug) {
        const roots = document.querySelectorAll('[class*="holdemWrapper"], [class*="tContainer___"], [class*="tableWrap___"], [class*="communityCards"]');
        for (const root of roots) {
          if (!root || root.closest?.('#tnp-dossier')) continue;
          for (const el of root.querySelectorAll('div')) {
            const bg = window.getComputedStyle(el).backgroundImage;
            if (typeof bg === 'string' && bg.indexOf('holdem/images/table') !== -1) {
              const m = bg.match(TABLE_ART_URL_RE);
              if (m) { slug = m[1].toLowerCase(); break; }
            }
          }
          if (slug) break;
        }
      }
    } catch { }
    _tableArtCache = { at: now, slug };
    return slug;
  };
  const tableFromArtSlug = (slug) => {
    if (!slug) return null;
    const t = TABLE_BY_KEY.get(tableKeyOf(slug));
    return t ? { ...t } : null;
  };

  const confirmIdentity = (source, data) => {
    if (!data || typeof data.name !== 'string' || !data.name) return false;
    tableIdentityState.mode = 'confirmed';
    tableIdentityState.name = data.name.slice(0, 40);
    tableIdentityState.seats = (data.seats ?? data.maxplayers ?? 0) | 0;
    tableIdentityState.players = (data.players ?? 0) | 0;
    tableIdentityState.speed = Number.isFinite(data.speed) ? data.speed : null;
    tableIdentityState.source = source;
    tableIdentityState.at = Date.now();
    persistTableCtx();
    return true;
  };

  const dropTableIdentity = (why) => {
    tableIdentityState.mode = 'none';
    tableIdentityState.name = '';
    tableIdentityState.seats = 0;
    tableIdentityState.source = '';
    tableIdentityState.at = 0;
    stakesMismatchCount = 0;
    session.capacityHint = 0;
    _tableArtCache = { at: 0, slug: null };
    try { sessionStorage.removeItem(TABLE_CTX_KEY); } catch { }
    if (why) tinfo(`[TNP] Table identity dropped: ${why}`);
  };

  const applyLobbyRows = (rows) => {
    const current = rows.find((r) => r.current && r.name);
    if (current) {
      confirmIdentity('game list (current row)', current);
      if (tableStakesRead.bb === 0 && current.bb > 0) {
        tableStakesRead.sb = current.sb; tableStakesRead.bb = current.bb; tableStakesRead.at = Date.now();
      }
    }
    if (pendingJoin) {
      const match = rows.find((r) => r.name === pendingJoin.name);
      if (match) {
        pendingJoin.seats = match.maxplayers || pendingJoin.seats;
        pendingJoin.players = match.players || pendingJoin.players;
        pendingJoin.speed = match.speed ?? pendingJoin.speed;
        if (!pendingJoin.bb && match.bb) { pendingJoin.sb = match.sb; pendingJoin.bb = match.bb; }
      }
    }
  };

  const observeTableIdentity = () => {
    scanLobby();
    if (pendingJoin) {
      if (Date.now() - pendingJoin.at > JOIN_PENDING_MS) {
        pendingJoin = null;
      } else if (findOwnSeat()) {
        confirmIdentity('game list (join click)', pendingJoin);
        if (tableStakesRead.bb === 0 && pendingJoin.bb > 0) {
          tableStakesRead.sb = pendingJoin.sb; tableStakesRead.bb = pendingJoin.bb; tableStakesRead.at = Date.now();
        }
        pendingJoin = null;
      }
    }

                if (tableIdentityState.mode !== 'confirmed') {
      try {
        const slug = readTableArtSlug();
        if (slug) {
          const artTable = tableFromArtSlug(slug);
          if (artTable) {
            const stakesAgree = tableStakesRead.bb === 0
              || (Math.round(tableStakesRead.bb * 100) === artTable.bb
                && Math.round((tableStakesRead.sb || 0) * 100) === artTable.sb);
            if (stakesAgree) {
              confirmIdentity('table art', { name: artTable.name, seats: artTable.seats, speed: artTable.timer });
            } else if (tableStakesRead.bb > 0) {
              tdebug(`[TNP] Table art says "${artTable.name}" but live blinds read `
                + `$${tableStakesRead.sb.toLocaleString()}/$${tableStakesRead.bb.toLocaleString()}; not trusting the art (tournament themes reuse parent art).`);
            }
          }
        }
      } catch { }
    }

    try {
      if (tableIdentityState.wsTableId !== null) tableIdentityState.wsTableId = null;
    } catch { }

    if (tableIdentityState.mode === 'confirmed') {
      const cap = session.capacityHint | 0;
      const catSeats = (() => {
        const cat = TABLE_BY_KEY.get(tableKeyOf(tableIdentityState.name));
        return cat && cat.seats ? cat.seats : tableIdentityState.seats;
      })();
      if (cap > 0 && catSeats > 0 && cap > catSeats) {
        tinfo(`[TNP] Table identity dropped: a ${cap}-seat layout cannot be ${tableIdentityState.name} (${catSeats} seats). Re-deriving.`);
        dropTableIdentity();
        pendingJoin = null;
      }
    }

    if (tableIdentityState.mode === 'confirmed' && tableStakesRead.bb > 0) {
      const cat = TABLE_BY_KEY.get(tableKeyOf(tableIdentityState.name));
      if (cat) {
        const liveBB = Math.round(tableStakesRead.bb * 100);
        const liveSB = Math.round(tableStakesRead.sb * 100);
        if (cat.bb === liveBB && cat.sb === liveSB) {
          stakesMismatchCount = 0;
        } else if (++stakesMismatchCount >= 3) {

          tinfo(`[TNP] Table identity dropped: live stakes ${tableStakesRead.sb}/${tableStakesRead.bb} no longer match ${tableIdentityState.name}. Re-deriving.`);
          dropTableIdentity();
          pendingJoin = null;
        }
      }
    }
  };

  const persistTableCtx = () => {
    if (tableIdentityState.mode !== 'confirmed') return;
    try {
      sessionStorage.setItem(TABLE_CTX_KEY, JSON.stringify({
        name: tableIdentityState.name,
        seats: tableIdentityState.seats,
        speed: tableIdentityState.speed,
        source: tableIdentityState.source,
        wsTableId: tableIdentityState.wsTableId,
        at: tableIdentityState.at
      }));
    } catch { }
  };

  const restoreTableCtx = () => {
    try {
      const raw = sessionStorage.getItem(TABLE_CTX_KEY);
      if (!raw) return;
      const d = JSON.parse(raw);
      if (!d || typeof d.name !== 'string' || !d.name) return;

      const at = Number(d.at) || 0;
      if (at <= 0 || Date.now() - at > IDENTITY_TTL_MS) return;
      const wsId = Number(d.wsTableId);
      if (Number.isFinite(wsId) && wsId > 0) tableIdentityState.wsTableId = wsId;
      confirmIdentity(d.source || 'earlier in this tab', d);
    } catch { }
  };

  const adoptSessionTableCtx = (ctx) => {
    if (!ctx || typeof ctx.name !== 'string' || !ctx.name) return;
    if (tableIdentityState.mode === 'confirmed') return;
    const cap = session.capacityHint | 0;
    const ctxSeats = (ctx.seats ?? 0) | 0;
    if (cap > 0 && ctxSeats > 0 && ctxSeats < cap) {
      tdebug(`[TNP] Ignoring saved table context for ${ctx.name}: its ${ctxSeats} seats cannot host the ${cap}-seat layout seen now.`);
      return;
    }
    if (tableStakesRead.bb > 0) {
      const cat = TABLE_BY_KEY.get(tableKeyOf(ctx.name));
      if (cat && cat.bb != null && Math.round(tableStakesRead.bb * 100) !== cat.bb) {
        tdebug(`[TNP] Ignoring saved table context for ${ctx.name}: live big blind ${tableStakesRead.bb.toLocaleString()} disagrees with the catalog.`);
        return;
      }
    }
    confirmIdentity('session restore', ctx);
  };

  const onLobbyClick = (e) => {
    try {
      const t = e.target;
      if (!t || t.nodeType !== 1) return;
      if (t.closest?.('#tnp-dossier')) return;
      const row = t.closest?.('tbody tr');
      if (!row) return;
      const tableEl = row.closest?.('table');
      if (!tableEl) return;
      const heads = Array.from(tableEl.querySelectorAll('thead th'))
        .map((th) => (th.textContent ?? '').trim().toLowerCase());
      if (heads.length < 4 || heads[0] !== 'name' || heads[1] !== 'stakes') return;
      const tds = row.querySelectorAll('td');
      if (tds.length < 4) return;
      const btn = tds[0].querySelector('button');
      const aria = btn ? parseLobbyAria(btn.getAttribute('aria-label')) : null;
      if (aria?.dulled) return;
      const cell = parseLobbyPlayersCell(tds[3].textContent);
      const name = String((btn ?? tds[0]).textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 40);
      if (!name) return;
      const stake = String(tds[1].textContent ?? '').split('/');
      pendingJoin = {
        name,
        seats: (aria?.maxplayers || cell?.maxplayers || 0),
        players: (aria?.players ?? cell?.players ?? 0),
        speed: aria?.speed ?? null,
        sb: aria?.sb || (stake.length === 2 ? parseTornNumber(stake[0]) : 0),
        bb: aria?.bb || (stake.length === 2 ? parseTornNumber(stake[1]) : 0),
        at: Date.now()
      };
    } catch {  }
  };

  const resolveTableIdentity = () => {
    if (tableIdentityState.mode === 'confirmed' && tableIdentityState.name) {
      let t = TABLE_BY_KEY.get(tableKeyOf(tableIdentityState.name)) || null;
      if (!t) {

        t = identifyTable(tableStakesRead.sb || 0, tableStakesRead.bb || 0, {
          seats: tableIdentityState.seats, players: getAllSeats().length
        });
        if (!t) return null;
      }
      return { table: t, confidence: 'confirmed', sourceLabel: tableIdentityState.source, basisLine: '' };
    }
    const capacity = session.capacityHint | 0;
    const guess = identifyTable(tableStakesRead.sb, tableStakesRead.bb, {
      seats: capacity > 0 ? capacity : 0,
      players: getAllSeats().length,
      minSeats: capacity > 0 ? 0 : (session.capacityHint | 0)
    });
    if (!guess) return null;
    return { table: guess, confidence: guess.confidence, sourceLabel: '', basisLine: guess.basis.join('; ') };
  };

  const tableContextSnapshot = () => (tableIdentityState.mode === 'confirmed'
    ? { name: tableIdentityState.name, seats: tableIdentityState.seats, speed: tableIdentityState.speed, source: tableIdentityState.source, wsTableId: tableIdentityState.wsTableId, at: tableIdentityState.at }
    : null);

  const currentTableName = () => (tableIdentityState.mode === 'confirmed' ? tableIdentityState.name : '');

  const tableIdentityDebug = () => ({
    mode: tableIdentityState.mode,
    name: tableIdentityState.name || null,
    seats: tableIdentityState.seats || null,
    players: tableIdentityState.players || null,
    speed: tableIdentityState.speed ?? null,
    source: tableIdentityState.source || null,
    wsTableId: tableIdentityState.wsTableId ?? null,
    artSlug: readTableArtSlug() || null,
    age_s: tableIdentityState.at ? Math.round((Date.now() - tableIdentityState.at) / 1000) : null,
    pending_join: pendingJoin ? pendingJoin.name : null,
    lobby_rows: lobbyRows.length,
    lobby_signature: lobbySignature.slice(0, 80) || null,
    stakes: { sb: tableStakesRead.sb, bb: tableStakesRead.bb, age_s: tableStakesRead.at ? Math.round((Date.now() - tableStakesRead.at) / 1000) : null },
    capacity_hint: session.capacityHint || null,
    evidence: tableIdentityState.mode === 'confirmed'
      ? [
          `game-list row or table art: "${tableIdentityState.name}": maxplayers ${tableIdentityState.seats}, players ${tableIdentityState.players}${tableIdentityState.speed != null ? `, speed ${tableIdentityState.speed}s` : ''}`,
          `source: ${tableIdentityState.source}`
        ]
      : (tableStakesRead.bb > 0
        ? [`live BLINDS read: $${tableStakesRead.sb.toLocaleString()}/$${tableStakesRead.bb.toLocaleString()}`]
        : ['no identity evidence read yet']),
    limitations: tableIdentityState.mode === 'confirmed'
      ? ['cash tables never change blinds, so a confirmed name is dropped if the live stakes stop matching it for three consecutive ticks; a websocket channel change drops it immediately']
      : ['the seated view renders seats only for the players present, so a stakes-only read cannot separate same-stakes tables; the fallback names the smallest table that fits, labels it unconfirmed, and lists the rivals'],
    resolved: (() => { const r = resolveTableIdentity(); return r ? { name: r.table.name, confidence: r.confidence, alternates: r.table.alternates ?? [] } : null; })()
  });

  if (pendingSessionTableCtx?.name) adoptSessionTableCtx(pendingSessionTableCtx);
  restoreTableCtx();

  let lastStackDebugAt = 0;
  let lastStackDebugKey = '';
  const logStackDebug = (message, ...args) => {
    const key = `${message}|${args[0] ?? ''}`;
    const now = Date.now();
    if (key === lastStackDebugKey && now - lastStackDebugAt < 5000) return;
    lastStackDebugKey = key;
    lastStackDebugAt = now;
    tdebug(message, ...args);
  };

  const stackLabel = (el) => [
    getClassString(el), el.getAttribute('aria-label') ?? '', el.getAttribute('title') ?? '',
    el.getAttribute('data-value') ?? '', el.getAttribute('data-amount') ?? ''
  ].join(' ').toLowerCase();

  const stackCandidateScore = (el, text, fallback = false) => {
    const label = stackLabel(el);
    let score = fallback ? 0 : 40;
    if (/stack|chip/.test(label)) score += 100;
    if (/amount|value/.test(label)) score += 20;
    if (/data-stack|data-chips|data-amount|data-value/.test(label)) score += 40;

    if (/bankroll|wallet|account|net\s*worth/.test(label)
      && !/stack|chip/.test(label)) score -= 120;
    if (text.length <= 20) score += 5;
    return score;
  };

  let lastHeroStackZeroDisplayed = false;
  const ZERO_STACK_DISPLAY_RE = /^\$?\s*0(?:[.,]0{1,2})?\s*$/;
  const readHeroStack = (knownSeat = null, referenceStack = 0) => {

    lastHeroStackZeroDisplayed = false;
    try {
      const seat = knownSeat || findOwnSeat() || document.querySelector(
        '[class*="self___"], [data-self="true"], [data-is-me="true"], [class*="playerMeGateway___"]'
      );
      if (!seat) {
        logStackDebug('[TNP] readHeroStack: own seat/container returned null');
        return 0;
      }

      const candidates = [];
      const seen = new Set();
      const addCandidate = (el, fallback = false) => {
        if (!el || seen.has(el) || el.closest?.('#tnp-dossier')) return;

        if (el.closest?.('button, [role="button"], input, [class*="betPanel"], [class*="betOptions"], [class*="betInputWrap"], [class*="betSize"], [class*="betControl"], [class*="slider"], [class*="buttonsWrap"], [class*="panelTopRow"]')) return;

        if (el.closest?.('[class*="countDown"], [class*="timer"]')) return;

        if (el.closest?.('[class*="pot"]')) return;
        seen.add(el);
        const text = [
          el.textContent ?? '', el.getAttribute('aria-label') ?? '',
          el.getAttribute('title') ?? '', el.getAttribute('data-value') ?? '',
          el.getAttribute('data-amount') ?? ''
        ].join(' ').replace(/\s+/g, ' ').trim();
        const val = parseStackCandidate(text);
        if (val > 0 && isPlausibleStack(val)) {
          candidates.push({ el, val, text, order: candidates.length, score: stackCandidateScore(el, text, fallback) });
        } else if (val > 0) {
          logStackDebug(`[TNP] readHeroStack: rejected implausible $${val.toLocaleString()}`);
        }
      };

      const stackEls = seat.querySelectorAll(
        '[class*="stack"], [class*="chips"], [class*="balance"], [class*="cash"], ' +
        '[class*="chipCount"], [class*="playerChips"], [class*="chipStack"], ' +
        '[data-chips], [data-stack], [data-amount], [data-value], ' +
        '[aria-label*="stack" i], [aria-label*="chips" i], [title*="stack" i], ' +
        '[class*="money"], [class*="bankroll"], [class*="playerBalance"], ' +
        '[class*="chipAmount"], [class*="amount___"], [class*="value___"], [class*="total___"]'
      );
      stackEls.forEach(el => addCandidate(el));

      const textOfEl = (el) => [
        el.textContent ?? '', el.getAttribute('aria-label') ?? '',
        el.getAttribute('title') ?? '', el.getAttribute('data-value') ?? '',
        el.getAttribute('data-amount') ?? ''
      ].join(' ').replace(/\s+/g, ' ').trim();
      for (const el of stackEls) {
        if (!el || el.closest?.('#tnp-dossier')) continue;
        if (ZERO_STACK_DISPLAY_RE.test(textOfEl(el))) { lastHeroStackZeroDisplayed = true; break; }
      }

      if (!candidates.some(c => c.score >= 100)) {
        const allEls = seat.querySelectorAll('span, div, p, em, strong, b');
        for (const el of allEls) {
          if (el.children.length > 2) continue;
          if (!lastHeroStackZeroDisplayed
            && ZERO_STACK_DISPLAY_RE.test(textOfEl(el))
            && !el.closest?.('button, [role="button"], input, [class*="betPanel"], [class*="betOptions"], [class*="betInputWrap"], [class*="panelTopRow"]')) {
            lastHeroStackZeroDisplayed = true;
          }
          addCandidate(el, true);
        }
      }

      if (isMobile() && seat.parentElement) {
        const stackScope = seat.parentElement.parentElement || seat.parentElement;
        const sibEls = stackScope.querySelectorAll(
          '[class*="stack"], [class*="chips"], [class*="balance"], [class*="cash"], ' +
          '[data-chips], [data-stack], [data-amount], [aria-label*="stack" i], ' +
          '[aria-label*="chips" i], [title*="stack" i]'
        );
        sibEls.forEach(el => {
          if (el === seat || seat.contains(el) || el.contains(seat)) return;
          addCandidate(el);
        });
      }

      if (!candidates.length) {

        try {
          const srStack = readSrSummary();
          if (srStack && srStack.heroStack > 0 && isPlausibleStack(srStack.heroStack)) {
            logStackDebug('[TNP] readHeroStack: using the sr-only summary line', `$${srStack.heroStack}`);
            return srStack.heroStack;
          }
        } catch { }
        logStackDebug('[TNP] readHeroStack: seat found but no plausible stack value detected', getClassString(seat));
        return 0;
      }

      const reference = Number(referenceStack) > 0 ? Number(referenceStack) : 0;
      const referenceWindow = reference ? Math.max(250000, reference * 1000) : 0;
      const nearReference = reference
        ? candidates.filter(c => Math.abs(c.val - reference) <= referenceWindow)
        : [];

      const pool = reference ? nearReference : candidates;
      if (!pool.length) {
        logStackDebug(`[TNP] readHeroStack: no candidate near known stack $${reference.toLocaleString()}`);
        return 0;
      }
      pool.sort((a, b) => {
        if (b.score !== a.score) return b.score - a.score;
        if (reference) return Math.abs(a.val - reference) - Math.abs(b.val - reference);

        return (a.order ?? 0) - (b.order ?? 0);
      });
      return pool[0].val;
    } catch (err) {
      logStackDebug('[TNP] readHeroStack failed:', err?.message || err);
    }
    return 0;
  };

  const readOpponentStackFromSeat = (seat) => {
    try {
      if (!seat || seat.closest?.('#tnp-dossier')) return 0;
      const els = seat.querySelectorAll('[class*="stack"], [class*="chips"], [class*="balance"], [class*="money"], [class*="amount___"], [data-amount], [data-value]');
      for (const el of els) {
        if (el.closest?.('button, [role="button"], [class*="betPanel"], [class*="betInputWrap"], [class*="buttonsWrap"], [class*="slider"]')) continue;
        if (el.closest?.('[class*="pot"]')) continue;
        const text = [
          el.textContent ?? '', el.getAttribute('aria-label') ?? '', el.getAttribute('title') ?? ''
        ].join(' ').replace(/\s+/g, ' ').trim();
        const val = parseStackCandidate(text);
        if (val > 0 && isPlausibleStack(val)) return val;
      }
      return 0;
    } catch { return 0; }
  };

  const readBetInputFloorDom = () => {
    try {
      const input = document.querySelector('[class*="betInputWrap"] input, input[class*="betInput"], [class*="betPanel"] input');
      if (!input || !isElementVisible(input)) return 0;
      const min = parseTornNumber(input.getAttribute('min') || '');
      if (min > 0 && isPlausibleStack(min)) return min;
      const val = parseTornNumber(input.value || '');
      return (val > 0 && isPlausibleStack(val)) ? val : 0;
    } catch { return 0; }
  };

        const computeEffectiveStack = (heroStack) => {
    const hero = Number(heroStack) || 0;
    if (!(hero > 0)) return { eff: 0, source: 'none' };
    let eff = hero;
    let source = 'hero stack only';
    try {
      const me = findOwnSeat();
      const seats = me ? getAllSeats() : [];
      let opponents = 0;
      for (const seat of seats) {
        if (me && (seat === me || seat.contains(me) || me.contains(seat))) continue;
        if (!isOpponentActive(seat)) continue;
        const oppStack = readOpponentStackFromSeat(seat);
        if (oppStack > 0) {
          opponents++;
          eff = Math.min(eff, oppStack);
        }
      }
      if (opponents > 0) source = `min(you, ${opponents} active seat stacks)`;
    } catch { }
    return { eff, source };
  };

  let sessionAwardSeenAt = 0;

  const netStackTransition = (prev, read, opts = {}) => {
    const heroExpected = opts.heroExpected !== false;
    const heroWonSinceZero = opts.heroWonSinceZero === true;
    const zeroRiseAgeMs = Number.isFinite(opts.zeroRiseAgeMs) ? opts.zeroRiseAgeMs : Infinity;
    const afterAway = opts.afterAway === true;
    const zeroStreak = Number.isFinite(opts.zeroStreak) ? Math.max(1, Math.floor(opts.zeroStreak)) : 1;
    const zeroBustThreshold = Number.isFinite(opts.zeroBustThreshold) ? Math.max(1, Math.floor(opts.zeroBustThreshold)) : 1;
    const zeroTrusted = opts.zeroTrusted !== false;
    const awardSeen = opts.awardSeen === true;
    const jumpLimit = Math.max(250000,
      (prev.startStack || 0) * 8,
      prev.currentStack * 2);
    if (!(read > 0)) {

      if (heroExpected && prev.currentStack > 0 && zeroStreak >= zeroBustThreshold && zeroTrusted) {
        return { kind: 'bust', net: -prev.currentStack, current: 0 };
      }
      return { kind: 'none', net: 0, current: prev.currentStack };
    }
    if (afterAway && prev.currentStack > 0) return { kind: 'resync', net: 0, current: read };
    if (prev.startStack === 0) return { kind: 'initial', net: 0, current: read };
    if (prev.currentStack <= 0) {
      if (heroWonSinceZero) return { kind: 'winback', net: read, current: read };
      if (zeroRiseAgeMs < 3000) return { kind: 'hold', net: 0, current: prev.currentStack };
      return { kind: 'rebuy', net: 0, current: read };
    }
    const delta = read - prev.currentStack;
    if (delta === 0) return { kind: 'none', net: 0, current: read };
    if (Math.abs(delta) > jumpLimit) return { kind: 'resync', net: 0, current: read };
    if (!isPlausibleDelta(delta, prev.currentStack)) return { kind: 'resync', net: 0, current: read };
    if (heroExpected && !awardSeen && delta < 0) {
      return { kind: 'hold', net: 0, current: prev.currentStack };
    }
    if (heroExpected && !awardSeen && delta > 0 && zeroRiseAgeMs > 25000) {
      return { kind: 'hold', net: 0, current: prev.currentStack };
    }
    return { kind: delta > 0 ? 'win' : 'loss', net: delta, current: read };
  };

  const commitSessionLedger = () => {
    const net = session.pendingNet | 0;
    if (net === 0) return;
    session.pendingNet = 0;
    if (net > session.biggestWin) session.biggestWin = net;
    if (net < session.biggestLoss) session.biggestLoss = net;
    session.recentDeltas.push(net);
    if (session.recentDeltas.length > 12) session.recentDeltas.shift();
        session.netSeries.push({ h: session.handsPlayed, net: session.netChips });
    if (session.netSeries.length > 400) session.netSeries = session.netSeries.slice(-400);
    tinfo(`[TNP] Session: hand settled ${net >= 0 ? '+' : ''}$${net.toLocaleString()}, net $${session.netChips.toLocaleString()}`);
    renderSessionPanel();
    renderBankrollPanel();
  };

  const syncSessionStack = () => {
    const heroSeat = findOwnSeat();
    const heroExpected = !!heroSeat && !isSeatEmpty(heroSeat) && !isSeatSittingOut(heroSeat);
    const currentStack = heroExpected
      ? readHeroStack(heroSeat, session.currentStack || session.startStack || 0)
      : 0;

    reportDom('stack', currentStack > 0 || lastHeroStackZeroDisplayed, heroExpected);

    if (!heroExpected) {
      if (session.currentStack > 0 && !session.heroAwayAt) session.heroAwayAt = Date.now();
    } else if (session.heroAwayAt) {

      session.wasAway = Date.now() - session.heroAwayAt > 30000;
      session.heroAwayAt = 0;
    }
    if (!heroExpected && session.currentStack > 0) return session.currentStack;

    if (session.currentStack <= 0 && currentStack > 0) {
      if (!session.zeroRiseAt) session.zeroRiseAt = Date.now();
    } else if (session.zeroRiseAt) {
      session.zeroRiseAt = 0;
    }

    if (heroExpected && !(currentStack > 0)) {
      session.zeroStreak = (session.zeroStreak || 0) + 1;
    } else {
      session.zeroStreak = 0;
    }

    const move = netStackTransition(
      { startStack: session.startStack, currentStack: session.currentStack },
      currentStack,
      {
        heroExpected,
        heroWonSinceZero: session.lastHandHeroWon === true && session.currentStack <= 0,
        zeroRiseAgeMs: session.zeroRiseAt ? Date.now() - session.zeroRiseAt : Infinity,
        afterAway: session.wasAway === true,
        zeroStreak: session.zeroStreak || 1,
        zeroBustThreshold: 3,
        zeroTrusted: lastHeroStackZeroDisplayed && !(domHealth.stack && domHealth.stack.warned),
        awardSeen: sessionAwardSeenAt > 0 && (Date.now() - sessionAwardSeenAt) < 30000
      }
    );
    session.wasAway = false;

    if (move.kind === 'hold') return session.currentStack;

    if (move.kind === 'initial') {
      session.startStack = currentStack;
      session.currentStack = currentStack;
      session.stackKnown = true;
      session.stackDeltaKnown = false;
      tinfo(`[TNP] Session: initial stack $${currentStack.toLocaleString()}`);
      saveSession();
      return currentStack;
    }

    if (move.net !== 0) {

      session.netChips += move.net;
      session.stackDeltaKnown = true;
      session.pendingNet = (session.pendingNet | 0) + move.net;
      tinfo(`[TNP] Session: ${move.kind} ${move.net >= 0 ? '+' : ''}$${move.net.toLocaleString()}, net $${session.netChips.toLocaleString()}`);
      renderSessionPanel();
      renderBankrollPanel();
    } else if (move.kind === 'rebuy') {
            session.rebuys = (session.rebuys | 0) + 1;
      tinfo('[TNP] Session: rebuy detected (stack returned from zero); buy-in count updated.');
    } else if (move.kind !== 'none') {
      logStackDebug(`[TNP] Session: stack ${move.kind} to $${(move.current || 0).toLocaleString()} (no net)`);
    }
    session.stackKnown = session.stackKnown || currentStack > 0;
    if (move.kind === 'bust' || move.kind === 'winback') session.zeroRiseAt = move.kind === 'bust' ? Date.now() : 0;
    session.currentStack = move.current;

    if (move.kind !== 'none') saveSession();
    return session.currentStack;
  };

  const evaluateHand = (cards) => {
    if (cards.length === 0) return { score: 0, type: 0 };

    const idx = cards.map(c => CARD_IDX[c]);
    const score = evalFastIdx(new Uint8Array(idx), idx.length);
    return { score, type: score >> 20 };
  };

  const createDeck = (deadCards) => {
    const deck = [];
    for (const r of RANKS) for (const s of SUITS) {
      const c = r + s;
      if (!deadCards.includes(c)) deck.push(c);
    }
    return deck;
  };

  const wilsonCI = (wins, total, z = 1.96) => {
    if (total === 0) return { lower: 0, upper: 0 };
    const p = wins / total;
    const denom = 1 + z * z / total;
    const center = (p + z * z / (2 * total)) / denom;
    const spread = z * Math.sqrt(p * (1 - p) / total + z * z / (4 * total * total)) / denom;
    return { lower: Math.max(0, center - spread), upper: Math.min(1, center + spread) };
  };

  const varianceCI = (sum, sumSquares, runs, z = 1.96) => {
    if (runs <= 0) return { lower: 0, upper: 1 };
    const mean = sum / runs;
    const variance = runs > 1 ? Math.max(0, (sumSquares - runs * mean * mean) / (runs - 1)) : 0;
    const stderr = Math.sqrt(variance / runs);
    return {
      lower: Math.max(0, mean - z * stderr),
      upper: Math.min(1, mean + z * stderr)
    };
  };

  const runMonteCarlo = (hole, board, opponents, jobId, oppRanges, opts = {}) => {
    return new Promise(resolve => {
      const T = opts.targets ?? mcTargetsNow();
      if (Number.isFinite(opts.seed)) _rngState = (opts.seed >>> 0) || 1;
      const oppCount = Math.max(1, opponents);
      const onProgress = typeof opts.onProgress === 'function' ? opts.onProgress : null;
                        const heroThreshold = Number.isFinite(opts.heroRangeThreshold) ? opts.heroRangeThreshold : null;
      const fixedHole = (hole && hole.length === 2) ? hole.map(c => CARD_IDX[c]) : null;
      const holeIdx = fixedHole || [CARD_IDX['A♠'], CARD_IDX['K♠']];
      const boardIdx = board.map(c => CARD_IDX[c]);
      const dead = new Set(fixedHole ? [...holeIdx, ...boardIdx] : [...boardIdx]);
      const baseDeck = new Uint8Array(52 - dead.size);
      {
        let k = 0;
        for (let c = 0; c < 52; c++) if (!dead.has(c)) baseDeck[k++] = c;
      }
      const boardNeeded = Math.max(0, 5 - board.length);

      const deck = new Uint8Array(baseDeck.length);
      const my7 = new Uint8Array(7);
      const opp7 = new Uint8Array(7);
      const oppC1 = new Uint8Array(oppCount);
      const oppC2 = new Uint8Array(oppCount);
      if (fixedHole) { my7[0] = holeIdx[0]; my7[1] = holeIdx[1]; }

      const myBaseScore = (fixedHole && board.length === 5)
        ? evalFastIdx(new Uint8Array([...holeIdx, ...boardIdx]), 7)
        : 0;

      let runs = 0;
      let resultSum = 0, resultSumSquares = 0;
      let winCount = 0, tieCount = 0, lossCount = 0;
      const typeCounts = new Array(10).fill(0);
      const startedAt = Date.now();
      let batch = Math.max(T.minSlice, T.progressEvery);
      let lastProgressAt = 0;

      const snapshot = () => ({
        equity: runs > 0 ? resultSum / runs : 0,
        ci: varianceCI(resultSum, resultSumSquares, runs),
        typeDist: typeCounts.map(c => c / Math.max(1, runs)),
        samples: runs,
        resultSum, resultSumSquares,
        winCount, tieCount, lossCount,
        typeCounts
      });

      const cancelled = opts.isCancelled ?? (() => mcJobId !== jobId);

      const chunk = () => {
        if (cancelled()) { resolve(null); return; }
        const sliceStart = Date.now();
        const iters = Math.min(batch, T.maxSamples - runs);

        for (let i = 0; i < iters; i++) {
          deck.set(baseDeck);
          let liveLen = deck.length;

                              if (heroThreshold !== null && liveLen >= 2) {
            let heroAccepted = false;
            for (let attempt = 0; attempt < 30; attempt++) {
              const idx1 = (rng() * liveLen) | 0;
              let idx2 = (rng() * (liveLen - 1)) | 0;
              if (idx2 >= idx1) idx2++;
              const c1 = deck[idx1], c2 = deck[idx2];
              if (PRE_SCORE[c1 * 52 + c2] >= heroThreshold) {
                const hiP = idx1 > idx2 ? idx1 : idx2;
                const loP = idx1 > idx2 ? idx2 : idx1;
                liveLen--; deck[hiP] = deck[liveLen];
                liveLen--; deck[loP] = deck[liveLen];
                my7[0] = c1; my7[1] = c2;
                heroAccepted = true;
                break;
              }
            }
            if (!heroAccepted) {
              let idx = (rng() * liveLen) | 0;
              const c1 = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
              idx = (rng() * liveLen) | 0;
              const c2 = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
              my7[0] = c1; my7[1] = c2;
            }
          }

          let dealtOpps = 0;
          for (let p = 0; p < oppCount; p++) {
            if (liveLen < 2) break;
            const threshold = oppRanges ? oppRanges[p] : null;
            let accepted = false;

            for (let attempt = 0; attempt < 30; attempt++) {
              const idx1 = (rng() * liveLen) | 0;
              let idx2 = (rng() * (liveLen - 1)) | 0;
              if (idx2 >= idx1) idx2++;
              const c1 = deck[idx1], c2 = deck[idx2];
              if (!threshold || PRE_SCORE[c1 * 52 + c2] >= threshold) {
                const hiP = idx1 > idx2 ? idx1 : idx2;
                const loP = idx1 > idx2 ? idx2 : idx1;
                liveLen--; deck[hiP] = deck[liveLen];
                liveLen--; deck[loP] = deck[liveLen];
                oppC1[p] = c1; oppC2[p] = c2;
                accepted = true;
                break;
              }
            }
            if (!accepted) {
              let idx = (rng() * liveLen) | 0;
              oppC1[p] = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
              idx = (rng() * liveLen) | 0;
              oppC2[p] = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
            }
            dealtOpps++;
          }

          for (let b = 0; b < boardIdx.length; b++) my7[2 + b] = boardIdx[b];
          for (let b = 0; b < boardNeeded; b++) {
            const idx = (rng() * liveLen) | 0;
            my7[2 + boardIdx.length + b] = deck[idx];
            liveLen--; deck[idx] = deck[liveLen];
          }

          const myScoreNow = evalFastIdx(my7, 7);
          const myScore = board.length === 5 ? myBaseScore : myScoreNow;
          typeCounts[myScoreNow >> 20]++;

          for (let b = 0; b < 5; b++) opp7[2 + b] = my7[2 + b];

          let won = true, tied = 1;
          for (let p = 0; p < dealtOpps; p++) {
            opp7[0] = oppC1[p]; opp7[1] = oppC2[p];
            const oppScore = evalFastIdx(opp7, 7);
            if (oppScore > myScore) { won = false; break; }
            if (oppScore === myScore) tied++;
          }

          if (won) {

            const share = tied === 1 ? 1 : (1 / tied);
            resultSum += share;
            resultSumSquares += share * share;
          }

          if (!won) lossCount++;
          else if (tied > 1) tieCount++;
          else winCount++;
        }

        runs += iters;
        const now = Date.now();
        if (iters > 0) {

          const perSim = (now - sliceStart) / iters;
          batch = Math.max(T.minSlice, Math.min(60000, Math.round(T.sliceMs / Math.max(perSim, 1e-4))));
        }

        const snap = snapshot();
        const half = (snap.ci.upper - snap.ci.lower) / 2;
        if (onProgress && runs - lastProgressAt >= T.progressEvery
          && runs >= T.progressEvery && runs < T.maxSamples) {
          lastProgressAt = runs;
          onProgress(snap);
        }

        if ((runs >= T.minSamples && half <= T.ciHalfWidth)
          || runs >= T.maxSamples
          || now - startedAt >= T.deadlineMs) {
          resolve(Object.assign(snap, {
            method: 'monte-carlo',
            workers: 0,
            elapsedMs: now - startedAt
          }));
          return;
        }
        setTimeout(chunk, 0);
      };
      setTimeout(chunk, 0);
    });
  };

  const MC_WORKER_SRC = `
'use strict';

const RANKS = ['2','3','4','5','6','7','8','9','T','J','Q','K','A'];
const SUITS = ['\u2660','\u2665','\u2666','\u2663'];
const RANK_VALS = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'T':10,'J':11,'Q':12,'K':13,'A':14};
const RANK_OF = new Uint8Array(52);
const SUIT_OF = new Uint8Array(52);
const CARD_IDX = {};
(function () {
  let i = 0;
  for (const r of RANKS) for (const s of SUITS) {
    CARD_IDX[r + s] = i;
    RANK_OF[i] = RANK_VALS[r];
    SUIT_OF[i] = SUITS.indexOf(s);
    i++;
  }
})();
const preflopScore = (c1, c2) => {
  const r1 = RANK_VALS[c1[0]], r2 = RANK_VALS[c2[0]];
  const hi = Math.max(r1, r2), lo = Math.min(r1, r2);
  const suited = c1[1] === c2[1];
  const gap = hi - lo - 1;
  if (hi === lo) return 300 + hi * 20;
  let score = hi * 20 + lo * 4;
  if (suited) score += 25;
  if (gap === 0) score += 15; else score -= gap * 8;
  if (hi === 14) score += 15;
  if (hi >= 11 && lo >= 10) score += 20;
  return score;
};
const PRE_SCORE = new Int16Array(52 * 52);
(function () {
  const cards = Object.keys(CARD_IDX);
  for (const a of cards) for (const b of cards) {
    const ia = CARD_IDX[a], ib = CARD_IDX[b];
    if (ia !== ib) PRE_SCORE[ia * 52 + ib] = preflopScore(a, b);
  }
})();
let _rngState = 1;
const rng = () => {
  let x = _rngState;
  x ^= x << 13; x >>>= 0;
  x ^= x >>> 17;
  x ^= x << 5;  x >>>= 0;
  _rngState = x;
  return x / 4294967296;
};
const straightHighFromMask = (mask) => {
  for (let hi = 14; hi >= 6; hi--) {
    const need = 0b11111 << (hi - 4);
    if ((mask & need) === need) return hi;
  }
  const wheel = (1 << 14) | (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2);
  if ((mask & wheel) === wheel) return 5;
  return 0;
};
const _rc = new Uint8Array(15);
const _sc = new Uint8Array(4);
const _sm = new Uint16Array(4);
const evalFastIdx = (cards, n) => {
  _rc.fill(0); _sc.fill(0); _sm.fill(0);
  let rankMask = 0;
  for (let i = 0; i < n; i++) {
    const c = cards[i];
    const r = RANK_OF[c], s = SUIT_OF[c];
    _rc[r]++; _sc[s]++;
    _sm[s] |= (1 << r);
    rankMask |= (1 << r);
  }
  let flushSuit = -1;
  for (let s = 0; s < 4; s++) if (_sc[s] >= 5) { flushSuit = s; break; }
  if (flushSuit >= 0) {
    const sfHigh = straightHighFromMask(_sm[flushSuit]);
    if (sfHigh > 0) {
      const type = sfHigh === 14 ? 9 : 8;
      return (type << 20) | (sfHigh << 16);
    }
  }
  let quads = 0, trip1 = 0, trip2 = 0, pair1 = 0, pair2 = 0;
  for (let r = 14; r >= 2; r--) {
    const c = _rc[r];
    if (c === 4) { if (!quads) quads = r; }
    else if (c === 3) { if (!trip1) trip1 = r; else if (!trip2) trip2 = r; }
    else if (c === 2) { if (!pair1) pair1 = r; else if (!pair2) pair2 = r; }
  }
  if (quads) {
    let k = 0;
    for (let r = 14; r >= 2; r--) if (r !== quads && _rc[r] > 0) { k = r; break; }
    return (7 << 20) | (quads << 16) | (k << 12);
  }
  if (trip1 && (trip2 || pair1)) {
    const pr = trip2 > pair1 ? trip2 : pair1;
    return (6 << 20) | (trip1 << 16) | (pr << 12);
  }
  if (flushSuit >= 0) {
    let score = (5 << 20), got = 0;
    const m = _sm[flushSuit];
    for (let r = 14; r >= 2 && got < 5; r--) {
      if (m & (1 << r)) { score |= r << (16 - 4 * got); got++; }
    }
    return score;
  }
  const stHigh = straightHighFromMask(rankMask);
  if (stHigh > 0) return (4 << 20) | (stHigh << 16);
  if (trip1) {
    let score = (3 << 20) | (trip1 << 16), got = 0;
    for (let r = 14; r >= 2 && got < 2; r--) {
      if (r !== trip1 && _rc[r] > 0) { score |= r << (12 - 4 * got); got++; }
    }
    return score;
  }
  if (pair1 && pair2) {
    let k = 0;
    for (let r = 14; r >= 2; r--) if (r !== pair1 && r !== pair2 && _rc[r] > 0) { k = r; break; }
    return (2 << 20) | (pair1 << 16) | (pair2 << 12) | (k << 8);
  }
  if (pair1) {
    let score = (1 << 20) | (pair1 << 16), got = 0;
    for (let r = 14; r >= 2 && got < 3; r--) {
      if (r !== pair1) {
        for (let c = 0; c < _rc[r] && got < 3; c++) { score |= r << (12 - 4 * got); got++; }
      }
    }
    return score;
  }
  let score = 0, got = 0;
  for (let r = 14; r >= 2 && got < 5; r--) {
    for (let c = 0; c < _rc[r] && got < 5; c++) { score |= r << (16 - 4 * got); got++; }
  }
  return score;
};
const varianceCI = (sum, sumSquares, runs, z = 1.96) => {
  if (runs <= 0) return { lower: 0, upper: 1 };
  const mean = sum / runs;
  const variance = runs > 1 ? Math.max(0, (sumSquares - runs * mean * mean) / (runs - 1)) : 0;
  const stderr = Math.sqrt(variance / runs);
  return {
    lower: Math.max(0, mean - z * stderr),
    upper: Math.min(1, mean + z * stderr)
  };
};
const DEFAULT_T = { ciHalfWidth: ${MC_MANDATE.ciHalfWidth}, minSamples: ${MC_MANDATE.minSamples}, maxSamples: ${MC_MANDATE.maxSamples}, deadlineMs: ${MC_MANDATE.deadlineMs}, progressEvery: ${MC_MANDATE.progressEvery} };
let currentJob = 0;
let stopRequested = false;
const sampleWeighted = (table, rnd) => {
  if (!table || !table.c.length || !(table.t > 0)) return null;
  const r = rnd() * table.t;
  let lo = 0, hi = table.c.length - 1;
  while (lo < hi) { const mid = (lo + hi) >> 1; if (table.w[mid] < r) lo = mid + 1; else hi = mid; }
  return table.c[lo];
};
self.onmessage = (e) => {
  const msg = e && e.data;
  if (!msg || typeof msg !== 'object') return;
  if (msg.type === 'ping') { self.postMessage({ type: 'ready' }); return; }
  if (msg.type === 'stop') { if (msg.jobId === currentJob) stopRequested = true; return; }
  if (msg.type !== 'run') return;
  currentJob = msg.jobId >>> 0;
  stopRequested = false;
  _rngState = (msg.seed >>> 0) || 1;

  const T = (msg.targets && Number.isFinite(msg.targets.minSamples))
    ? msg.targets
    : DEFAULT_T;
  const jobId = currentJob;
  const post = (extra) => self.postMessage(Object.assign({ type: 'done', jobId }, extra));
  const holeIdx = (msg.hole || []).map(c => CARD_IDX[c]);
  const boardIdx = (msg.board || []).map(c => CARD_IDX[c]);
  if (holeIdx.length !== 2) { post({ equity: null, cancelled: true }); return; }
  const oppCount = Math.max(1, msg.opponents | 0);
  const oppRanges = Array.isArray(msg.ranges) ? msg.ranges : null;
  const oppTables = Array.isArray(msg.combos)
    ? msg.combos.map((t) => (t && Array.isArray(t.c) && Array.isArray(t.w)) ? { c: t.c, w: t.w, t: t.t } : null)
    : null;
  const dead = new Set(holeIdx.concat(boardIdx));
  const baseDeck = new Uint8Array(52 - dead.size);
  {
    let k = 0;
    for (let c = 0; c < 52; c++) if (!dead.has(c)) baseDeck[k++] = c;
  }
  const boardNeeded = Math.max(0, 5 - boardIdx.length);
  const myBaseScore = boardIdx.length === 5 ? evalFastIdx(new Uint8Array(holeIdx.concat(boardIdx)), 7) : 0;
  const deck = new Uint8Array(baseDeck.length);
  const my7 = new Uint8Array(7), opp7 = new Uint8Array(7);
  const oppC1 = new Uint8Array(oppCount), oppC2 = new Uint8Array(oppCount);
  my7[0] = holeIdx[0]; my7[1] = holeIdx[1];
  let runs = 0, resultSum = 0, resultSumSquares = 0;
  let winCount = 0, tieCount = 0, lossCount = 0;
  const typeCounts = new Array(10).fill(0);
  let lastProgressAt = 0;
  const t0 = Date.now();
  let batch = Math.max(1000, T.progressEvery);
  const snapshot = () => {
    const equity = runs > 0 ? resultSum / runs : 0;
    return { equity, ci: varianceCI(resultSum, resultSumSquares, runs), typeDist: typeCounts.map(c => c / Math.max(1, runs)), samples: runs, resultSum, resultSumSquares, winCount, tieCount, lossCount, typeCounts };
  };
  const chunk = () => {
    if (currentJob !== jobId) { post({ equity: null, cancelled: true }); return; }
    const sliceStart = Date.now();
    const iters = Math.min(batch, T.maxSamples - runs);
    for (let i = 0; i < iters; i++) {
      deck.set(baseDeck);
      let liveLen = deck.length;
      let dealtOpps = 0;
      for (let p = 0; p < oppCount; p++) {
        if (liveLen < 2) break;
        if (oppTables && oppTables[p]) {
          let accepted = false;
          for (let attempt = 0; attempt < 40; attempt++) {
            const combo = sampleWeighted(oppTables[p], rng);
            if (!combo) break;
            const i1 = deck.indexOf(CARD_IDX[combo[0] + combo[1]]);
            if (i1 < 0 || i1 >= liveLen) continue;
            const c1 = deck[i1]; liveLen--; deck[i1] = deck[liveLen];
            const i2 = deck.indexOf(CARD_IDX[combo[2] + combo[3]]);
            if (i2 < 0 || i2 >= liveLen) { liveLen++; deck[liveLen - 1] = c1; continue; }
            const c2 = deck[i2]; liveLen--; deck[i2] = deck[liveLen];
            oppC1[p] = c1; oppC2[p] = c2;
            accepted = true;
            break;
          }
          if (!accepted) {
            let idx = (rng() * liveLen) | 0;
            oppC1[p] = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
            idx = (rng() * liveLen) | 0;
            oppC2[p] = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
          }
          dealtOpps++;
          continue;
        }
        const threshold = oppRanges ? oppRanges[p] : null;
        let accepted = false;
        for (let attempt = 0; attempt < 30; attempt++) {
          const idx1 = (rng() * liveLen) | 0;
          let idx2 = (rng() * (liveLen - 1)) | 0;
          if (idx2 >= idx1) idx2++;
          const c1 = deck[idx1], c2 = deck[idx2];
          if (!threshold || PRE_SCORE[c1 * 52 + c2] >= threshold) {
            const hiP = idx1 > idx2 ? idx1 : idx2;
            const loP = idx1 > idx2 ? idx2 : idx1;
            liveLen--; deck[hiP] = deck[liveLen];
            liveLen--; deck[loP] = deck[liveLen];
            oppC1[p] = c1; oppC2[p] = c2;
            accepted = true;
            break;
          }
        }
        if (!accepted) {
          let idx = (rng() * liveLen) | 0;
          oppC1[p] = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
          idx = (rng() * liveLen) | 0;
          oppC2[p] = deck[idx]; liveLen--; deck[idx] = deck[liveLen];
        }
        dealtOpps++;
      }
      for (let b = 0; b < boardIdx.length; b++) my7[2 + b] = boardIdx[b];
      for (let b = 0; b < boardNeeded; b++) {
        const idx = (rng() * liveLen) | 0;
        my7[2 + boardIdx.length + b] = deck[idx];
        liveLen--; deck[idx] = deck[liveLen];
      }
      const myScoreNow = evalFastIdx(my7, 7);
      const myScore = boardIdx.length === 5 ? myBaseScore : myScoreNow;
      typeCounts[myScoreNow >> 20]++;
      for (let b = 0; b < 5; b++) opp7[2 + b] = my7[2 + b];
      let won = true, tied = 1;
      for (let p = 0; p < dealtOpps; p++) {
        opp7[0] = oppC1[p]; opp7[1] = oppC2[p];
        const oppScore = evalFastIdx(opp7, 7);
        if (oppScore > myScore) { won = false; break; }
        if (oppScore === myScore) tied++;
      }
      if (won) {
        const share = tied === 1 ? 1 : (1 / tied);
        resultSum += share;
        resultSumSquares += share * share;
      }
      if (!won) lossCount++;
      else if (tied > 1) tieCount++;
      else winCount++;
    }
    runs += iters;
    const now = Date.now();
    if (iters > 0) {
      const perSim = (now - sliceStart) / iters;
      batch = Math.max(1000, Math.min(60000, Math.round(10 / Math.max(perSim, 1e-4))));

      if (T.coordinated) batch = Math.min(batch, Math.max(4000, T.progressEvery));
    }
    const snap = snapshot();
    const half = (snap.ci.upper - snap.ci.lower) / 2;
    if (runs - lastProgressAt >= T.progressEvery && runs >= T.progressEvery && runs < T.maxSamples) {
      lastProgressAt = runs;
      self.postMessage(Object.assign({ type: 'progress', jobId }, snap));
    }
    if (stopRequested
      || (!T.coordinated && runs >= T.minSamples && half <= T.ciHalfWidth)
      || runs >= T.maxSamples
      || now - t0 >= T.deadlineMs) {
      post(Object.assign(snap, { deadlineHit: now - t0 >= T.deadlineMs && runs < T.maxSamples }));
      return;
    }
    setTimeout(chunk, 0);
  };
  setTimeout(chunk, 0);
};
`;

  let mcPool = [];
  let mcPoolState = 'none';
  let mcPoolPromise = null;
  let mcPoolDeadAt = 0;
  const MC_WORKER_JOBS = new Map();

  const spawnMcWorkers = (wanted) => {

    return new Promise(resolve => {
      let url = null;
      const batch = [];
      let settled = false;
      try {
        if (typeof Worker === 'undefined' || typeof Blob === 'undefined'
          || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') throw new Error('workers unavailable');
        url = URL.createObjectURL(new Blob([MC_WORKER_SRC], { type: 'text/javascript' }));
      } catch {
        resolve([]);
        return;
      }
      const finish = () => {
        if (settled) return;
        settled = true;
        clearTimeout(timer);
        try { URL.revokeObjectURL(url); } catch { }
        const alive = batch.filter(w => w.__tnpReady);
        for (const w of batch) if (!w.__tnpReady) { try { w.terminate(); } catch { } }
        resolve(alive);
      };
      const timer = setTimeout(finish, 1500);
      for (let i = 0; i < wanted; i++) {
        let w = null;
        try { w = new Worker(url); } catch { continue; }
        w.__tnpIndex = i;
        w.onerror = () => {
          w.__tnpDead = true;
          try { w.terminate(); } catch { }
          mcPool = mcPool.filter(x => x !== w);
          if (!mcPool.length && mcPoolState !== 'spawning') {
            mcPoolState = 'dead';
            mcPoolDeadAt = Date.now();
            for (const entry of MC_WORKER_JOBS.values()) entry.bail();
            MC_WORKER_JOBS.clear();
          }
        };
        w.onmessageerror = w.onerror;
        w.onmessage = (e) => {
          const m = e && e.data;
          if (!m || typeof m !== 'object') return;
          if (m.type === 'ready') {
            w.__tnpReady = true;
            if (batch.length && batch.every(x => x.__tnpReady)) finish();
            return;
          }
          mcPoolRoute(m, w.__tnpIndex);
        };
        batch.push(w);
        try { w.postMessage({ type: 'ping' }); } catch { batch.splice(batch.indexOf(w), 1); }
      }
      if (!batch.length) finish();
    });
  };

  const mcPoolRoute = (m, workerIndex) => {
    const coord = MC_WORKER_JOBS.get(m.jobId);
    if (coord) coord.onMessage(m, workerIndex);
  };

  const getMcPool = () => {
    if (mcPoolState === 'dead') {
      if (Date.now() - mcPoolDeadAt > 60000) {
        mcPoolState = 'none';
        mcPoolPromise = null;
        mcPool = [];
      } else {
        return Promise.resolve(mcPool);
      }
    }
    if (mcPoolState === 'ready') return Promise.resolve(mcPool);
    if (!mcPoolPromise) {
      mcPoolState = 'spawning';
      mcPoolPromise = spawnMcWorkers(MC_POOL_SIZE).then(ws => {
        mcPool = ws || [];
        mcPoolState = mcPool.length ? 'ready' : 'dead';
        if (!mcPool.length) {
          mcPoolDeadAt = Date.now();

          for (const entry of MC_WORKER_JOBS.values()) entry.bail();
          MC_WORKER_JOBS.clear();
        }
        return mcPool;
      });
    }
    return mcPoolPromise;
  };

  const runPooledMonteCarlo = (hole, board, opponents, jobId, oppRanges, opts, pool) => {
    const W = pool.length;
    if (!W) return Promise.resolve(null);
    const T = opts.targets ?? mcTargetsNow();
    const totalTrials = (Number.isFinite(T.totalTrials) && T.totalTrials > 0) ? Math.floor(T.totalTrials) : (T.maxSamples || 1000000);
    const startedAt = Date.now();
    const onProgress = typeof opts.onProgress === 'function' ? opts.onProgress : null;
    const baseQuota = Math.floor(totalTrials / W);
    const quotaRemainder = totalTrials - baseQuota * W;
    const quotaFor = (i) => baseQuota + (i < quotaRemainder ? 1 : 0);
    const combos = Array.isArray(opts.combos) ? opts.combos : null;

    return new Promise(resolve => {
      const partials = new Array(W).fill(null);
      let doneCount = 0;
      let stopped = false;
      let settled = false;
      let safety = null;
      const isCancelled = typeof opts.isCancelled === 'function'
        ? opts.isCancelled
        : () => jobId !== mcJobId;

      const finish = (value) => {
        if (settled) return;
        settled = true;
        if (safety) clearTimeout(safety);
        MC_WORKER_JOBS.delete(jobId);
        resolve(value);
      };

      const mergedPublic = (m, complete) => ({
        equity: m.equity,
        ci: m.ci,
        typeDist: m.typeDist,
        samples: m.samples,
        winCount: m.wins, tieCount: m.ties, lossCount: m.losses,
        workers: W,
        trialsComplete: complete === true,
        mandatedTrials: totalTrials
      });

      const settleMerged = () => {
        const merged = mergeMcPartials(partials);
        if (!merged.samples) { finish(null); return; }
        const complete = merged.samples >= totalTrials;
        finish(Object.assign(mergedPublic(merged, complete), {
          method: 'monte-carlo',
          elapsedMs: Date.now() - startedAt
        }));
      };

      const stopAll = () => {
        if (stopped) return;
        stopped = true;
        for (const w of pool) {
          try { w.postMessage({ type: 'stop', jobId }); } catch { }
        }
      };

      const coord = {
        onMessage: (m, workerIndex) => {
          if (settled) return;

          if (isCancelled()) { stopAll(); finish(null); return; }
          if (m.type === 'progress') {
            partials[workerIndex] = m;
            const merged = mergeMcPartials(partials);
            if (onProgress) onProgress(mergedPublic(merged, false));
            return;
          }
          if (m.type === 'done') {
            if (!m.cancelled) partials[workerIndex] = m;
            doneCount++;
            if (doneCount >= W) settleMerged();
          }
        },
        bail: () => { stopAll(); finish(null); }
      };
      MC_WORKER_JOBS.set(jobId, coord);

      safety = setTimeout(() => { stopAll(); setTimeout(settleMerged, 150); },
        T.deadlineMs + 3000);

      const baseSeed = (typeof opts.seed === 'number' && Number.isFinite(opts.seed))
        ? (opts.seed >>> 0) || 1
        : (T.deterministic ? scenarioSeed(hole, board, opponents, oppRanges) : 0);
      for (let i = 0; i < W; i++) {
        const w = pool[i];
        const quota = quotaFor(i);
        const seed = baseSeed
          ? (((baseSeed ^ ((i + 1) * 0x85EBCA6B)) >>> 0) || 1)
          : (((Date.now() ^ (jobId * 0x9E3779B9)) ^ ((i + 1) * 0x85EBCA6B)) >>> 0) || 1;
        const per = {
          ciHalfWidth: 0,
          minSamples: quota,
          maxSamples: quota,
          deadlineMs: T.deadlineMs,
          progressEvery: Math.max(4000, Math.floor(quota / 10)),
          coordinated: true
        };
        try {
          w.postMessage({ type: 'run', jobId, hole, board, opponents, ranges: oppRanges, combos, seed, targets: per });
        } catch {

          doneCount++;
        }
      }
      if (doneCount >= W) settleMerged();
    });
  };

  const equityFinalCache = new Map();
  const EQUITY_CACHE_CAP = 48;
  const equityCacheKey = (hole, board, opponents, rangeSig) =>
    `${(hole || []).join(',')}|${(board || []).join(',')}|${opponents | 0}|${rangeSig || ''}`;
  const equityCacheStore = (key, result) => {
    if (!result || result.trialsComplete !== true) return;
    if (equityFinalCache.size >= EQUITY_CACHE_CAP) {
      equityFinalCache.delete(equityFinalCache.keys().next().value);
    }
    equityFinalCache.set(key, result);
  };

  const runMandatedEquity = async (hole, board, opponents, jobId, opts = {}) => {
    const onProgress = typeof opts.onProgress === 'function' ? opts.onProgress : null;
    const combos = Array.isArray(opts.combos) && opts.combos.length ? opts.combos : null;
    const thresholds = Array.isArray(opts.ranges) && opts.ranges.length ? opts.ranges : null;
    const isCancelled = typeof opts.isCancelled === 'function' ? opts.isCancelled : null;
    const pool = await getMcPool();
    let result = null;
    if (pool.length > 0) {
      result = await runPooledMonteCarlo(hole, board, opponents, jobId, thresholds, {
        onProgress, combos,
        targets: MC_MANDATE,
        seed: scenarioSeed(hole, board, opponents, thresholds),
        isCancelled
      }, pool);
      if (result === null && (isCancelled ? isCancelled() : jobId !== mcJobId)) return null;
    }
    if (result === null) {
      result = await runMonteCarlo(hole, board, opponents, jobId, thresholds, {
        onProgress, targets: MC_MANDATE,
        seed: scenarioSeed(hole, board, opponents, thresholds),
        isCancelled: isCancelled || undefined
      });
      if (result) {
        result.method = 'monte-carlo (main-thread fallback)';
        result.workers = 0;
        result.trialsComplete = result.samples >= MC_MANDATE.totalTrials;
        result.mandatedTrials = MC_MANDATE.totalTrials;
      }
    }
    return result;
  };

  const runEquityJob = async (hole, board, opponents, jobId, oppRanges, opts = {}) => {
                    const pool = (Number.isFinite(opts.heroRangeThreshold)) ? [] : await getMcPool();
    if (pool.length > 0) {
      const pooled = await runPooledMonteCarlo(hole, board, opponents, jobId, oppRanges, opts, pool);
      if (pooled !== null) return pooled;
      if (jobId !== mcJobId) return null;
    }
    return runMonteCarlo(hole, board, opponents, jobId, oppRanges, opts);
  };

  const EXACT_ENUM_CAP = 60000;

  const exactDealCount = (boardLen) => {
    const drawCount = 5 - boardLen;
    if (drawCount < 0 || drawCount > 2) return null;
    const deckLen = 52 - 2 - boardLen;
    const poolSize = deckLen - drawCount;
    if (drawCount <= 1) {
      return drawCount === 0
        ? (poolSize * (poolSize - 1)) / 2
        : (deckLen * (poolSize * (poolSize - 1))) / 2;
    }

    const oppPairs = (deckLen * (deckLen - 1)) / 2;
    const boardPairs = (poolSize * (poolSize - 1)) / 2;
    return oppPairs * boardPairs;
  };
  const runExactEquity = (hole, board, jobId, oppThreshold = null, opts = null) => {
    return new Promise(resolve => {
      const exactCancelled = (opts && typeof opts.isCancelled === 'function')
        ? opts.isCancelled
        : () => mcJobId !== jobId;
      const holeIdx = hole.map(c => CARD_IDX[c]);
      const boardIdx = board.map(c => CARD_IDX[c]);
      const dead = new Set([...holeIdx, ...boardIdx]);
      const deck = [];
      for (let c = 0; c < 52; c++) if (!dead.has(c)) deck.push(c);

      const drawCount = 5 - board.length;
      if (drawCount < 0 || drawCount > 2) { resolve(null); return; }

      const combosTotal = exactDealCount(board.length);
      const dealCap = drawCount === 2 ? EXACT_FLOP_CAP : EXACT_ENUM_CAP;
      if (combosTotal === null || !Number.isFinite(combosTotal) || combosTotal <= 0 || combosTotal > dealCap) {
        resolve(null);
        return;
      }
      const startedAt = Date.now();

      const my7 = new Uint8Array(7);
      const opp7 = new Uint8Array(7);
      const all7 = new Uint8Array(7);
      for (let h = 0; h < 2; h++) { my7[h] = holeIdx[h]; all7[h] = holeIdx[h]; }
      for (let b = 0; b < boardIdx.length; b++) { my7[2 + b] = boardIdx[b]; opp7[2 + b] = boardIdx[b]; all7[2 + b] = boardIdx[b]; }

      const typeCounts = new Array(10).fill(0);

      const heroScoreByDraw = new Uint32Array(deck.length);
      const heroScore2 = drawCount === 2 ? new Uint32Array(52 * 52) : null;
      if (drawCount === 2) {
        for (let t = 0; t < deck.length; t++) {
          all7[5] = deck[t];
          for (let r = t + 1; r < deck.length; r++) {
            all7[6] = deck[r];
            heroScore2[deck[t] * 52 + deck[r]] = evalFastIdx(all7, 7);
          }
        }
        all7[5] = 0; all7[6] = 0;
      } else if (drawCount === 1) {
        for (let d = 0; d < deck.length; d++) {
          all7[6] = deck[d];
          heroScoreByDraw[d] = evalFastIdx(all7, 7);
          typeCounts[heroScoreByDraw[d] >> 20]++;
        }
      } else {
        const base = evalFastIdx(my7, 7);
        heroScoreByDraw.fill(base);
        typeCounts[base >> 20] = 1;
      }

      let equitySum = 0, combosDone = 0;
      let winCount = 0, tieCount = 0, lossCount = 0;
      let drawIndex = 0;
      let pairIndex = 0;

      const flopPairs = [];
      if (drawCount === 2) {
        for (let a = 0; a < deck.length - 1; a++)
          for (let b = a + 1; b < deck.length; b++) flopPairs.push(a * 64 + b);
      }

      const finish = () => {

        if (combosDone === 0) { resolve(null); return; }
        const equity = equitySum / combosDone;

        const ci = { lower: equity, upper: equity };
        const typeDist = drawCount === 0
          ? null
          : typeCounts.map(c => c / Math.max(1, drawCount === 1 ? deck.length : combosDone));
        resolve({
          equity, ci, typeDist,
          samples: combosDone, method: 'exact',
          winCount, tieCount, lossCount,
          workers: 0,
          elapsedMs: Date.now() - startedAt
        });
      };

      const enumerateDraw = () => {
        const riverCard = deck[drawIndex];
        opp7[6] = riverCard;
        const myScore = heroScoreByDraw[drawIndex];
        for (let a = 0; a < deck.length; a++) {
          if (a === drawIndex) continue;
          opp7[0] = deck[a];
          for (let b = a + 1; b < deck.length; b++) {
            if (b === drawIndex) continue;

            if (oppThreshold !== null && PRE_SCORE[deck[a] * 52 + deck[b]] < oppThreshold) continue;
            opp7[1] = deck[b];
            const oppScore = evalFastIdx(opp7, 7);
            if (oppScore < myScore) { equitySum += 1; winCount++; }
            else if (oppScore === myScore) { equitySum += 0.5; tieCount++; }
            else lossCount++;
            combosDone++;
          }
        }
      };

      const enumerateRiver = () => {
        const myScore = heroScoreByDraw[0];
        for (let a = 0; a < deck.length - 1; a++) {
          opp7[0] = deck[a];
          for (let b = a + 1; b < deck.length; b++) {

            if (oppThreshold !== null && PRE_SCORE[deck[a] * 52 + deck[b]] < oppThreshold) continue;
            opp7[1] = deck[b];
            const oppScore = evalFastIdx(opp7, 7);
            if (oppScore < myScore) { equitySum += 1; winCount++; }
            else if (oppScore === myScore) { equitySum += 0.5; tieCount++; }
            else lossCount++;
            combosDone++;
          }
        }
      };

      if (drawCount === 0) {

        setTimeout(() => {
          if (exactCancelled()) { resolve(null); return; }
          enumerateRiver();
          finish();
        }, 0);
      } else if (drawCount === 1) {

        const step = () => {
          if (exactCancelled()) { resolve(null); return; }
          if (drawIndex >= deck.length) { finish(); return; }
          enumerateDraw();
          drawIndex++;
          if (drawIndex >= deck.length) { finish(); return; }
          setTimeout(step, 0);
        };
        setTimeout(step, 0);
      } else {

        const enumerateFlop = () => {
          const sliceStart = Date.now();
          while (pairIndex < flopPairs.length) {
            const packed = flopPairs[pairIndex];
            const a = packed >> 6, b = packed & 63;

            if (oppThreshold !== null && PRE_SCORE[deck[a] * 52 + deck[b]] < oppThreshold) {
              pairIndex++;
              continue;
            }
            opp7[0] = deck[a]; opp7[1] = deck[b];
            for (let t = 0; t < deck.length; t++) {
              if (t === a || t === b) continue;
              const dt = deck[t];
              opp7[5] = dt;
              for (let r = t + 1; r < deck.length; r++) {
                if (r === a || r === b) continue;
                const dr = deck[r];
                const myScore = heroScore2[dt * 52 + dr];
                typeCounts[myScore >> 20]++;
                opp7[6] = dr;
                const oppScore = evalFastIdx(opp7, 7);
                if (oppScore < myScore) { equitySum += 1; winCount++; }
                else if (oppScore === myScore) { equitySum += 0.5; tieCount++; }
                else lossCount++;
                combosDone++;
              }
            }
            pairIndex++;
            if (Date.now() - sliceStart >= MC_MANDATE.sliceMs) return true;
          }
          return false;
        };
        const step = () => {
          if (exactCancelled()) { resolve(null); return; }
          if (Date.now() - startedAt >= EXACT_FLOP_DEADLINE_MS) { resolve(null); return; }
          if (!enumerateFlop()) { finish(); return; }
          setTimeout(step, 0);
        };
        setTimeout(step, 0);
      }
    });
  };

  const _outsCache = new Map();
  const analyzeOutsCards = (hole, board) => {
    if (board.length !== 3 && board.length !== 4) return null;
    const cacheKey = hole.join(',') + '|' + board.join(',');
    if (_outsCache.has(cacheKey)) return _outsCache.get(cacheKey);
    const currentEval = evaluateHand(hole.concat(board));
    const deck = createDeck(hole.concat(board));
    const boardRanks = board.map(c => c[0]);
    const boardSuits = board.map(c => c[1]);
    const boardRankVals = board.map(c => RANK_VALS[c[0]]);
    const topBoardRank = Math.max(0, ...boardRankVals);
    const suitTally = {};
    for (const s of boardSuits) suitTally[s] = (suitTally[s] || 0) + 1;
    const wetBoard = Math.max(0, ...Object.values(suitTally)) >= 3 || new Set(boardRankVals).size >= 3
      && Math.max(...boardRankVals) - Math.min(...boardRankVals) <= 4;
    const currMain = (currentEval.score >> 16) & 0xF;
    const out = [];
    const seen = new Set();
    for (const card of deck) {
      if (seen.has(card)) continue;
      seen.add(card);
      const newEval = evaluateHand(hole.concat(board, [card]));
      if (newEval.score <= currentEval.score) continue;
      const improvesType = newEval.type > currentEval.type;
      const newMain = (newEval.score >> 16) & 0xF;
      const improvesRank = !improvesType && newMain > currMain && currentEval.type >= 1;
      if (!improvesType && !improvesRank) continue;

      const pairsBoard = boardRanks.includes(card[0]);
      const suitsCount = boardSuits.filter(s => s === card[1]).length + 1;
      const bringsSharedFlush = suitsCount >= 3 && !hole.some(c => c[1] === card[1]);
      let weight = 1.0;
      let dirty = false;
      let label = improvesType ? (OUTS_TYPE_NAMES[newEval.type] ?? 'improve') : 'better rank';
      if (board.length === 4) {
        const boardOnly = evaluateHand(board.concat([card]));
        if (newEval.score <= boardOnly.score) {
          out.push({
            card,
            type: 0,
            label: 'board plays (tie)',
            weight: 0.3,
            dirty: true
          });
          continue;
        }
      }
      if (improvesType) {
        if (pairsBoard) { weight *= 0.75; dirty = true; }
        if (bringsSharedFlush) { weight *= 0.75; dirty = true; }
        if (newEval.type === 1) {
          const pairRank = newMain;
          const pairUsesHole = hole.some(c => RANK_VALS[c[0]] === pairRank);
          if (pairUsesHole && pairRank < topBoardRank) {
            weight *= 0.35;
            dirty = true;
            label = 'under-pair / below-top pair';
          } else if (pairUsesHole && !pairsBoard) {
            weight *= wetBoard ? 0.45 : 0.65;
            dirty = true;
            label = 'top pair on ' + (wetBoard ? 'wet' : 'dry') + ' board';
          }
        }
      } else {
        weight *= 0.5;
        dirty = true;
        if (pairsBoard) weight *= 0.75;
      }
      out.push({
        card,
        type: improvesType ? newEval.type : 0,
        label,
        weight: Math.round(weight * 100) / 100,
        dirty
      });
    }
    if (_outsCache.size > 48) _outsCache.delete(_outsCache.keys().next().value);
    _outsCache.set(cacheKey, out);
    return out;
  };

  const calculateOuts = (hole, board) => {
    const cards = analyzeOutsCards(hole, board);
    if (!cards) return null;
    let total = 0;
    for (const c of cards) total += c.weight;
    return Math.round(total * 10) / 10;
  };

  const OUTS_TYPE_NAMES = { 9: 'royal flush', 8: 'straight flush', 7: 'quads', 6: 'full house', 5: 'flush', 4: 'straight', 3: 'trips', 2: 'two pair', 1: 'pair' };
        const nextCardImprovement = (hole, board) => {
    const cards = analyzeOutsCards(hole, board);
    if (!cards) return null;
    const unseen = 52 - hole.length - board.length;
    return { improve: cards.length, unseen, pct: unseen > 0 ? cards.length / unseen : 0 };
  };
  const _riverOddsCache = new Map();
  const riverImprovementOdds = (hole, board) => {
    if (board.length !== 3) return null;
    const rk = hole.join(',') + '|' + board.join(',');
    if (_riverOddsCache.has(rk)) return _riverOddsCache.get(rk);
    const current = evaluateHand(hole.concat(board)).score;
    const deck = createDeck(hole.concat(board));
    let improve = 0, total = 0;
    for (let i = 0; i < deck.length; i++) {
      for (let j = i + 1; j < deck.length; j++) {
        if (evaluateHand(hole.concat(board, [deck[i], deck[j]])).score > current) improve++;
        total++;
      }
    }
    const rr = { improve, total, pct: total > 0 ? improve / total : 0 };
    if (_riverOddsCache.size > 48) _riverOddsCache.delete(_riverOddsCache.keys().next().value);
    _riverOddsCache.set(rk, rr);
    return rr;
  };
  const analyzeOutsDetail = (hole, board) => {
    const cards = analyzeOutsCards(hole, board);
    if (!cards) return null;
    const buckets = {};
    for (const c of cards) buckets[c.type] = (buckets[c.type] ?? 0) + c.weight;
    return Object.keys(buckets)
      .map(Number)
      .sort((a, b) => buckets[b] - buckets[a])
      .map(t => ({ label: t === 0 ? 'better rank' : OUTS_TYPE_NAMES[t] ?? 'improve', weight: Math.round(buckets[t] * 10) / 10 }))
      .filter(p => p.weight > 0);
  };

  const classifyDraws = (hole, board) => {
    const out = { flushDraw: null, straightDraw: null, backdoorFlush: false, backdoorStraight: false, labels: [] };
    if (!hole || hole.length !== 2 || board.length < 3 || board.length > 4) return out;
    const all = hole.concat(board);
    const suitTally = {};
    for (const c of all) suitTally[c[1]] = (suitTally[c[1]] || 0) + 1;
    const holeSuited = hole[0][1] === hole[1][1];
    let fdSuit = null, fdCount = 0;
    for (const s of [hole[0][1], hole[1][1]]) {
      if ((suitTally[s] || 0) > fdCount) { fdCount = suitTally[s] || 0; fdSuit = s; }
    }
    if (fdSuit && fdCount === 4 && hole.some(c => c[1] === fdSuit)) {
      out.flushDraw = { outs: 13 - fdCount, suit: fdSuit };
    } else if (holeSuited && fdCount === 3 && board.length === 3) {
      out.backdoorFlush = true;
    }
    let rankMaskAll = 0, holeRankMask = 0;
    for (const c of all) rankMaskAll |= (1 << RANK_VALS[c[0]]);
    for (const c of hole) holeRankMask |= (1 << RANK_VALS[c[0]]);
    const aceLow = (m) => (m & (1 << 14)) ? (m | (1 << 1)) : m;
    const present = aceLow(rankMaskAll);
    const holePresent = aceLow(holeRankMask);
    let madeStraight = false;
    const windows = [];
    for (let lo = 1; lo <= 10; lo++) {
      let cnt = 0, holeCnt = 0, missingRank = 0;
      for (let r = lo; r < lo + 5; r++) {
        if (present & (1 << r)) { cnt++; if (holePresent & (1 << r)) holeCnt++; }
        else missingRank = r;
      }
      if (cnt === 5) { madeStraight = true; continue; }
      if (cnt === 4 && holeCnt >= 1 && missingRank >= 2 && missingRank <= 14) windows.push({ lo, missingRank });
    }
    const deadOfRank = (r) => all.filter(c => RANK_VALS[c[0]] === r).length;
    if (!madeStraight && windows.length) {
      const uniq = [...new Set(windows.map(w => w.missingRank))];
      let outsSum = 0;
      for (const r of uniq) outsSum += Math.max(0, 4 - deadOfRank(r));
      let type = null;
      if (uniq.length >= 3) type = 'multi-straight';
      else if (uniq.length === 2) {
        const ranks = [...new Set(all.map(c => RANK_VALS[c[0]]))].sort((a, b) => a - b);
        const consecutive4 = ranks.some((r, i) => ranks.includes(r + 1) && ranks.includes(r + 2) && ranks.includes(r + 3));
        type = consecutive4 ? 'open-ended' : 'double-gutshot';
      } else type = 'gutshot';
      out.straightDraw = { type, outs: outsSum, ranks: uniq.map(r => r === 1 ? 'A' : RANKS[r - 2]) };
    } else if (!madeStraight && board.length === 3) {
      let bd = 0;
      for (let lo = 1; lo <= 10; lo++) {
        let cnt = 0, holeCnt = 0;
        for (let r = lo; r < lo + 5; r++) {
          if (present & (1 << r)) { cnt++; if (holePresent & (1 << r)) holeCnt++; }
        }
        if (cnt === 3 && holeCnt >= 1) bd++;
      }
      out.backdoorStraight = bd > 0;
    }
    if (out.flushDraw) out.labels.push(`flush draw (${out.flushDraw.outs} outs)`);
    if (out.straightDraw) out.labels.push(`${out.straightDraw.type} (${out.straightDraw.outs} outs)`);
    if (out.backdoorFlush) out.labels.push('backdoor flush');
    if (out.backdoorStraight) out.labels.push('backdoor straight');
    if (out.flushDraw && out.straightDraw) out.labels.push('combo draw');
    return out;
  };

  const outsSummary = (hole, board, equityOuts = null) => {
    if (!hole || hole.length !== 2 || (board.length !== 3 && board.length !== 4)) return null;
    const cards = analyzeOutsCards(hole, board) || [];
    const draws = classifyDraws(hole, board);
    const clean = cards.filter(c => !c.dirty);
    return {
      street: board.length === 3 ? 'flop' : 'turn',
      totalCards: cards.length,
      weighted: calculateOuts(hole, board),
      cleanCount: clean.length,
      dirtyCount: cards.length - clean.length,
      straightOuts: cards.filter(c => c.type === 4).length,
      flushOuts: cards.filter(c => c.type === 5).length,
      improveCategory: cards.filter(c => c.type > 0).length,
      improveRank: cards.filter(c => c.type === 0 && c.label !== 'board plays (tie)').length,
      draws,
      equityOuts
    };
  };

  const EQ_OUTS_THRESHOLD = 0.005;
  const _eqOutsCache = new Map();
  const equityImprovingOuts = (hole, board) => {
    if (!hole || hole.length !== 2) return null;
    if (board.length !== 3 && board.length !== 4) return null;
    const key = hole.join(',') + '|' + board.join(',');
    if (_eqOutsCache.has(key)) return _eqOutsCache.get(key);
    const heroIdx = hole.map(c => CARD_IDX[c]);
    const boardIdx = board.map(c => CARD_IDX[c]);
    const dead = new Set(heroIdx.concat(boardIdx));
    const rest = [];
    for (let c = 0; c < 52; c++) if (!dead.has(c)) rest.push(c);
    const M = rest.length;
    const result = { key, baseline: null, cards: [], trials: 0, vs: 'one uniform random opponent', exact: true };
    const buf = new Uint8Array(7);
    const scoreOf = (c1, c2, b) => {
      buf[0] = c1; buf[1] = c2;
      for (let k = 0; k < b.length; k++) buf[2 + k] = b[k];
      return evalFastIdx(buf, 2 + b.length);
    };
    const heroScoreOf = (b) => {
      buf[0] = heroIdx[0]; buf[1] = heroIdx[1];
      for (let k = 0; k < b.length; k++) buf[2 + k] = b[k];
      return evalFastIdx(buf, 2 + b.length);
    };
    const tryStore = (value) => {
      if (_eqOutsCache.size > 24) _eqOutsCache.delete(_eqOutsCache.keys().next().value);
      _eqOutsCache.set(key, value);
      return value;
    };
    if (board.length === 4) {
      let total = 0, hands = 0;
      const perCard = [];
      for (let ti = 0; ti < M; ti++) {
        const t = rest[ti];
        const fullBoard = boardIdx.concat([t]);
        const heroScore = heroScoreOf(fullBoard);
        let sum = 0, n = 0;
        for (let i = 0; i < M; i++) {
          if (i === ti) continue;
          for (let j = i + 1; j < M; j++) {
            if (j === ti) continue;
            const oppScore = scoreOf(rest[i], rest[j], fullBoard);
            sum += heroScore > oppScore ? 1 : heroScore === oppScore ? 0.5 : 0;
            n++;
          }
        }
        perCard.push({ card: CARD_STR[t], equity: n ? sum / n : 0 });
        total += sum; hands += n;
      }
      result.trials = hands;
      result.baseline = hands ? total / hands : 0;
      for (const pc of perCard) {
        if (pc.equity > result.baseline + EQ_OUTS_THRESHOLD) {
          result.cards.push({ card: pc.card, equity: Math.round(pc.equity * 1000) / 1000, delta: Math.round((pc.equity - result.baseline) * 1000) / 1000 });
        }
      }
      return tryStore(result);
    }
    let total = 0, hands = 0;
    const perCard = [];
    for (let ti = 0; ti < M; ti++) {
      const t = rest[ti];
      const restNoT = rest.filter(c => c !== t);
      let tSum = 0, tN = 0;
      for (let ri = 0; ri < restNoT.length; ri++) {
        const r = restNoT[ri];
        const fullBoard = boardIdx.concat([t, r]);
        const heroScore = heroScoreOf(fullBoard);
        for (let i = 0; i < restNoT.length; i++) {
          if (restNoT[i] === r) continue;
          for (let j = i + 1; j < restNoT.length; j++) {
            if (restNoT[j] === r) continue;
            const oppScore = scoreOf(restNoT[i], restNoT[j], fullBoard);
            tSum += heroScore > oppScore ? 1 : heroScore === oppScore ? 0.5 : 0;
            tN++;
          }
        }
      }
      perCard.push({ card: CARD_STR[t], equity: tN ? tSum / tN : 0 });
      total += tSum; hands += tN;
    }
    result.trials = hands;
    result.baseline = hands ? total / hands : 0;
    for (const pc of perCard) {
      if (pc.equity > result.baseline + EQ_OUTS_THRESHOLD) {
        result.cards.push({ card: pc.card, equity: Math.round(pc.equity * 1000) / 1000, delta: Math.round((pc.equity - result.baseline) * 1000) / 1000 });
      }
    }
    return tryStore(result);
  };

  const OUTS_WORKER_SRC = `
const RANKS = ['2','3','4','5','6','7','8','9','T','J','Q','K','A'];
const SUITS = ['\\u2660','\\u2665','\\u2666','\\u2663'];
const RANK_VALS = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'T':10,'J':11,'Q':12,'K':13,'A':14};
const CARD_STR = [];
const RANK_OF = new Uint8Array(52);
const SUIT_OF = new Uint8Array(52);
const CARD_IDX = {};
(() => { let i = 0; for (const r of RANKS) for (const s of SUITS) { const c = r + s; CARD_STR[i] = c; RANK_OF[i] = RANK_VALS[r]; SUIT_OF[i] = SUITS.indexOf(s); CARD_IDX[c] = i; i++; } })();
const _rc = new Uint8Array(15);
const _sc = new Uint8Array(4);
const _sm = new Uint16Array(4);
const straightHighFromMask = ${straightHighFromMask.toString()};
const evalFastIdx = ${evalFastIdx.toString()};
const EQ_OUTS_THRESHOLD = 0.005;
const _eqOutsCache = new Map();
const equityImprovingOuts = ${equityImprovingOuts.toString()};
self.onmessage = (e) => {
  const m = e && e.data;
  if (!m || m.kind !== 'outsEq') return;
  try {
    const res = equityImprovingOuts(m.hole, m.board);
    self.postMessage({ kind: 'outsEqDone', key: m.key, result: res });
  } catch (err) {
    self.postMessage({ kind: 'outsEqDone', key: m.key, result: null, error: String(err && err.message || err) });
  }
};
`;

  let outsWorker = null;
  let outsWorkerUrl = null;
  const outsWorkerPending = new Map();
  const terminateOutsWorker = () => {
    try { if (outsWorker) outsWorker.terminate(); } catch { }
    outsWorker = null;
    if (outsWorkerPending.size) {
      for (const resolve of outsWorkerPending.values()) resolve(null);
      outsWorkerPending.clear();
    }
  };
  const outsWorkerRequest = (hole, board) => new Promise((resolve) => {
    const key = hole.join(',') + '|' + board.join(',');
    try {
      if (typeof Worker === 'undefined' || typeof Blob === 'undefined'
        || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') {
        resolve(equityImprovingOuts(hole, board));
        return;
      }
      if (!outsWorker) {
        const blob = new Blob([OUTS_WORKER_SRC], { type: 'text/javascript' });
        outsWorkerUrl = URL.createObjectURL(blob);
        outsWorker = new Worker(outsWorkerUrl);
        outsWorker.onmessage = (e) => {
          const m = e && e.data;
          if (!m || m.kind !== 'outsEqDone') return;
          const waiter = outsWorkerPending.get(m.key);
          if (waiter) { outsWorkerPending.delete(m.key); waiter(m.result || null); }
        };
        outsWorker.onerror = () => { terminateOutsWorker(); };
      }
      if (outsWorkerPending.has(key)) { resolve(null); return; }
      outsWorkerPending.set(key, resolve);
      outsWorker.postMessage({ kind: 'outsEq', key, hole, board });
    } catch {
      resolve(equityImprovingOuts(hole, board));
    }
  });

  const evaluateRelativeStrength = (hole, board, evalResult) => {
    if (!hole?.length) return '-';
    const r1 = RANK_VALS[hole[0][0]], r2 = RANK_VALS[hole[1][0]];
    if (!board?.length) {
      if (r1 === r2) return 'Pocket Pair';
      return `${RANKS[Math.max(r1, r2) - 2]} High`;
    }
    const boardRanks = board.map(c => RANK_VALS[c[0]]).sort((a, b) => b - a);
    if (evalResult.type >= 4) {
      const names = { 4: 'Straight', 5: 'Flush', 6: 'Full House', 7: 'Quads', 8: 'Straight Flush', 9: 'Royal Flush' };
      return names[evalResult.type] ?? 'Monster';
    }
    if (evalResult.type === 3) return (r1 === r2 && boardRanks.includes(r1)) ? 'Set' : 'Trips';
    if (evalResult.type === 2) {
      const pairsOnBoard = boardRanks.filter((item, idx) => boardRanks.indexOf(item) !== idx);
      if (pairsOnBoard.length > 0) {
        if (r1 !== r2 && [r1, r2].includes(pairsOnBoard[0])) return 'Trips (Board Pair)';
        if (r1 === r2 && r1 < pairsOnBoard[0]) return 'Two Pair (Counterfeited)';
      }
      if (r1 !== r2 && boardRanks.includes(r1) && boardRanks.includes(r2)) return 'Top Two Pair';
      return 'Two Pair';
    }
    if (evalResult.type === 1) {
      if (r1 === r2) {
        if (r1 > boardRanks[0]) return 'Overpair';
        if (r1 === boardRanks[0]) return 'Top Pair';
        if (boardRanks.length > 1 && r1 > boardRanks[1]) return '2nd Pair';
        return 'Underpair';
      }
      const pairedRank = boardRanks.includes(r1) ? r1 : (boardRanks.includes(r2) ? r2 : null);
      if (!pairedRank) return 'Board Pair';
      if (pairedRank === boardRanks[0]) {
        const kicker = pairedRank === r1 ? r2 : r1;
        if (kicker >= 13) return 'TPTK (Top Kicker)';
        if (kicker >= 10) return 'Top Pair';
        return 'Top Pair (Weak Kicker)';
      }
      if (boardRanks.length > 1 && pairedRank === boardRanks[1]) return 'Middle Pair';
      return 'Bottom Pair';
    }
    const allRanks = [r1, r2, ...boardRanks].sort((a, b) => b - a);
    return `${RANKS[allRanks[0] - 2]} High`;
  };

  const detectBlockers = (hole, board) => {
    if (!hole?.length || hole.length < 2) return '-';
    if (!board?.length || board.length < 3) return 'N/A (Preflop)';
    const boardSuits = board.map(c => c[1]);
    const suitCounts = {};
    for (const s of boardSuits) suitCounts[s] = (suitCounts[s] ?? 0) + 1;
    const blockers = [];
    for (const suit in suitCounts) {
      if (suitCounts[suit] >= 3) {
        const holeWithSuit = hole.filter(c => c[1] === suit);
        if (holeWithSuit.length > 0) {
          const topRank = Math.max(...holeWithSuit.map(c => RANK_VALS[c[0]]));
          if (topRank === 14) blockers.push(`Nut ${suit} Blocker`);
          else if (topRank === 13) blockers.push(`K${suit} Blocker`);
        }
      }
    }
    const boardRanks = [...new Set(board.map(c => RANK_VALS[c[0]]))].sort((a, b) => a - b);
    if (boardRanks.length >= 3) {
      for (let i = 0; i <= boardRanks.length - 3; i++) {
        if (boardRanks[i + 2] - boardRanks[i] <= 4) {
          for (const hc of hole) {
            const hr = RANK_VALS[hc[0]];
            if (hr >= boardRanks[i] - 2 && hr <= boardRanks[i + 2] + 2 && !boardRanks.includes(hr)) {
              if (!blockers.includes('Straight Blocker')) blockers.push('Straight Blocker');
            }
          }
        }
      }
    }
    return blockers.length ? blockers.join(', ') : 'None';
  };

  let lastPositionExact = true;
  let lastPositionHu = false;
  let lastPositionKnown = true;

  const positionFromDistance = (dist, total, headsUp) => {
    if (headsUp) return dist === 0 ? 'BTN' : 'BB';
    if (dist === 0) return 'BTN';
    if (dist === 1) return 'SB';
    if (dist === 2) return 'BB';
    if (dist === 3) return 'UTG';
    if (dist === total - 1) return 'CO';
    return 'MP';
  };

  const SEAT_POSITION_INDEX_RE = /(?:^|\s)(?:playerPositioner|playerPosition)-(\d+)(?:___|\s|$)/i;
  const seatPositionIndex = (seat) => {
    let node = seat, hops = 0;
    while (node && node.nodeType === 1 && hops < 4) {
      const m = getClassString(node).match(SEAT_POSITION_INDEX_RE);
      if (m) return Number(m[1]);
      node = node.parentElement;
      hops++;
    }
    return null;
  };

  const dealerSeatIndex = (ring) => {
    const me = findOwnSeat();
    const dealerCandidates = document.querySelectorAll('[class*="dealerButton"], [class*="btnDealer"], [class*="dealer___"], [class*="dealer"], [aria-label*="dealer" i]');
    for (const dealer of dealerCandidates) {
      if (dealer.closest?.('#tnp-dossier')) continue;
      const dealerIdx = ring.findIndex(s => s.contains(dealer) || s === dealer);
      if (dealerIdx !== -1) return dealerIdx;
      const markerCls = getClassString(dealer);
      if (me && /(?:^|\s)position-self(?:___|\s|$)/i.test(markerCls)) {
        const meIdx = ring.findIndex(s => s === me || s.contains(me) || me.contains(s));
        if (meIdx !== -1) return meIdx;
        continue;
      }
      const dm = markerCls.match(/(?:^|\s)position-(\d+)(?:___|\s|$)/i);
      if (dm) {
        const dealerVis = Number(dm[1]);

        const indexed = ring
          .map((s) => ({ seat: s, vis: seatPositionIndex(s) ?? ((me && (s === me || s.contains(me) || me.contains(s))) ? 0 : null) }))
          .filter(x => x.vis !== null)
          .sort((a, b) => a.vis - b.vis);
        const at = indexed.findIndex(x => x.vis === dealerVis);
        if (at !== -1) return ring.indexOf(indexed[at].seat);
      }
    }
    return null;
  };

  const detectPosition = () => {

    const seats = getAllSeats();
    const me = findOwnSeat();
    if (me && seats.length >= 2) {

      const occupied = seats.filter(s => !isSeatEmpty(s));
      const ring = occupied.length >= 2 ? occupied : seats;
      lastPositionHu = occupied.length === 2;
      const myIdx = ring.findIndex(s => s === me || s.contains(me) || me.contains(s));
      if (myIdx !== -1) {
        const dealerIdx = dealerSeatIndex(ring);
        if (dealerIdx !== null) {
          lastPositionExact = true;
          lastPositionKnown = true;
          const total = ring.length;
          return positionFromDistance((myIdx - dealerIdx + total) % total, total, lastPositionHu);
        }
      }

      const heroPlayer = getHeroIdentity();
      if (heroPlayer) {
        const byLog = positionFromBlindPosts(parseActionLog(), heroPlayer.name, lastPositionHu);
        if (byLog) { lastPositionExact = true; lastPositionKnown = true; return byLog; }
      }
    }

    lastPositionExact = false;
    lastPositionKnown = false;
    lastPositionHu = false;
    return 'MP';
  };

  const opponentSeatPositions = () => {
    const out = {};
    const seats = getAllSeats();
    const me = findOwnSeat();
    if (!me || seats.length < 2) return out;
    const occupied = seats.filter(s => !isSeatEmpty(s));
    const ring = occupied.length >= 2 ? occupied : seats;
    const hu = occupied.length === 2;
    const msgs = parseActionLog();
    const dealerIdx = dealerSeatIndex(ring);
    for (const seat of ring) {
      if (isOwnPlayerSeat(seat, me)) continue;
      if (!isOpponentActive(seat)) continue;
      const player = getPlayerName(seat);
      if (!player) continue;
      const byLog = positionFromBlindPosts(msgs, player.name, hu);
      if (byLog) { out[player.name] = byLog; continue; }
      if (dealerIdx === null) continue;
      const idx = ring.indexOf(seat);
      out[player.name] = positionFromDistance((idx - dealerIdx + ring.length) % ring.length, ring.length, hu);
    }
    return out;
  };

  const POSITION_DETAILS = {
    BTN: 'Button (late)', SB: 'Small blind', BB: 'Big blind',
    UTG: 'UTG (early)', MP: 'Middle position', CO: 'Cutoff (late)'
  };
  const positionLabel = (pos, exact) => {

    if (!lastPositionKnown) return 'Unread · no button or blinds found; advice assumes a middle seat';
    let d = POSITION_DETAILS[pos] ?? 'Unknown seat';

    if (lastPositionHu && pos === 'BTN') d = 'Button / SB (heads-up)';
    else if (lastPositionHu && pos === 'BB') d = 'Big blind (heads-up)';
    return exact === false ? `${pos} (est.) · ${d}` : `${pos} · ${d}`;
  };

  const BB_POST_RE = /post(?:ed|s)?\s+(?:the\s+)?big\s+blind(?:\s+of)?[^0-9$]*\$?\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)?/i;
  const SB_POST_RE = /post(?:ed|s)?\s+(?:the\s+)?small\s+blind(?:\s+of)?[^0-9$]*\$?\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)?/i;

  const WINNER_LINE_RE = /(?:wins?\s|won\s|takes?\s+(?:the\s+)?pot|pot\s+awarded|scoops?\s)/i;

  const raiseContextFromMessages = (msgs) => {
    if (!msgs || !msgs.length) return { level: 0, bbAmount: 0, reliable: false };
    let lastWin = -1;
    for (let i = msgs.length - 1; i >= 0; i--) {
      if (WINNER_LINE_RE.test(msgs[i])) { lastWin = i; break; }
    }
    let bbIdx = -1, bbAmount = 0;
    for (let i = msgs.length - 1; i > lastWin; i--) {
      const m = msgs[i].match(BB_POST_RE);
      if (m) { bbAmount = m[1] ? parseTornNumber(m[1]) : 0; bbIdx = i; break; }
    }
    let startIdx;
    if (bbIdx >= 0) startIdx = bbIdx + 1;
    else if (lastWin >= 0) startIdx = lastWin + 1;
    else return { level: 0, bbAmount: 0, reliable: false };
    let raises = 0;
    for (let i = startIdx; i < msgs.length; i++) {
      const msg = msgs[i];
      const ev = parseActionMessage(msg);
      if (!ev) {
        if (/\b(flop|turn|river)\b/i.test(msg)) break;
        continue;
      }
      if (/\b(flop|turn|river)\b/i.test(msg)) continue;

      if (ev.action === 'allin' || /\ball[\s-]?in\b/i.test(ev.rest ?? '')) return { level: 3, bbAmount, reliable: true };
      if (ev.action === 'raise' || ev.action === 'bet') raises++;
    }
    return { level: Math.min(3, raises), bbAmount, reliable: true };
  };

  const detectRaiseContext = () => {
    try {
      const rc = raiseContextFromMessages(parseActionLog());
      const bbAmount = rc.bbAmount > 0 ? rc.bbAmount : (handTracker.bbAmount || 0);
      return { level: rc.level, bbAmount, reliable: rc.reliable };
    } catch {  }
    return { level: 0, bbAmount: 0, reliable: false };
  };

  const analyzeBoardTexture = (board) => {
    if (!board || board.length < 3) return [];
    const tags = [];
    const suits = board.map(c => c[1]);
    const ranks = board.map(c => RANK_VALS[c[0]]).sort((a, b) => b - a);
    const suitCounts = {};
    for (const s of suits) suitCounts[s] = (suitCounts[s] ?? 0) + 1;
    const maxSuit = Math.max(...Object.values(suitCounts));

    if (maxSuit >= 5) tags.push('Board Flush');
    else if (maxSuit >= 4) tags.push('4-Flush');
    else if (maxSuit === 3 && board.length === 3) tags.push('Monotone');
    else if (maxSuit === 3) tags.push('3-Flush');

    const rankSet = new Set(ranks);
    if (rankSet.has(14)) rankSet.add(1);
    const inWindow = (lo) => {
      let n = 0;
      for (let r = lo; r < lo + 5; r++) if (rankSet.has(r)) n++;
      return n;
    };
    let bestWindow = 0;
    for (let lo = 1; lo <= 10; lo++) bestWindow = Math.max(bestWindow, inWindow(lo));

    if (board.length === 3) {
      if (bestWindow >= 3) tags.push('Connected');
    } else {
      if (bestWindow >= 5) tags.push('Straight-Board');
      else if (bestWindow >= 4) tags.push('4-Straight');
      const uniqueRanks = [...new Set(ranks)];
      const range = uniqueRanks[0] - uniqueRanks[uniqueRanks.length - 1];
      if (bestWindow >= 4 || range <= 5) tags.push('Connected');
    }

    const rankCounts = {};
    for (const r of ranks) rankCounts[r] = (rankCounts[r] ?? 0) + 1;
    const pairs = Object.values(rankCounts).filter(c => c >= 2).length;
    if (pairs >= 1) tags.push('Paired');
    if (pairs >= 2) tags.push('Double Paired');

    if (board.length === 3 && maxSuit === 2) tags.push('Two-tone');
    const wetNow = (board.length === 3 && (maxSuit >= 3 || bestWindow >= 3))
      || (board.length > 3 && (maxSuit >= 3 || bestWindow >= 4));
    if (wetNow && pairs === 0) tags.push('Wet');

    if (tags.length === 0) tags.push('Dry');
    return tags;
  };

  const boardThreatExtras = (hole, board) => {
    const out = { overcards: 0, overcardThreat: false, counterfeitRisk: false, fullHouseThreat: false, notes: [] };
    if (!Array.isArray(hole) || hole.length !== 2 || !Array.isArray(board) || board.length < 3) return out;
    const holeRanks = hole.map(c => RANK_VALS[c[0]]);
    const topHole = Math.max(...holeRanks);
    const boardRanks = board.map(c => RANK_VALS[c[0]]);
    const heroEval = evaluateHand(hole.concat(board));
    out.overcards = boardRanks.filter(r => r > topHole).length;
    if (out.overcards > 0 && heroEval.type <= 1) {
      out.overcardThreat = true;
      out.notes.push(`${out.overcards} overcard${out.overcards === 1 ? '' : 's'} above your top card`);
    }
    const rankCounts = {};
    for (const r of boardRanks) rankCounts[r] = (rankCounts[r] || 0) + 1;
    const pairedRanks = Object.keys(rankCounts).map(Number).filter(r => rankCounts[r] >= 2);
    const tripsOnBoard = Object.values(rankCounts).some(c => c >= 3);
    if (heroEval.type < 6 && (tripsOnBoard || pairedRanks.length >= 2
      || (pairedRanks.length >= 1 && board.length >= 4 && new Set(boardRanks).size <= 3))) {
      out.fullHouseThreat = true;
      out.notes.push(tripsOnBoard ? 'board trips: any pocket pair boats' : 'board pairs: one pairing card boats someone');
    }
    if (heroEval.type === 4 && board.length >= 4) {
      let boardWindow = 0;
      const bset = new Set(boardRanks);
      if (bset.has(14)) bset.add(1);
      for (let lo = 1; lo <= 10; lo++) {
        let n = 0;
        for (let r = lo; r < lo + 5; r++) if (bset.has(r)) n++;
        boardWindow = Math.max(boardWindow, n);
      }
      if (boardWindow >= 4) {
        out.counterfeitRisk = true;
        out.notes.push('straight on the board: one card re-splits or overtakes it');
      }
    }
    if (heroEval.type === 2 && holeRanks.every(r => boardRanks.includes(r))) {
      out.counterfeitRisk = true;
      out.notes.push('both pairs use one hole card: a new board pair plays without you');
    }
    return out;
  };

  const boardDanger = (hole, board) => {
    const out = {
      flushComplete: false, heroHasFlush: false, heroFlushWeak: false, boardFlush: false,
      straightComplete: false, heroHasStraight: false, heroStraightLow: false,
      boardPaired: false, heroClaimsPair: false, hard: false,
      tag: '', message: ''
    };
    if (!Array.isArray(hole) || hole.length !== 2 || !Array.isArray(board) || board.length < 3) return out;

    const suitCounts = {};
    let topSuit = null, topN = 0;
    for (const c of board) {
      const s = c[1];
      suitCounts[s] = (suitCounts[s] ?? 0) + 1;
      if (suitCounts[s] > topN) { topN = suitCounts[s]; topSuit = s; }
    }
    if (topN >= 5) {

      out.flushComplete = true;
      out.heroHasFlush = true;
      out.boardFlush = true;
    } else if (topN === 4) {
      out.flushComplete = true;
      const heroSuitRanks = hole.filter(c => c[1] === topSuit).map(c => RANK_VALS[c[0]]);
      out.heroHasFlush = heroSuitRanks.length > 0;
      if (out.heroHasFlush) {
        const heroHigh = Math.max(...heroSuitRanks);
        const boardRanks = board.filter(c => c[1] === topSuit).map(c => RANK_VALS[c[0]]);

        let topAvailable = 0;
        for (let r = 14; r >= 2; r--) {
          if (!boardRanks.includes(r)) { topAvailable = r; break; }
        }
        out.heroFlushWeak = heroHigh < topAvailable;
      }
    }

    const boardRankSet = new Set(board.map(c => RANK_VALS[c[0]]));
    const windowSet = new Set(boardRankSet);
    if (windowSet.has(14)) windowSet.add(1);

    const holeRanks = hole.map(c => RANK_VALS[c[0]]);
    const holeCovers = (m, i) => {
      const hr = holeRanks[i];
      return hr === m || (m === 1 && hr === 14);
    };
    let boardPlayHigh = 0;
    let heroBestHigh = 0;
    const oneCardHighs = [];
    for (let lo = 1; lo <= 10; lo++) {
      const missing = [];
      for (let r = lo; r < lo + 5; r++) if (!windowSet.has(r)) missing.push(r);
      if (missing.length === 0) boardPlayHigh = Math.max(boardPlayHigh, lo + 4);
      if (missing.length === 1) oneCardHighs.push(lo + 4);
      if (missing.length === 0
        || (missing.length === 1 && (holeCovers(missing[0], 0) || holeCovers(missing[0], 1)))
        || (missing.length === 2 && ((holeCovers(missing[0], 0) && holeCovers(missing[1], 1))
          || (holeCovers(missing[1], 0) && holeCovers(missing[0], 1))))) {
        heroBestHigh = Math.max(heroBestHigh, lo + 4);
      }
    }
    if (boardPlayHigh > 0) {
      out.straightComplete = true;
      out.heroHasStraight = true;
    } else if (oneCardHighs.length > 0) {
      out.straightComplete = true;
      out.heroHasStraight = heroBestHigh > 0;
    }

    out.heroStraightLow = out.heroHasStraight && oneCardHighs.some(h => h > heroBestHigh);
    const straightByBoard = boardPlayHigh > 0 && heroBestHigh <= boardPlayHigh;

    const pairCounts = {};
    let pairRank = 0;
    for (const c of board) {
      const r = RANK_VALS[c[0]];
      pairCounts[r] = (pairCounts[r] ?? 0) + 1;
      if (pairCounts[r] >= 2 && r > pairRank) pairRank = r;
    }
    if (pairRank > 0) {
      out.boardPaired = true;

      const heroType = evaluateHand(hole.concat(board)).type;
      out.heroClaimsPair = hole.some(c => RANK_VALS[c[0]] === pairRank) || heroType >= 7;
    }

    const flushDanger = out.boardFlush || (out.flushComplete && (!out.heroHasFlush || out.heroFlushWeak));
    const straightDanger = out.straightComplete && (!out.heroHasStraight || out.heroStraightLow);
    const pairDanger = out.boardPaired && !out.heroClaimsPair;
    out.hard = flushDanger || straightDanger;

    Object.assign(out, boardThreatExtras(hole, board));

    if (out.boardFlush) {
      out.tag = 'board flush';
      out.message = 'the board itself is a flush, so every player has the same hand and pressure cannot win the pot';
    } else if (out.flushComplete && !out.heroHasFlush) {
      out.tag = 'flush';
      out.message = 'four cards of one suit are on board and you hold none of that suit; any single card of it makes a flush that beats you';
    } else if (out.flushComplete && out.heroFlushWeak) {
      out.tag = 'weak flush';
      out.message = 'you hold a flush, but higher cards of that suit are still live and any of them beats you';
    } else if (out.straightComplete && !out.heroHasStraight) {
      out.tag = 'straight';
      out.message = 'the board shows four straight rungs your cards cannot complete; any single filling card makes a straight that beats you';
    } else if (out.straightComplete && out.heroStraightLow) {
      out.tag = 'idiot-end straight';
      out.message = straightByBoard
        ? 'the board made the straight, but a single higher card still outranks it'
        : 'you filled the bottom of the straight; any higher completing card beats you';
    } else if (pairDanger) {
      out.tag = 'board pair';
      out.message = 'the board is paired; an opponent holding that rank already has trips or better';
    }
    return out;
  };

  const boardRisk = (hole, board) => {
    const out = {
      suitThreat: false, heroFlushDraw: false, heroMadeFlush: false,
      straightThreat: false, heroStraightDraw: false,
      tag: '', message: ''
    };
    if (!Array.isArray(hole) || hole.length !== 2 || !Array.isArray(board) || board.length < 3) return out;

    const suitCounts = {};
    let topSuit = null, topN = 0;
    for (const c of board) {
      const s = c[1];
      suitCounts[s] = (suitCounts[s] || 0) + 1;
      if (suitCounts[s] > topN) { topN = suitCounts[s]; topSuit = s; }
    }
    const holeInSuit = hole.filter(c => c[1] === topSuit).length;
    out.heroMadeFlush = (topN >= 3 && holeInSuit >= 2) || (topN >= 4 && holeInSuit >= 1);
    out.heroFlushDraw = topN === 3 && holeInSuit === 1;
    out.suitThreat = topN === 3 && !out.heroMadeFlush && !out.heroFlushDraw;

    const boardSet = new Set(board.map(c => RANK_VALS[c[0]]));
    if (boardSet.has(14)) boardSet.add(1);
    const withHole = new Set(boardSet);
    const holeSet = new Set();
    for (const c of hole) {
      const r = RANK_VALS[c[0]];
      withHole.add(r);
      holeSet.add(r);
      if (r === 14) { withHole.add(1); holeSet.add(1); }
    }
    const inSpan = (set, lo, width) => {
      let n = 0;
      for (let r = lo; r < lo + width; r++) if (set.has(r)) n++;
      return n;
    };
    let boardDense = 0;
    for (let lo = 1; lo <= 11; lo++) boardDense = Math.max(boardDense, inSpan(boardSet, lo, 4));
    let heroConnects = false;
    for (let lo = 1; lo <= 10 && !heroConnects; lo++) {
      heroConnects = inSpan(withHole, lo, 5) >= 4 && inSpan(holeSet, lo, 5) >= 1;
    }
    out.heroStraightDraw = heroConnects;
    out.straightThreat = boardDense >= 3 && !out.heroStraightDraw;

    const suitName = topSuit === '♠' ? 'spades' : topSuit === '♥' ? 'hearts'
      : topSuit === '♦' ? 'diamonds' : 'clubs';
    if (out.suitThreat && out.straightThreat) {
      out.tag = 'flush and straight risk';
      out.message = `three ${suitName} and connected rungs, none of them yours: a bet here usually means a made hand`;
    } else if (out.suitThreat) {
      out.tag = 'flush risk';
      out.message = `three ${suitName} on board and you hold none: a bet here often IS the flush`;
    } else if (out.straightThreat) {
      out.tag = 'straight risk';
      out.message = 'the board runs connected and your cards do not bridge it: a bet here often IS the straight';
    }
    return out;
  };

  const mdfVsBet = (potTotal, toCall) => {
    if (!(potTotal > 0) || !(toCall > 0)) return null;
    const potBefore = potTotal - toCall;
    if (potBefore <= 0) return null;
    return Math.min(1, potBefore / potTotal);
  };

  const callEv = (equity, potTotal, toCall) => {
    if (equity === null || equity === undefined || !(potTotal > 0) || !(toCall > 0)) return null;
    return equity * potTotal - (1 - equity) * toCall;
  };

  const shoveEv = (equity, pot, invest, foldEq, eqCalled = null) => {
    if (!(pot > 0) || !(invest > 0) || !(foldEq >= 0) || !(foldEq <= 1)) return null;
    const eq = eqCalled !== null ? eqCalled : equity * 0.85;
    return foldEq * pot + (1 - foldEq) * (eq * (pot + 2 * invest) - invest);
  };

  const evOptions = (equity, pot, toCall, stack, feStat = null) => {
    const out = { fold: 0, call: callEv(equity, pot, toCall), shove: null, shoveFe: null, shoveAssumed: null };
    if (equity === null || equity === undefined) return out;
    if (pot > 0 && stack > 0 && toCall === 0) {
      const invest = Math.min(stack, Math.round(pot * 0.75));
      if (invest > 0) {
        out.shoveAssumed = shoveEv(equity, pot, invest, 0.40);
        if (feStat !== null) {
          out.shove = shoveEv(equity, pot, invest, feStat);
          out.shoveFe = feStat;
        }
      }
    }
    return out;
  };

  const eqrFactor = (position, activeOpps, street) => {
    let f = 1;
    if (street === 'Flop' || street === 'Turn') {
      if (position === 'SB' || position === 'BB' || position === 'UTG') f -= 0.07;
      else if (position === 'BTN' || position === 'CO') f += 0.04;
      if (activeOpps >= 3) f -= 0.06;
    }
    return Math.min(1.04, Math.max(0.87, f));
  };

  const geometricBetFraction = (pot, effStack, streetsLeft) => {
    if (!(pot > 0) || !(effStack > 0) || !(streetsLeft >= 1)) return null;
    const f = 0.5 * (Math.pow(1 + (2 * effStack) / pot, 1 / streetsLeft) - 1);
    return (f >= 0.2 && f <= 1.2) ? f : null;
  };

  const sprVsPot = (stack, pot) => (stack > 0 && pot > 0) ? stack / pot : null;

  const bluffBreakEven = (pct) => pct / (100 + pct);

  const RIVER_BET_MIN_FACES = 8;
  const RIVER_OVERFOLD_MARGIN = 0.04;
  const riverOverfoldRead = (p, pot, effStack = 0) => {
    if (!p || !(pot > 0)) return null;
    if ((p.handsObserved || 0) < 25) return null;
    const faced = p.riverBetFaced || 0;
    const folded = p.riverBetFolded || 0;
    if (faced < RIVER_BET_MIN_FACES) return null;
    const lb = wilsonCI(folded, faced).lower;
    const bet = Math.min(pot * 0.75, effStack > 0 ? effStack : pot * 0.75);
    const be = bet / (pot + bet);
    if (lb < be + RIVER_OVERFOLD_MARGIN) return null;
    const ev = lb * pot - (1 - lb) * bet;
    if (ev <= 0) return null;
    return { name: p.name, pot, bet, faced, folded, rate: folded / faced, lb, be, ev };
  };

  const overfoldSizingText = (of) => {
    if (!of || !(of.pot > 0)) return '';
    const pct = Math.round(of.bet / of.pot * 100);
    return `Bluff $${Math.round(of.bet).toLocaleString()} (~${pct}% pot) · needs folds ${Math.round(of.be * 100)}%`;
  };

  const ruleOfFourTwo = (outs, street) => {
    if (outs === null || outs === undefined || outs < 1) return null;
    if (street === 'Flop') return Math.min(100, Math.round(outs * 4));
    if (street === 'Turn') return Math.min(100, Math.round(outs * 2));
    return null;
  };

  const getBetSizingAdvice = (equity, pot, toCall, activeOpps, street, boardTexture = [], bbAmount = 0, raiseLevel = 0, effStack = 0, danger = null, risk = null, oppAggressive = false, legalFloor = 0) => {
    if (!equity || equity === null) return null;
    const fairShare = 1 / (activeOpps + 1);
    const prof = strategyProfile();
    const isStrong = equity > fairShare * 1.4 * prof.value;
    const isMarginal = equity > fairShare * 0.9 * prof.value;
    const liftToLegal = (target) => {
      if (!(legalFloor > 0) || !(target > 0)) return target;
      if (target >= legalFloor) return target;
      if (effStack > 0 && legalFloor > effStack) return effStack;
      return legalFloor;
    };

    if (toCall > 0 && pot > 0) {
      const potOdds = toCall / (pot + toCall);
      if (equity < potOdds) return null;
    }

    if (street === 'Preflop') {
      if (!isStrong) return null;

      if (raiseLevel >= 1 && toCall > 0) {
        const target = liftToLegal(Math.round(toCall * 3));
        if (effStack > 0 && target >= effStack) return `All-in $${effStack.toLocaleString()} (3-bet)`;
        return `3-Bet to ~$${target.toLocaleString()} (3x their raise)`;
      }
      if (bbAmount > 0) {
        const target = liftToLegal(Math.round(bbAmount * 3.5));
        if (effStack > 0 && target >= effStack) return `All-in $${effStack.toLocaleString()} (open)`;
        return `Open ~$${target.toLocaleString()} (3.5x BB)`;
      }
      return 'Raise 3-4x BB';
    }

    if (danger && danger.tag) {
      if (toCall > 0) return null;
      return `Check / pot control: ${danger.message ?? danger.tag + ' risk on board'}`;
    }

    const pressured = !!(risk && (risk.suitThreat || risk.straightThreat));
    if (pressured && oppAggressive && equity <= fairShare * 1.8) {
      if (toCall > 0) return null;
      return `Check / pot control: ${risk.message}`;
    }

    if (!(pot > 0)) return null;

    const wet = boardTexture.some(t => ['3-Flush', '4-Flush', 'Monotone', 'Connected'].includes(t));
    const streetsLeft = street === 'Flop' ? 3 : street === 'Turn' ? 2 : 1;

    const spr = effStack > 0 ? effStack / pot : 0;
    const foldsNote = (pct) => ` · needs folds ${Math.round(bluffBreakEven(pct) * 100)}%`;

    if (isStrong) {

      const pct = wet ? 75 : 50;
      const target = liftToLegal(Math.round(pot * pct / 100));

      if (effStack > 0 && target >= effStack) {
        const allInPct = Math.round(effStack / pot * 100);
        return `All-in $${effStack.toLocaleString()} (~${allInPct}% pot)${wet ? ' · charge draws' : ''}${foldsNote(allInPct)}`;
      }
      let geoNote = '';
      if (spr >= 2) {
        const geo = geometricBetFraction(pot, effStack, streetsLeft);
        if (geo && Math.abs(geo - pct / 100) >= 0.08) {
          geoNote = ` · geometric ${Math.round(geo * 100)}%/street`;
        }
      }
      return `Bet ${pct}% pot ($${target.toLocaleString()})${wet ? ' · charge draws' : ''}${foldsNote(pct)}${geoNote}`;
    }
    if (isMarginal && toCall === 0) {
      const pct = wet ? 50 : 33;
      const target = liftToLegal(Math.round(pot * pct / 100));
      if (effStack > 0 && target >= effStack) {
        const allInPct = Math.round(effStack / pot * 100);
        return `All-in $${effStack.toLocaleString()} (~${allInPct}% pot)${foldsNote(allInPct)}`;
      }
      return `Bet ${pct}% pot ($${target.toLocaleString()})${foldsNote(pct)}`;
    }
    return null;
  };

  const parseActionMessage = (msg) => {
    if (!msg) return null;
    const normalized = msg.replace(/\s+/g, ' ').trim();
    const m = normalized.match(/^(.+?)\s+(rais(?:ed|es)?|call(?:ed|s)?|check(?:ed|s)?|bets?|bet|fold(?:ed|s)?|post(?:ed|s)?|(?:went|goes|is)\s+all[\s-]?in|show(?:ed|s)?|wins?|won|takes?\s+(?:the\s+)?pot|scoops?|reveal(?:ed|s)?|muck(?:ed|s)?)\b(.*)$/i);
    if (!m) return null;
    const name = m[1].trim();
    if (!name || !isPlausiblePlayerName(name)) return null;
    const verb = m[2].toLowerCase();
    const rest = m[3] ?? '';
    const presentTense = /^(?:calls?|checks?|bets?|folds?|raises?|posts?)$/i.test(verb)
      ? /^(?:calls|checks|bets|folds|raises|posts)$/i.test(verb)
      : false;
    if (presentTense && !/\$/.test(rest) && /\S/.test(rest)) return null;
    let action = null;
    if (/^rais/.test(verb)) action = 'raise';
    else if (/^call/.test(verb)) action = 'call';
    else if (/^check/.test(verb)) action = 'check';
    else if (/^bet/.test(verb)) action = 'bet';
    else if (/^fold/.test(verb)) action = 'fold';
    else if (/all[\s-]?in/.test(verb)) action = 'allin';
    else if (/^post/.test(verb)) {
      if (/big\s+blind/i.test(rest)) action = 'post_bb';
      else if (/small\s+blind/i.test(rest)) action = 'post_sb';
      else action = 'post';
    }
    else if (/^(show|reveal)/.test(verb)) action = 'show';
    else if (/^(win|won|scoop)|takes?\s+(?:the\s+)?pot/.test(verb)) action = 'win';
    else if (/^muck/.test(verb)) action = 'muck';
    if (!action) return null;

    const raiseToMatch = (action === 'raise' || action === 'allin')
      ? rest.match(/\bto\s+\$?\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)/i)
      : null;
    const amtMatch = raiseToMatch ?? rest.match(/\$\s*([\d,]+(?:[.]?\d+)?[kmbtp]?)/i);
    const amount = amtMatch ? parseTornNumber(amtMatch[1]) : 0;

    return { name, action, amount, rest };
  };

  const playerKey = (name) => String(name ?? '')
    .replace(/^[\s✓✔☑☞→➜➤↪⤷»>]+/u, '')
    .replace(/\s+/g, ' ')
    .replace(/[::]\s*$/, '')
    .trim()
    .toLowerCase();

  const samePlayer = (a, b) => {
    const left = playerKey(a), right = playerKey(b);
    return !!left && !!right && left === right;
  };

  const positionFromBlindPosts = (msgs, heroName, headsUp = false) => {
    if (!msgs || !msgs.length || !heroName) return null;

    let lastWin = -1;
    for (let i = msgs.length - 1; i >= 0; i--) {
      if (WINNER_LINE_RE.test(msgs[i])) { lastWin = i; break; }
    }
    let bbIdx = -1, sbIdx = -1;
    for (let i = msgs.length - 1; i > lastWin; i--) {
      if (bbIdx < 0 && BB_POST_RE.test(msgs[i])) bbIdx = i;
      if (sbIdx < 0 && SB_POST_RE.test(msgs[i])) sbIdx = i;
    }
    if (bbIdx < 0) return null;

    const startIdx = sbIdx >= 0 ? Math.min(bbIdx, sbIdx) : bbIdx;
    for (let i = startIdx; i < msgs.length; i++) {
      const ev = parseActionMessage(msgs[i]);
      if (!ev) {
        if (/\b(flop|turn|river)\b/i.test(msgs[i])) break;
        continue;
      }
      if ((ev.action === 'post_sb' || ev.action === 'post_bb') && samePlayer(ev.name, heroName)) {
        if (headsUp) return ev.action === 'post_sb' ? 'BTN' : 'BB';
        return ev.action === 'post_sb' ? 'SB' : 'BB';
      }
    }
    return null;
  };

  const currentHandEvents = (messages) => {
    const byName = {};
    const hand = { byName, street: 'preflop', bbAmount: 0 };
    if (!messages || !messages.length) return hand;

    let bbIdx = -1;
    for (let i = messages.length - 1; i >= 0; i--) {
      const bbMatch = messages[i].match(BB_POST_RE);
      if (bbMatch) { hand.bbAmount = bbMatch[1] ? parseTornNumber(bbMatch[1]) : 0; bbIdx = i; break; }
    }
    if (bbIdx < 0) return hand;

    let street = 'preflop';
    for (let i = bbIdx; i < messages.length; i++) {
      const msg = messages[i];
      if (/\bflop\b/i.test(msg) && !parseActionMessage(msg)) { street = 'flop'; continue; }
      if (/\bturn\b/i.test(msg) && !parseActionMessage(msg)) { street = 'turn'; continue; }
      if (/\briver\b/i.test(msg) && !parseActionMessage(msg)) { street = 'river'; continue; }
      const ev = parseActionMessage(msg);
      if (!ev) continue;
      if (ev.action === 'post_bb' || ev.action === 'post_sb' || ev.action === 'post') continue;
      const key = playerKey(ev.name);
      if (!byName[key]) byName[key] = [];
      const action = ev.action === 'allin' ? 'raise' : ev.action;
      byName[key].push({ street, action, amount: ev.amount });
    }
    hand.street = street;
    return hand;
  };

  const riverFacesFromEvents = (byName) => {
    if (!byName || typeof byName !== 'object') return null;
    const river = {};
    for (const key of Object.keys(byName)) {

      const acts = (byName[key] || [])
        .filter(e => e && (typeof e === 'string' || e.street === 'river'))
        .map(e => typeof e === 'string' ? e : e.action);
      if (acts.length) river[key] = acts;
    }
    const keys = Object.keys(river);
    if (keys.length !== 2) return null;
    const bettor = keys.find(k => river[k].includes('bet') || river[k].includes('raise'));
    if (!bettor) return null;
    const out = {};
    for (const k of keys) {
      out[k] = {
        faced: river[k].some(a => a === 'call' || a === 'fold' || a === 'raise'),
        folded: river[k].includes('fold')
      };
    }
    return out;
  };

  const lastPreflopAggressor = (messages) => {
    if (!messages || !messages.length) return null;
    let bbIdx = -1;
    for (let i = messages.length - 1; i >= 0; i--) {
      if (BB_POST_RE.test(messages[i])) { bbIdx = i; break; }
    }
    if (bbIdx < 0) return null;
    let last = null;
    for (let i = bbIdx + 1; i < messages.length; i++) {
      const msg = messages[i];
      const ev = parseActionMessage(msg);
      if (!ev) {
        if (/\b(?:flop|turn|river)\b/i.test(msg)) break;
        continue;
      }
      if (ev.action === 'raise' || ev.action === 'allin' || ev.action === 'bet') last = ev.name;
    }
    return last;
  };

  const buildPreflopOppSummary = (messages, activeOppResolved, heroName, raiseLevel) => {
    const byName = new Map();
    for (const entry of activeOppResolved) {
      if (entry?.player?.name) byName.set(playerKey(entry.player.name), entry);
    }
    let pick = null;
    let stealFoldJoint = null;
    if (raiseLevel >= 1) {
      const aggressor = lastPreflopAggressor(messages);
      if (aggressor && heroName && !samePlayer(aggressor, heroName)) {
        pick = byName.get(playerKey(aggressor)) ?? null;
      }
    } else {
      let joint = null;
      let anyActive = false;
      for (const entry of activeOppResolved) {
        const p = entry.p;
        if (!p) continue;
        anyActive = true;
        let foldRate;
        if ((p.blindFoldVsOpenOpp ?? 0) >= 3) {
          foldRate = Math.min(0.95, Math.max(0.25, (p.blindFoldVsOpenCount ?? 0) / p.blindFoldVsOpenOpp));
        } else {
          const t = profileTier(p.handsObserved) === 'unknown' ? null : classifyPlayer(p);
          foldRate = (t === 'FISH' || t === 'CALLING_STATION' || t === 'LOOSE_PASSIVE') ? 0.30
            : (t === 'NIT' || t === 'ROCK' || t === 'TIGHT_PASSIVE') ? 0.70 : 0.50;
        }
        joint = joint === null ? foldRate : joint * foldRate;
      }
      if (anyActive) stealFoldJoint = joint;
      let best = null;
      for (const entry of activeOppResolved) {
        const p = entry.p;
        if (!p || !((p.blindFoldVsOpenOpp ?? 0) >= 5)) continue;
        if (!best || (p.blindFoldVsOpenOpp ?? 0) > (best.p.blindFoldVsOpenOpp ?? 0)) best = entry;
      }
      pick = best;
    }
    if (!pick || !pick.p) return null;
    const p = pick.p;
    const pct = (num, den) => den > 0 ? Math.round((num / den) * 100) : null;
    return {
      name: pick.player.name,
      type: classifyPlayer(p),
      tier: profileTier(p.handsObserved),
      hands: p.handsObserved,
      threeBet: pct(p.threeBetCount ?? 0, p.threeBetOpp ?? 0),
      threeBetOpp: p.threeBetOpp ?? 0,
      foldTo3Bet: pct(p.foldTo3BetCount ?? 0, p.foldTo3BetOpp ?? 0),
      foldTo3BetOpp: p.foldTo3BetOpp ?? 0,
      foldVsOpen: pct(p.blindFoldVsOpenCount ?? 0, p.blindFoldVsOpenOpp ?? 0),
      foldVsOpenOpp: p.blindFoldVsOpenOpp ?? 0,
      stealFoldJoint
    };
  };

  const firstInStats = (pfActs, blindIds) => {
    const openOpp = new Set(), openers = new Set(), pfFolds = new Set();
    const blindSet = new Set(blindIds ?? []);
    let voluntarySeen = false, raises = 0, firstRaiserId = null;
    for (const pair of (pfActs ?? [])) {
      if (!Array.isArray(pair) || pair.length < 2) continue;
      const [pId, act] = pair;
      if (pId == null || !act) continue;
      if (act === 'fold') pfFolds.add(pId);
      if (!voluntarySeen && (act === 'fold' || act === 'call' || act === 'raise' || act === 'bet')) {
        openOpp.add(pId);
        if (act === 'raise' || act === 'bet') openers.add(pId);
      }
      if (act === 'call' || act === 'raise' || act === 'bet') voluntarySeen = true;
      if (act === 'raise' || act === 'bet') { raises++; if (raises === 1) firstRaiserId = pId; }
    }
    const soloOpenId = (raises === 1 && firstRaiserId !== null && openers.has(firstRaiserId)) ? firstRaiserId : null;
    const blindFoldVsOpenFaced = [], blindFoldVsOpen = [];
    if (soloOpenId !== null) {
      for (const bId of blindSet) {
        if (bId === soloOpenId) continue;
        blindFoldVsOpenFaced.push(bId);
        if (pfFolds.has(bId)) blindFoldVsOpen.push(bId);
      }
    }
    return { openOpp, openers, pfFolds, raises, firstRaiserId, soloOpenId, blindFoldVsOpenFaced, blindFoldVsOpen };
  };

  const buildLiveOppRanges = (liveEvents, activeOppPlayers, posByName = {}, handRaiseLevel = 0, riskyBoard = false) => {
    const thresholds = [];
    const display = [];
    for (const player of activeOppPlayers) {
      const p = player ? profiles[player.id] : null;
      let priors = {};
      if (p && p.handsObserved >= 5) {
        const n = p.handsObserved;
        priors = {
          vpip: smoothedRate(p.vpipCount, n),
          pfr: smoothedRate(p.pfrCount, n),
          afq: afqRate(p) ?? 0.35,
          handRaiseLevel
        };
      } else if (handRaiseLevel >= 2) {
        priors = { handRaiseLevel };
      }
      const events = player ? (liveEvents.byName[playerKey(player.name)] ?? []) : [];
      const seatPos = player ? (posByName[player.name] ?? null) : null;
      const frac = narrowRangeFraction(events, priors, seatPos, riskyBoard);
      thresholds.push(getRangeThreshold(frac));
      display.push({ name: player ? player.name : '?', pos: seatPos, frac });
    }
    return { thresholds, display };
  };

  const classifyPlayer = (p) => {

    if (!p || profileTier(p.handsObserved) === 'unknown') return 'UNKNOWN';
    const vpip = smoothedRate(p.vpipCount, p.handsObserved);
    const pfr = smoothedRate(p.pfrCount, p.handsObserved);
    const afq = afqRate(p);
    const wtsd = p.sawFlopCount > 0 ? p.wentToShowdownCount / p.sawFlopCount : 0;

    if (afq !== null) {
      if (vpip >= 0.60 && afq >= 0.50) return 'MANIAC';
      if (vpip >= 0.45 && afq >= 0.40) return 'LAG';
      if (vpip >= 0.45 && afq <= 0.25) return 'FISH';
      if (vpip >= 0.40 && afq <= 0.20) return 'CALLING_STATION';
      if (vpip >= 0.40 && afq <= 0.30) return 'LOOSE_PASSIVE';
      if (vpip <= 0.12 && pfr <= 0.08) return 'NIT';
      if (vpip <= 0.18 && pfr <= 0.10) return 'ROCK';
      if (vpip <= 0.25 && afq >= 0.35) return 'TAG';
      if (vpip <= 0.28 && afq <= 0.25) return 'TIGHT_PASSIVE';
      if (vpip >= 0.22 && vpip <= 0.40 && afq >= 0.30) return 'TAG';
      return 'UNKNOWN';
    }

    if (vpip >= 0.60 && pfr <= 0.30) return 'FISH';
    if (vpip >= 0.45 && pfr >= 0.30) return 'LAG';
    if (vpip >= 0.45) return 'CALLING_STATION';
    if (vpip <= 0.12 && pfr <= 0.08) return 'NIT';
    if (vpip <= 0.18 && pfr <= 0.10) return 'ROCK';
    if (vpip <= 0.28 && pfr >= 0.16) return 'TAG';
    if (vpip <= 0.28) return 'TIGHT_PASSIVE';
    return 'UNKNOWN';
  };

  const getExploitHint = (type, handsObserved) => {
    if (profileTier(handsObserved) === 'unknown' || profileTier(handsObserved) === 'tentative') return null;
    const hints = {
      MANIAC: 'Faces aggression with aggression. Let them bluff, trap with strong hands.',
      LAG: 'Plays many hands aggressively. Call down lighter and do not fold top pair easily.',
      TAG: 'Selective but aggressive. Respect their raises and avoid marginal confrontations.',
      FISH: 'Calls widely and rarely raises. Value bet more, bluff less.',
      CALLING_STATION: 'Rarely folds. Skip the bluffs; thin value bets work.',
      ROCK: 'Enters very few pots. Their raises usually mean strength.',
      NIT: 'Folds most hands. Stealing their blinds may work often.',
      TIGHT_PASSIVE: 'Cautious. Bluff more often, value bet when they continue.',
      LOOSE_PASSIVE: 'Calls too much. Value bet thin, skip the bluffs.',
      UNKNOWN: null
    };
    return hints[type] ?? null;
  };

  const getProfileMetrics = (p) => {
    if (!p) return null;
    const n = p.handsObserved || 0;
    if (n === 0) return null;
    const pct = (num, den) => den > 0 ? Math.round((num / den) * 100) : null;
    const m = {

      vpip: Math.round(smoothedRate(p.vpipCount, n) * 100),
      pfr: Math.round(smoothedRate(p.pfrCount, n) * 100),
      vpipRaw: pct(p.vpipCount, n),
      pfrRaw: pct(p.pfrCount, n),
      afq: p.postTotal > 0 ? Math.round((p.postAgg / p.postTotal) * 100) : 0,
      afqKnown: afqRate(p) !== null,
      afqSample: Math.round(p.postTotal ?? 0),
      af: afOf(p.postAggActions ?? 0, p.postCallActions ?? 0),
      wtsd: p.sawFlopCount > 0 ? Math.round((p.wentToShowdownCount / p.sawFlopCount) * 100) : 0,
      hands: Math.round(n),
      tier: profileTier(n),
      tierLabel: TIER_LABELS[profileTier(n)],
      lastSeen: p.lastSeen ?? null,
      lastSeenAgeMin: p.lastSeen ? Math.max(0, Math.round((Date.now() - p.lastSeen) / 60000)) : null,
      decayPct: p.lastSeen ? Math.round(decayFactor(Date.now() - p.lastSeen) * 100) : 100,
      threeBet: pct(p.threeBetCount ?? 0, p.threeBetOpp ?? 0),
      foldTo3Bet: pct(p.foldTo3BetCount ?? 0, p.foldTo3BetOpp ?? 0),
      cbet: pct(p.cbetCount ?? 0, p.cbetOpp ?? 0),
      foldToCbet: pct(p.foldToCbetCount ?? 0, p.foldToCbetOpp ?? 0),
      foldToRiverBet: pct(p.riverBetFolded ?? 0, p.riverBetFaced ?? 0),
      riverBetFaced: Math.round(p.riverBetFaced ?? 0),
      limp: (p.limpOpp ?? 0) > 0 ? Math.round((p.limpCount ?? 0) / p.limpOpp * 100) : null,
      open: pct(p.openRaiseCount ?? 0, p.openRaiseOpp ?? 0),
      foldToOpen: pct(p.blindFoldVsOpenCount ?? 0, p.blindFoldVsOpenOpp ?? 0),
      openOppCount: Math.round(p.openRaiseOpp ?? 0),
      blindVsOpenOppCount: Math.round(p.blindFoldVsOpenOpp ?? 0),
      avgRaiseBB: (p.raiseSizeCount ?? 0) > 0 ? Math.round((p.raiseSizeSum / p.raiseSizeCount) * 10) / 10 : null,
      confidence: Math.round(sampleConfidence(n) * 100)
    };

    if (p.aggStreet) {
      m.aggFlop = pct(p.aggStreet.flop?.agg ?? 0, p.aggStreet.flop?.total ?? 0);
      m.aggTurn = pct(p.aggStreet.turn?.agg ?? 0, p.aggStreet.turn?.total ?? 0);
      m.aggRiver = pct(p.aggStreet.river?.agg ?? 0, p.aggStreet.river?.total ?? 0);
    }
    return m;
  };

  const getStatExploits = (m) => {
    if (!m) return [];

    const tips = [];
    if (m.foldToCbet !== null && m.foldToCbet >= 65) tips.push('Folds to c-bets often in this sample; c-betting may work.');
    if (m.foldToCbet !== null && m.foldToCbet <= 30 && m.hands >= 10) tips.push('Rarely folds to c-bets in this sample; c-bet mostly for value.');
    if (m.foldTo3Bet !== null && m.foldTo3Bet >= 65) tips.push('Folds to 3-bets often in this sample; open-raising pressure works.');
    if (m.threeBet !== null && m.threeBet >= 15) tips.push('3-bets frequently in this sample; expect light 3-bets.');
    if (m.limp >= 30) tips.push('Limps frequently in this sample; raising their limps may be profitable.');
    if (m.aggRiver !== null && m.aggRiver <= 15 && m.hands >= 12) tips.push('River bets are rare in this sample; their river raises tend to be strong.');
    if (m.foldToRiverBet !== null && m.riverBetFaced >= 8 && m.foldToRiverBet >= 60) tips.push('Folds often vs heads-up river bets in this sample; river bluffs gain value.');
    return tips;
  };

  const MADE_HAND_LABELS = ['High card', 'One pair', 'Two pair', 'Trips', 'Straight', 'Flush', 'Full house', 'Quads', 'Str. flush', 'Royal flush'];
  const madeHandLabel = (t) => MADE_HAND_LABELS[t] ?? 'Unclassified';

  const heroLedgerFromMessages = (messages, heroName) => {
    if (!Array.isArray(messages) || !messages.length || !heroName) return null;
    let contrib = 0, won = 0, showed = false;
    let committed = 0;
    for (const msg of messages) {
      const ev = parseActionMessage(msg);
      if (!ev && /\b(?:flop|turn|river)\b/i.test(msg)) { committed = 0; continue; }
      if (!ev || !samePlayer(ev.name, heroName)) continue;
      if (ev.action === 'post' || ev.action === 'post_bb' || ev.action === 'post_sb') {
        contrib += ev.amount;
        committed = Math.max(committed, ev.amount);
      } else if (ev.action === 'bet' || ev.action === 'call') {
        contrib += ev.amount;
        committed += ev.amount;
      } else if (ev.action === 'raise' || ev.action === 'allin') {
        const delta = Math.max(0, ev.amount - committed);
        contrib += delta;
        committed = Math.max(committed, ev.amount);
      } else if (ev.action === 'win') {
        won += ev.amount;

        if (/with\s*\[/.test(ev.rest ?? '')) showed = true;
      } else if (ev.action === 'show') {
        showed = true;
      }
    }
    return { contrib, won, net: won - contrib, showed };
  };

  const heroLedgerView = (stats) => {
    const rows = {};
    const s = normalizeHeroStats(stats);
    for (const rec of s.ring) {
      (rows[rec.t] ??= { t: rec.t, n: 0, net: 0 });
      rows[rec.t].n++;
      rows[rec.t].net += rec.net;
    }
    return Object.values(rows)
      .map(r => ({ ...r, avg: r.n > 0 ? r.net / r.n : 0 }))
      .sort((a, b) => a.net - b.net);
  };

  const getHeroMetrics = (h) => {
    const s = normalizeHeroStats(h);
    const n = s.hands;
    const pct = (num, den) => den > 0 ? Math.round((num / den) * 100) : 0;
    const m = {
      hands: n,
      tier: profileTier(n),
      tierLabel: TIER_LABELS[profileTier(n)],
      vpip: pct(s.vpip, n),
      pfr: pct(s.pfr, n),
      limp: pct(s.limp, n),
      afq: pct(s.postAgg, s.postTotal),
      af: afOf(s.postAggActions ?? 0, s.postCallActions ?? 0),
      wtsd: pct(s.wtsd, s.sawFlop),
      wsd: pct(s.wsd, s.wtsd),
      open: pct(s.openRaise, s.openOpp),
      openOpp: s.openOpp,
      sdHands: s.ring.length,
      confidence: Math.round(sampleConfidence(n) * 100),
      archetype: classifyPlayer({
        handsObserved: n,
        vpipCount: s.vpip,
        pfrCount: s.pfr,
        postAgg: s.postAgg,
        postTotal: s.postTotal,
        sawFlopCount: s.sawFlop,
        wentToShowdownCount: s.wtsd
      })
    };
    return m;
  };

  const SELF_LEAK_MIN_HANDS = 40;
  const getSelfLeaks = (m, stats) => {
    if (!m) return [];
    const tips = [];
    const s = normalizeHeroStats(stats);
    if (m.hands >= SELF_LEAK_MIN_HANDS) {
      if (m.vpip >= 40 && m.pfr <= 12) {
        tips.push(`Self note: you enter ${m.vpip}% of hands but raise first in only ${m.pfr}% (this sample). Limp-calls pay a flop-viewing fee; the ledger shows the receipts.`);
      } else if (m.limp >= 25) {
        tips.push(`Self note: limping into ${m.limp}% of hands (this sample). Unraised pots are cheap to see but never won right there.`);
      }
      if (m.afq > 0 && m.afq <= 20) {
        tips.push(`Self note: postflop aggression ${m.afq}% (this sample): mostly checking and calling. Strong hands get paid; balancing bluffs are missing.`);
      }
      if (m.wtsd >= 35) {
        tips.push(`Self note: WTSD ${m.wtsd}% of flops seen (this sample). Sticky enough that the table's thin value bets aim at you.`);
      }
      if (m.pfr > 0 && m.pfr <= 8 && m.vpip >= 25) {
        tips.push(`Self note: PFR ${m.pfr}% vs VPIP ${m.vpip}% (this sample): almost every entry is a call. Raising first in takes the initiative more often.`);
      }
    }

    const view = heroLedgerView(s);
    const byType = Object.fromEntries(view.map(r => [r.t, r]));
    const pairRow = byType[1];
    if (pairRow && pairRow.n >= 10 && pairRow.net < 0) {
      tips.push(`Self note: one-pair showdowns: ${pairRow.n} hands, ${pairRow.net < 0 ? '-' : ''}$${Math.abs(Math.round(pairRow.net)).toLocaleString()} (this sample). Calling down with one pair is where that goes.`);
    }
    const hcRow = byType[0];
    if (hcRow && hcRow.n >= 5 && hcRow.net < 0) {
      tips.push(`Self note: ${hcRow.n} showdowns with just high card (this sample). Those pots were lost on earlier streets.`);
    }
    const tpRow = byType[2];
    if (tpRow && tpRow.n >= 8 && tpRow.net < 0) {
      tips.push(`Self note: two-pair showdowns: ${tpRow.n} hands, net negative (this sample). Weak two pair on coordinated boards needs a fold.`);
    }
    return tips;
  };

  const applyBackupData = (current, rawJson) => {
    let obj;
    try { obj = typeof rawJson === 'string' ? JSON.parse(rawJson) : rawJson; } catch { throw new Error('not valid JSON'); }
    if (!obj || typeof obj !== 'object' || obj.kind !== 'tnp-backup') throw new Error('not a Poker Hold\'em backup');
    const profiles = normalizeProfiles(obj.profiles);
    if (!obj.heroStats || typeof obj.heroStats !== 'object') throw new Error('backup is missing the self profile');
    return {
      profiles,
      playerNotes: normalizeNotes(obj.playerNotes),
      heroStats: normalizeHeroStats(obj.heroStats),
      lifetime: normalizeLifetime(obj.lifetime),
      bankroll: normalizeBankrollState(obj.bankroll),
      settings: normalizeSettings({ ...(current.settings ?? {}), ...(obj.settings ?? {}) })
    };
  };

  const mergeIncomingProfiles = (local, incoming) => {
    const base = normalizeProfiles(local);
    const inc = normalizeProfiles(incoming);
    let changed = 0;
    for (const [id, row] of Object.entries(inc)) {
      const cur = base[id];
      if (!cur || (row.handsObserved ?? 0) > (cur.handsObserved ?? 0)) {
        if (cur && cur.name === row.name && (cur.handsObserved ?? 0) === (row.handsObserved ?? 0)) continue;
        base[id] = row;
        changed++;
      }
    }
    return { merged: base, changed };
  };

  const POKER_MSG_RE = /\b(blind|fold|call|rais|check|bet|all[\s-]?in|wins?|won|takes?|scoops?|awarded|shows?|deal|flop|turn|river)/i;

                  const LOG_ACTION_VERB_START_RE = /^(?:calls?|called|checks?|checked|bets?|raises?|raised|re-?raises?|folds?|folded|posts?|posted|went\s+all-?in|goes\s+all-?in|is\s+all-?in|wins?|won|takes?|took|scoops?|reveals?|revealed|shows?|showed|mucks?|mucked|left the table|joined the table|is thinking)\b/i;
  const isChatMessageRow = (row) => {
    if (!row || row.nodeType !== 1 || typeof row.querySelector !== 'function') return false;
    try {
      if (row.closest('#tnp-dossier')) return false;
      if (row.closest('[id*="chat" i], [class*="tchat"], [class*="chat-app"], [class*="chatApp"], [class*="globalChat"], [class*="chatWrap"], [class*="chat-root" i]')) return true;
                              const cls = getClassString(row);
      const isRowShape = row.tagName === 'LI' || /(?:^|\s)message[_-]/i.test(cls);
      if (!isRowShape) return false;
      if (!row.querySelector('em')) return false;
      if (/(?:^|\s)(?:won|state)___/i.test(cls)) return false;
      const icon = row.querySelector('i[class*="logIcon"], i[class*="log-icon"]');
      if (icon && (icon.querySelector('svg') || (icon.textContent || '').trim())) return false;
      const span = row.querySelector('span');
      const spanText = span ? normalizeLogText(span.textContent) : '';
      if (!spanText) return false;
      return !LOG_ACTION_VERB_START_RE.test(spanText);
    } catch { return false; }
  };
  const insideChatMessageRow = (el) => {
    try {
      if (!el || typeof el.closest !== 'function') return false;
      const row = el.closest('li');
      return row ? isChatMessageRow(row) : false;
    } catch { return false; }
  };

  const LOG_ROW_MATCH_SEL = '[class*="message___"], li[class*="message"]';
  const LOG_ROW_CONTAINER_SEL = '[aria-label="Game log"], [class*="logListContainer"], [class*="messagesList"]';
  const isLogRowElement = (el) => !!(el && el.nodeType === 1 && typeof el.matches === 'function'
    && (el.matches(LOG_ROW_MATCH_SEL)
      || (el.tagName === 'LI' && !!el.closest && !!el.closest(LOG_ROW_CONTAINER_SEL))));
  const logRowTexts = (root) => {
    const rows = Array.from(root.querySelectorAll(LOG_ROW_MATCH_SEL))
      .filter(r => !r.closest('#tnp-dossier'))
      .filter(r => !isChatMessageRow(r));
    return rows
      .map(r => normalizeLogText(r.textContent))
      .filter(t => t.length > 0 && t.length <= LOG_TEXT_MAX);
  };

  const collectLogTexts = (el) => {
    if (!el) return [];

    if (isChatMessageRow(el)) return [];

    if (isLogRowElement(el)) {
      const own = normalizeLogText(el.textContent);
      return own ? [own] : [];
    }

    const rows = logRowTexts(el);
    if (rows.length) return rows;

    const nodes = Array.from(el.querySelectorAll('span, div, p, li'))
      .filter(e => !insideChatMessageRow(e));
    if (nodes.length === 0) {
      const own = (el.textContent ?? '').replace(/\s+/g, ' ').trim();
      return own ? [own] : [];
    }
    const leaves = nodes.filter(e => !Array.from(e.children).some(child => child.textContent.trim() === e.textContent.trim()));
    return (leaves.length ? leaves : nodes)
      .map(e => e.textContent.replace(/\s+/g, ' ').trim())
      .filter(t => t.length > 0 && t.length <= LOG_TEXT_MAX);
  };

  const LOG_TEXT_MAX = 250;
  const LOG_BUFFER_CAP = 600;

  const logLineIsAction = (raw) => {
    const t = normalizeLogText(raw);
    if (!logTextUsable(t)) return false;
    try { if (parseActionMessage(t)) return true; } catch {  }
    return /^the (preflop|flop|turn|river)\b/i.test(t)
      || /^[a-z0-9]{6,}\s+started$/i.test(t)
      || /^game\s+[a-z0-9]+\s+started/i.test(t)
      || /\s(joined|left) the table$/i.test(t)
      || /^two cards dealt/i.test(t);
  };
  const logCapture = {
    buffer: [],
    seenAny: false,
    source: '',
    reportedSource: false,
    container: null,
    containerObserver: null,
    bodyObserver: null,
    containerRetryTimer: null
  };

  const normalizeLogText = (t) => String(t ?? '')
    .replace(/[\u200B-\u200D\uFEFF\u2060]/g, '')
    .replace(/\s+/g, ' ')
    .trim();
  const logTextUsable = (t) => { const n = normalizeLogText(t); return n.length >= 3 && n.length <= LOG_TEXT_MAX; };

  const extractNodeTexts = (node) => {
    if (!node) return [];
    if (node.nodeType === 3) {
      const p = node.parentElement;
      if (p && p.closest && p.closest('#tnp-dossier, .tnp-seat-badge')) return [];
      if (p && insideChatMessageRow(p)) return [];
      const t = normalizeLogText(node.textContent);
      return t ? [t] : [];
    }
    if (node.nodeType !== 1) return [];
    if (node.closest && node.closest('#tnp-dossier, .tnp-seat-badge')) return [];
    if (isChatMessageRow(node) || insideChatMessageRow(node)) return [];
    if (isLogRowElement(node)) {
      const t = normalizeLogText(node.textContent);
      return t ? [t] : [];
    }
    if (typeof node.querySelectorAll === 'function') {
      const rows = logRowTexts(node);
      if (rows.length) return rows;
    }
    const leaves = Array.from(node.querySelectorAll('*'))
      .filter(e => e.childElementCount === 0)
      .filter(e => !insideChatMessageRow(e));
    const src = leaves.length ? leaves : [node];
    const out = [];
    for (const e of src) { const t = normalizeLogText(e.textContent); if (t) out.push(t); }
    return out;
  };
  const pushLogTexts = (texts) => {
    const buf = logCapture.buffer;
    for (const raw of texts || []) {
      const t = normalizeLogText(raw);
      if (!logLineIsAction(t)) continue;
      logCapture.seenAny = true;
      if (buf.length && buf[buf.length - 1] === t) continue;
      buf.push(t);
      if (buf.length > LOG_BUFFER_CAP) buf.splice(0, buf.length - LOG_BUFFER_CAP);
    }
  };

  const findLiveLogContainer = () => {
    if (logCapture.container && document.contains(logCapture.container)) return logCapture.container;
    let el = null, src = '';
    try {
      const sidebar = document.querySelector('.sidebar, [class*="sidebar"]');
      const liveInSidebar = sidebar && sidebar.querySelector('[aria-live="polite"][aria-atomic="true"]');
      if (liveInSidebar) { el = liveInSidebar; src = 'aria-live sidebar feed'; }
      if (!el) {
        const anyLive = Array.from(document.querySelectorAll('[aria-live="polite"][aria-atomic="true"]'))
          .find(e => !e.closest('#tnp-dossier') && normalizeLogText(e.textContent).length > 3);
        if (anyLive) { el = anyLive; src = 'aria-live feed'; }
      }
      if (!el) {
        for (const sel of ['[aria-label="Game log"]', '[class*="logListContainer"]', '[class*="messagesList"]', '[class*="messagesWrap"]']
          .concat(SELECTORS.actionLog.filter(s => s !== '[class*="message___"]'))) {
          const cands = Array.from(document.querySelectorAll(sel))
            .filter(e => !e.closest('#tnp-dossier')
              && !/(logo|login|logout|dialog|blog)/i.test(getClassString(e))
              && normalizeLogText(e.textContent).length > 10);
          if (cands.length) { el = cands[0]; src = sel; break; }
        }
      }
    } catch {  }
    if (!el) {
      try {
        const healedLog = healLocate('log', document.body);
        if (healedLog.length && normalizeLogText(healedLog[0].textContent).length > 10) {
          el = healedLog[0]; src = 'heal';
        }
      } catch {  }
    }
    if (el) {
      if (!logCapture.container || !document.contains(logCapture.container)) healRemember('log', el);
      logCapture.container = el;
      if (!logCapture.source) logCapture.source = src;
      if (!logCapture.reportedSource) {
        logCapture.reportedSource = true;
        tinfo(`[TNP] Log capture: watching the live feed (${src}).`);
      }
    }
    return el;
  };

  const observeLogContainer = () => {
    const el = findLiveLogContainer();
    if (!el) return false;
    if (logCapture.containerObserver) { try { logCapture.containerObserver.disconnect(); } catch {  } }
    try {
      logCapture.containerObserver = new MutationObserver((muts) => {
        if (!runtimeActive || !isTableObservationAllowed()) return;
        const texts = [];
        for (const m of muts) {
          if (m.type === 'characterData') {
            if (!insideChatMessageRow(m.target && m.target.parentElement)) texts.push(m.target.textContent);
          }
          else for (const n of m.addedNodes) texts.push(...extractNodeTexts(n));
        }
        pushLogTexts(texts);
      });
      logCapture.containerObserver.observe(el, { childList: true, subtree: true, characterData: true });
    } catch { return false; }
    return true;
  };

  const startLogCapture = () => {
    if (logCapture.bodyObserver) return;
    const armed = observeLogContainer();
    if (!armed) {

      logCapture.containerRetryTimer = setInterval(() => {
        if (!runtimeActive || logCapture.containerObserver) {
          clearInterval(logCapture.containerRetryTimer);
          logCapture.containerRetryTimer = null;
          return;
        }
        observeLogContainer();
      }, 2000);
    }
    try {
      logCapture.bodyObserver = new MutationObserver((muts) => {
        if (!runtimeActive || !isTableObservationAllowed()) return;
        const texts = [];
        for (const m of muts) {
          if (m.type !== 'childList') continue;

          if (logCapture.container && m.target && logCapture.container.contains(m.target)) continue;
          for (const n of m.addedNodes) texts.push(...extractNodeTexts(n));
        }
        if (texts.length) pushLogTexts(texts);

        if (!logCapture.containerObserver || (logCapture.container && !document.contains(logCapture.container))) {
          observeLogContainer();
        }
      });
      logCapture.bodyObserver.observe(document.body, { childList: true, subtree: true });
    } catch {  }

    try {
      const c = findLiveLogContainer();
      if (c) {
        const primed = collectLogTexts(c).filter(t => logLineIsAction(t));
        if (primed.length) {
          const have = new Set(logCapture.buffer);
          const fresh = primed.filter(t => !have.has(t));
          if (fresh.length) logCapture.buffer = fresh.concat(logCapture.buffer);
          if (fresh.length && !logCapture.seenAny) logCapture.seenAny = true;
        }
      }
    } catch {  }
    if (!logCapture.reportedSource) tinfo("[TNP] Log capture armed: watching for the table's action feed.");
  };

  const stopLogCapture = (clearBuffer) => {
    if (logCapture.containerObserver) { try { logCapture.containerObserver.disconnect(); } catch {  } logCapture.containerObserver = null; }
    if (logCapture.bodyObserver) { try { logCapture.bodyObserver.disconnect(); } catch {  } logCapture.bodyObserver = null; }
    if (logCapture.containerRetryTimer) { clearInterval(logCapture.containerRetryTimer); logCapture.containerRetryTimer = null; }
    logCapture.container = null;
    if (clearBuffer) {
      logCapture.buffer = [];
      logCapture.seenAny = false;
      logCapture.source = '';
      logCapture.reportedSource = false;
    }
  };

  const parseActionLog = () => {
    try {
      let fallback = null;
      let snapshot = null;

      for (let i = 0; i < SELECTORS.actionLog.length; i++) {
        const logEls = Array.from(document.querySelectorAll(SELECTORS.actionLog[i]))
          .filter(log => !log.closest('#tnp-dossier') && !/(logo|login|logout|dialog|blog)/i.test(getClassString(log)));
        if (logEls.length === 0) continue;
        const msgs = logEls.flatMap(log => collectLogTexts(log))
          .filter((t, j, arr) => t !== arr[j - 1]);
        if (msgs.some(m => POKER_MSG_RE.test(m))) {
          recordSelectorHit('actionLog', i);
          snapshot = msgs;
          break;
        }
        if (!fallback && msgs.length) fallback = msgs;
      }
      if (!snapshot) {
        recordSelectorMiss('actionLog');
        snapshot = fallback ?? [];
      }

      if (!logCapture.buffer.length) return snapshot;
      const inSnapshot = new Set(snapshot);
      const lostHead = logCapture.buffer.filter(t => !inSnapshot.has(t));
      return (lostHead.length ? lostHead.concat(snapshot) : snapshot)
        .filter((t, j, arr) => t !== arr[j - 1]);
    } catch {  }
    return [];
  };

  const DECAY_KEYS = ['handsObserved', 'vpipCount', 'pfrCount', 'postAgg', 'postTotal', 'sawFlopCount',
    'wentToShowdownCount', 'wonAtShowdownCount', 'threeBetCount', 'threeBetOpp', 'foldTo3BetCount',
    'foldTo3BetOpp', 'cbetCount', 'cbetOpp', 'foldToCbetCount', 'foldToCbetOpp', 'limpCount',
    'raiseSizeSum', 'raiseSizeCount', 'riverBetFaced', 'riverBetFolded',
    'openRaiseCount', 'openRaiseOpp', 'blindFoldVsOpenCount', 'blindFoldVsOpenOpp',
    'postAggActions', 'postCallActions'];

  const ensureProfile = (pId, name) => {
    if (!profiles[pId]) {
      profiles[pId] = {
        name, handsObserved: 0, vpipCount: 0, pfrCount: 0,
        postAgg: 0, postTotal: 0, sawFlopCount: 0,
        wentToShowdownCount: 0, wonAtShowdownCount: 0,
        threeBetCount: 0, threeBetOpp: 0, foldTo3BetCount: 0, foldTo3BetOpp: 0,
        cbetCount: 0, cbetOpp: 0, foldToCbetCount: 0, foldToCbetOpp: 0,
        limpCount: 0, raiseSizeSum: 0, raiseSizeCount: 0,
        openRaiseCount: 0, openRaiseOpp: 0, blindFoldVsOpenCount: 0, blindFoldVsOpenOpp: 0,
        postAggActions: 0, postCallActions: 0,
        aggStreet: { flop: { agg: 0, total: 0 }, turn: { agg: 0, total: 0 }, river: { agg: 0, total: 0 } },
        sess: { hands: 0, vpip: 0, raises: 0, agg: 0 },
        recent: [],
        lastBigLossTs: 0,
        lastSeen: Date.now()
      };
      return profiles[pId];
    }
    const p = profiles[pId];

    for (const k of DECAY_KEYS) if (typeof p[k] !== 'number') p[k] = 0;
    if (!p.aggStreet) p.aggStreet = { flop: { agg: 0, total: 0 }, turn: { agg: 0, total: 0 }, river: { agg: 0, total: 0 } };
    const now = Date.now();
    if (p.lastSeen && now - p.lastSeen > 3 * 86400000) {
      const f = decayFactor(now - p.lastSeen);
      for (const k of DECAY_KEYS) p[k] *= f;
      for (const st in p.aggStreet) { p.aggStreet[st].agg *= f; p.aggStreet[st].total *= f; }
    }
    p.lastSeen = now;
    return p;
  };

  const resetProfileSessionCounters = () => {
    let n = 0;
    for (const p of Object.values(profiles)) {
      if (p && p.sess && (p.sess.hands || p.sess.vpip || p.sess.raises || p.sess.agg)) {
        p.sess = { hands: 0, vpip: 0, raises: 0, agg: 0 };
        n++;
      }
    }
    if (n) saveProfiles();
  };

  const pruneProfiles = () => {
    const now = Date.now();
    const retentionMs = settings.profileRetentionDays * 86400000;
    let removed = 0;
    for (const [id, p] of Object.entries(profiles)) {
      const seen = Number(p?.lastSeen) || 0;
      if (now - seen > retentionMs) { delete profiles[id]; removed++; }
    }
    const ids = Object.keys(profiles);
    if (ids.length > settings.maxProfiles) {
      ids.sort((a, b) => (Number(profiles[a]?.lastSeen) || 0) - (Number(profiles[b]?.lastSeen) || 0));
      const excess = ids.length - settings.maxProfiles;
      for (let i = 0; i < excess; i++) { delete profiles[ids[i]]; removed++; }
    }
    if (removed > 0) {
      tinfo(`[TNP] Retention: removed ${removed} stale local profile(s) (window ${settings.profileRetentionDays}d, cap ${settings.maxProfiles}).`);
      saveProfiles();
    }
    return removed;
  };

  const captureHandEvidence = (holeKey, messages, heroSeat = null) => {
    if (!holeKey) return;
    if (handEvidence.key !== holeKey) {
      handEvidence = { key: holeKey, messages: [], heroName: '', heroVoluntary: false, heroWon: false, heroShowed: false };
    }
    const hero = (heroSeat && getPlayerName(heroSeat)) || getHeroIdentity();
    if (hero?.name) handEvidence.heroName = hero.name;
    for (const message of messages || []) {
      if (!handEvidence.messages.includes(message)) handEvidence.messages.push(message);
      const event = parseActionMessage(message);
      if (!event || !handEvidence.heroName || !samePlayer(event.name, handEvidence.heroName)) continue;
      if (['call', 'raise', 'bet', 'allin'].includes(event.action)) handEvidence.heroVoluntary = true;
      if (event.action === 'win') {
        handEvidence.heroWon = true;

        if (/with\s*\[/.test(event.rest ?? '')) handEvidence.heroShowed = true;
      }
      if (event.action === 'show' || event.action === 'reveal') handEvidence.heroShowed = true;
    }
    if (handEvidence.messages.length > 240) handEvidence.messages = handEvidence.messages.slice(-160);
  };

  const handSignature = (messages, winnerIdx) => {

    const part = (i) => (Number.isInteger(i) && i >= 0 && i < messages.length ? String(messages[i]).slice(0, 80) : '');

    let anchor = winnerIdx;
    while (anchor > 0 && WINNER_LINE_RE.test(messages[anchor - 1])) anchor--;
    const award = part(anchor);
    if (!award) return '';
    let i = anchor - 1;
    while (i >= 0 && WINNER_LINE_RE.test(messages[i])) i--;
    let prev = -1;
    for (; i >= 0; i--) {
      if (WINNER_LINE_RE.test(messages[i])) { prev = i; break; }
    }
    const window = [];
    for (let j = prev + 1; j <= anchor && window.length < 40; j++) window.push(part(j));
    return `${award}##${window.length}##${window.join('|')}`;
  };

  const recordFallbackSessionHand = (holeKey, messages, seats, evidence = null, dealtIn = true) => {
    if (!holeKey || recordedSessionHandKeys.has(holeKey)) return false;

    const windowMsgs = evidence?.messages?.length ? evidence.messages : (messages || []);
    let latestWinIdx = -1;
    for (let i = windowMsgs.length - 1; i >= 0; i--) {
      if (WINNER_LINE_RE.test(windowMsgs[i])) { latestWinIdx = i; break; }
    }
    const latestAwardLine = latestWinIdx >= 0 ? String(windowMsgs[latestWinIdx] ?? '') : '';
    if (latestAwardLine && seenAwardLines.has(latestAwardLine)) return false;
    const fallbackSig = latestWinIdx >= 0 ? handSignature(windowMsgs, latestWinIdx) : '';
    if (fallbackSig && (handTracker.lastHandSig === fallbackSig || handTracker.processedMsgs.has(fallbackSig))) {
      recordedSessionHandKeys.add(holeKey);
      return false;
    }
    recordedSessionHandKeys.add(holeKey);
    try {
      void TNP6.persistHandRecord({
        id: 'dom:' + holeKey + ':' + (evidence?.key || Date.now()),
        ts: Date.now(),
        hole: holeKey.split(',').filter(Boolean),
        source: 'dom-action-log',
        messages: (windowMsgs || []).slice(-60)
      });
    } catch (e) { }
    if (recordedSessionHandKeys.size > 120) {
      const keys = Array.from(recordedSessionHandKeys);
      recordedSessionHandKeys.clear();
      keys.slice(-60).forEach(k => recordedSessionHandKeys.add(k));
    }
    if (latestAwardLine) {
      seenAwardLines.add(latestAwardLine);
      if (seenAwardLines.size > 12) {
        seenAwardLines = new Set(Array.from(seenAwardLines).slice(-8));
      }
    }
    if (fallbackSig) {
      handTracker.fallbackSigs.add(fallbackSig);
      if (handTracker.fallbackSigs.size > 100) {
        const arr = Array.from(handTracker.fallbackSigs);
        handTracker.fallbackSigs = new Set(arr.slice(-50));
      }
    }

    const myPlayer = getHeroIdentity();
    const heroName = myPlayer?.name ?? evidence?.heroName ?? '';
    const evidenceMessages = evidence?.messages?.length ? evidence.messages : (messages || []);
    const heroEvents = heroName ? evidenceMessages
      .map(parseActionMessage)
      .filter(Boolean)
      .filter(ev => samePlayer(ev.name, heroName)) : [];
    const heroVoluntary = !!evidence?.heroVoluntary || heroEvents.some(ev => ['call', 'raise', 'bet', 'allin'].includes(ev.action));
    const heroWon = !!evidence?.heroWon || heroEvents.some(ev => ev.action === 'win');

    const heroShowed = !!evidence?.heroShowed || heroEvents.some(ev =>
      ['show', 'reveal'].includes(ev.action)
      || (ev.action === 'win' && /with\s*\[/.test(ev.rest ?? '')));
    const heroActionObserved = heroEvents.length > 0;
    const heroOutcomeKnown = heroEvents.some(ev => ['fold', 'muck', 'win', 'show', 'reveal'].includes(ev.action));

    const heroParticipated = heroActionObserved || !heroName || dealtIn === true;
    if (!heroParticipated) {
      tinfo('[TNP] Session: fallback hand skipped (no hero action in the window; likely not dealt in)');
      session.lastHandHeroWon = false;
      saveSession();
      return false;
    }

    session.handsPlayed++;
    pipelineStats.handsRecorded++;
    if (heroActionObserved) {
      pipelineStats.heroHands++;
      pipelineStats.actionsParsed += heroEvents.length;
      session.handsVPIPKnown++;
      if (heroVoluntary) session.handsVPIP++;
    }
    if (heroOutcomeKnown) session.outcomeKnownHands++;
    if (heroWon) {
      session.handsWon++;
      if (heroShowed) session.showdownWins++;
      const gain = estimateHandScore({
        won: true,
        handType: heroShowed ? lastHeroEvalType : 0,
        opponents: Math.max(1, (seats || []).length - 1),
        showdown: heroShowed,
        bb: handTracker.bbAmount || 100
      });
      session.scoreEst += gain;
      lifetime.scoreEst += gain;
      lifetime.handsWon++;
      if (heroShowed) {
        lifetime.showdownWins++;
        if (lastHeroEvalType > (lifetime.bestHandType ?? 0)) lifetime.bestHandType = lastHeroEvalType;
      }
    }
    lifetime.handsPlayed++;
    saveLifetime();

    if (heroName && heroActionObserved) {
      heroStats.hands++;
      if (heroVoluntary) heroStats.vpip++;
      const firstStreet = evidenceMessages.findIndex(m => /\b(?:flop|turn|river)\b/i.test(m));
      const firstRaise = evidenceMessages.findIndex(m => {
        const ev = parseActionMessage(m);
        return ev && samePlayer(ev.name, heroName) && ['raise', 'bet', 'allin'].includes(ev.action);
      });
      if (firstRaise >= 0 && (firstStreet < 0 || firstRaise < firstStreet)) heroStats.pfr++;
      let heroSawFlop = heroShowed;
      if (!heroSawFlop) {
        const flopIdx = evidenceMessages.findIndex(m => /\bflop\b/i.test(m) && !parseActionMessage(m));
        if (flopIdx >= 0) {
          const foldedPre = evidenceMessages.slice(0, flopIdx).some(m => {
            const ev = parseActionMessage(m);
            return ev && samePlayer(ev.name, heroName) && (ev.action === 'fold' || ev.action === 'muck');
          });
          const inHand = heroEvents.some(ev => ev.action !== 'win' && ev.action !== 'show');
          if (!foldedPre && inHand) heroSawFlop = true;
        }
      }
      if (heroSawFlop) heroStats.sawFlop++;
      if (heroShowed) heroStats.wtsd++;
      if (heroShowed && heroWon) heroStats.wsd++;
      if (heroEvents.some(ev => ['bet', 'raise', 'allin'].includes(ev.action))) heroStats.postAgg++;
      if (heroEvents.some(ev => ['bet', 'raise', 'allin', 'call', 'check'].includes(ev.action))) heroStats.postTotal++;
                  {
        let streetFb = 'preflop', fbAgg = 0, fbCalls = 0;
        for (const msgText of evidenceMessages) {
          const evFb = parseActionMessage(msgText);
          if (!evFb) {
            if (/\bflop\b/i.test(msgText)) streetFb = 'flop';
            else if (/\bturn\b/i.test(msgText)) streetFb = 'turn';
            else if (/\briver\b/i.test(msgText)) streetFb = 'river';
            continue;
          }
          if (streetFb === 'preflop') continue;
          if (!heroName || !samePlayer(evFb.name, heroName)) continue;
          if (['bet', 'raise', 'allin'].includes(evFb.action)) fbAgg++;
          else if (evFb.action === 'call') fbCalls++;
        }
        heroStats.postAggActions = (heroStats.postAggActions ?? 0) + fbAgg;
        heroStats.postCallActions = (heroStats.postCallActions ?? 0) + fbCalls;
      }
      const fallbackLedger = heroLedgerFromMessages(evidenceMessages, heroName);
      if (heroShowed && fallbackLedger
        && Number.isFinite(fallbackLedger.net) && Math.abs(fallbackLedger.net) < 1e12) {
        heroLedgerApply(heroStats, { t: lastHeroEvalType ?? 0, net: fallbackLedger.net });
      }
      saveHeroStats();
    }
    tinfo(`[TNP] Session: hand #${session.handsPlayed} recorded by hand-boundary fallback`);
    session.lastHandHeroWon = heroWon;
    tagDecisionOutcomes(heroWon, decisionHandStartedAt);
    saveSession();
    renderSessionPanel();
    renderBankrollPanel();
    renderMirrorPanel();
    return true;
  };

  const processHandActions = (messages, seats) => {
    if (!messages || messages.length === 0) return;

    let bbAmount = 0;
    for (let i = messages.length - 1; i >= 0; i--) {
      const bbMatch = messages[i].match(BB_POST_RE);
      if (bbMatch) {
        bbAmount = bbMatch[1] ? parseTornNumber(bbMatch[1]) : 0;
        break;
      }
    }

    const latestWinnerIdx = messages.reduce((idx, msg, i) =>
      WINNER_LINE_RE.test(msg) ? i : idx, -1);
    if (latestWinnerIdx < 0) return;

    const sig = handSignature(messages, latestWinnerIdx);
    if (!sig || handTracker.lastHandSig === sig) return;
    if (handTracker.processedMsgs.has(sig)) return;

    const awardLine = String(messages[latestWinnerIdx] ?? '');
    if (awardLine && seenAwardLines.has(awardLine) && !handTracker.fallbackSigs.has(sig)) return;

    let i = latestWinnerIdx - 1;
    while (i >= 0 && WINNER_LINE_RE.test(messages[i])) i--;
    let prevWinnerIdx = -1;
    for (; i >= 0; i--) {
      if (WINNER_LINE_RE.test(messages[i])) { prevWinnerIdx = i; break; }
    }
    const lowerBound = prevWinnerIdx + 1;
    if (!bbAmount) bbAmount = handTracker.bbAmount || 0;

    const nameToId = {};
    for (const seat of seats) {
      const player = getPlayerName(seat);
      if (player) nameToId[playerKey(player.name)] = player.id;
    }
    const heroPlayer = getHeroIdentity();
    const heroName = heroPlayer?.name ?? '';
    let heroVoluntaryThisHand = false;
    let heroActionSeenThisHand = false;
    let heroOutcomeKnownThisHand = false;

    const handMsgs = messages.slice(lowerBound, latestWinnerIdx + 1);
    pipelineStats.awardWindows++;
    pipelineStats.lastHandAt = Date.now();
    sessionAwardSeenAt = Date.now();
    handTracker.processedMsgs.add(sig);
    if (handTracker.processedMsgs.size > 100) {
      const arr = Array.from(handTracker.processedMsgs);
      handTracker.processedMsgs = new Set(arr.slice(-50));
    }
    handTracker.lastHandSig = sig;
    if (awardLine) {
      seenAwardLines.add(awardLine);
      if (seenAwardLines.size > 12) {
        seenAwardLines = new Set(Array.from(seenAwardLines).slice(-8));
      }
    }

    let currentStreet = 'preflop';
    const vpipThisHand = new Set();
    const pfrThisHand = new Set();
    const postAggThisHand = new Set();
    const postTotalThisHand = new Set();
    const sawFlopPlayers = new Set();
    const showdownPlayers = new Set();
    const limpers = new Set();
    const limpOppThisHand = new Set();
    const threeBetOppSet = new Set(), threeBetSet = new Set();
    const foldTo3BetOppSet = new Set(), foldTo3BetSet = new Set();
    const cbetOppSet = new Set(), cbetSet = new Set();
    const foldToCbetOppSet = new Set(), foldToCbetSet = new Set();
    const riverActsByPId = {};
    let heroPostAggActions = 0, heroPostCallActions = 0;
    let pipeParsed = 0, pipeAttributed = 0, pipeMisses = 0;

                            const actedThisHand = new Set();

    const pfActs = [];
    const blindIdsThisHand = new Set();
    let pfRaises = 0, firstRaiserId = null, lastPfRaiserId = null, cbetMade = false;

    for (const msg of handMsgs) {
      const evProbe = parseActionMessage(msg);
      if (!evProbe) {
        if (/\bflop\b/i.test(msg)) { currentStreet = 'flop'; continue; }
        if (/\bturn\b/i.test(msg)) { currentStreet = 'turn'; continue; }
        if (/\briver\b/i.test(msg)) { currentStreet = 'river'; continue; }
        continue;
      }
      const ev = evProbe;
      pipeParsed++;
      const pId = nameToId[playerKey(ev.name)];
      if (pId) actedThisHand.add(pId);
      const act = ev.action === 'allin' ? 'raise' : ev.action;
      const isHeroAction = !!(heroName && samePlayer(ev.name, heroName));
      if (isHeroAction) {
        heroActionSeenThisHand = true;
        if (['call', 'raise', 'bet', 'allin'].includes(ev.action)) heroVoluntaryThisHand = true;
        if (['fold', 'muck', 'win', 'show', 'reveal'].includes(ev.action)) heroOutcomeKnownThisHand = true;
      } else if (pId) {
        pipeAttributed++;
      } else {
        pipeMisses++;
      }
      if (!pId) continue;
                  const p = isHeroAction ? null : ensureProfile(pId, ev.name);

      if (ev.action === 'post_bb' || ev.action === 'post_sb' || ev.action === 'post') {
        if (ev.action !== 'post') blindIdsThisHand.add(pId);
        continue;
      }
      if (currentStreet === 'preflop') {
        pfActs.push([pId, act]);
        if (act === 'call' || act === 'raise' || act === 'bet') vpipThisHand.add(pId);
        if (act === 'raise' || act === 'bet') pfrThisHand.add(pId);
        if (act === 'call' && pfRaises === 0) limpers.add(pId);
        if (pfRaises === 0 && (act === 'call' || act === 'fold') && !blindIdsThisHand.has(pId)) limpOppThisHand.add(pId);
        if (pfRaises === 1 && pId !== firstRaiserId && (act === 'call' || act === 'raise' || act === 'fold') && !threeBetOppSet.has(pId)) {
          threeBetOppSet.add(pId);
          if (act === 'raise') threeBetSet.add(pId);
        }
        if (pfRaises >= 2 && pId === firstRaiserId && (act === 'call' || act === 'raise' || act === 'fold') && !foldTo3BetOppSet.has(pId)) {
          foldTo3BetOppSet.add(pId);
          if (act === 'fold') foldTo3BetSet.add(pId);
        }
        if (act === 'raise' || act === 'bet') {
          pfRaises++;
          if (pfRaises === 1) firstRaiserId = pId;
          lastPfRaiserId = pId;
        }
      } else {
        if (currentStreet === 'flop') sawFlopPlayers.add(pId);
        const isAgg = act === 'raise' || act === 'bet';
        const isVoluntary = isAgg || act === 'call' || act === 'check' || act === 'fold';
        if (isAgg) { postAggThisHand.add(pId); postTotalThisHand.add(pId); }
        else if (act === 'call' || act === 'check' || act === 'fold') postTotalThisHand.add(pId);
        if (isVoluntary && p && p.aggStreet[currentStreet]) {
          p.aggStreet[currentStreet].total++;
          if (isAgg) p.aggStreet[currentStreet].agg++;
        }
                        if (p) {
          if (isAgg) p.postAggActions = (p.postAggActions ?? 0) + 1;
          else if (act === 'call') p.postCallActions = (p.postCallActions ?? 0) + 1;
        }
        if (isHeroAction) {
          if (isAgg) heroPostAggActions++;
          else if (act === 'call') heroPostCallActions++;
        }
        if (currentStreet === 'river') (riverActsByPId[pId] ??= []).push(act);
        if (currentStreet === 'flop' && lastPfRaiserId) {
          if (pId === lastPfRaiserId && !cbetOppSet.has(pId) && (isAgg || act === 'check')) {
            cbetOppSet.add(pId);
            if (isAgg) { cbetSet.add(pId); cbetMade = true; }
          } else if (cbetMade && pId !== lastPfRaiserId && isVoluntary && !foldToCbetOppSet.has(pId)) {
            foldToCbetOppSet.add(pId);
            if (act === 'fold') foldToCbetSet.add(pId);
          }
        }
      }

      if (p && (act === 'raise' || act === 'bet') && ev.amount > 0 && bbAmount > 0) {
        p.raiseSizeSum += ev.amount / bbAmount;
        p.raiseSizeCount++;
      }

      if ((act === 'show' || act === 'win' || act === 'muck') && currentStreet === 'river') {
        showdownPlayers.add(pId);
        if (act === 'win' && p) p.wonAtShowdownCount = (p.wonAtShowdownCount ?? 0) + 1;
      }
    }

    const allPlayersInHand = new Set([...actedThisHand, ...vpipThisHand, ...pfrThisHand, ...sawFlopPlayers, ...showdownPlayers]);
    for (const msg of handMsgs) {
      const blindMatch = msg.match(/^(.+?)\s+post(?:ed|s)?\s+(?:the\s+)?(?:big|small)\s+blind/i);
      if (blindMatch) {
        const name = blindMatch[1].trim();
        const pId = nameToId[playerKey(name)];
        if (pId) allPlayersInHand.add(pId);
      }
    }

    for (const pId of allPlayersInHand) {
      if (!profiles[pId]) continue;
      const p = profiles[pId];
      p.handsObserved++;
      if (!p.sess) p.sess = { hands: 0, vpip: 0, raises: 0, agg: 0 };
      if (!Array.isArray(p.recent)) p.recent = [];
      p.sess.hands++;
      const handV = vpipThisHand.has(pId) ? 1 : 0;
      const handR = pfrThisHand.has(pId) ? 1 : 0;
      const handA = postAggThisHand.has(pId) ? 1 : 0;
      if (handV) p.sess.vpip++;
      if (handR) p.sess.raises++;
      if (handA) p.sess.agg++;
      p.recent.push({ ts: Date.now(), v: handV, r: handR, a: handA, w: showdownPlayers.has(pId) ? 1 : 0, net: null });
      if (p.recent.length > 10) p.recent = p.recent.slice(-10);
      if (vpipThisHand.has(pId)) p.vpipCount++;
      if (pfrThisHand.has(pId)) p.pfrCount++;
      if (sawFlopPlayers.has(pId)) p.sawFlopCount++;
      if (postAggThisHand.has(pId)) p.postAgg++;
      if (postTotalThisHand.has(pId)) p.postTotal++;
      if (showdownPlayers.has(pId)) p.wentToShowdownCount++;
      if (limpers.has(pId)) p.limpCount++;
      if (limpOppThisHand.has(pId)) p.limpOpp = (p.limpOpp ?? 0) + 1;
      if (threeBetOppSet.has(pId)) p.threeBetOpp++;
      if (threeBetSet.has(pId)) p.threeBetCount++;
      if (foldTo3BetOppSet.has(pId)) p.foldTo3BetOpp++;
      if (foldTo3BetSet.has(pId)) p.foldTo3BetCount++;
      if (cbetOppSet.has(pId)) p.cbetOpp++;
      if (cbetSet.has(pId)) p.cbetCount++;
      if (foldToCbetOppSet.has(pId)) p.foldToCbetOpp++;
      if (foldToCbetSet.has(pId)) p.foldToCbetCount++;
    }

    const firstIn = firstInStats(pfActs, blindIdsThisHand);
    for (const pId of firstIn.openOpp) {
      const p = profiles[pId];
      if (p) p.openRaiseOpp = (p.openRaiseOpp ?? 0) + 1;
    }
    for (const pId of firstIn.openers) {
      const p = profiles[pId];
      if (p) p.openRaiseCount = (p.openRaiseCount ?? 0) + 1;
    }
    for (const bId of firstIn.blindFoldVsOpenFaced) {
      const p = profiles[bId];
      if (!p) continue;
      p.blindFoldVsOpenOpp = (p.blindFoldVsOpenOpp ?? 0) + 1;
      if (firstIn.pfFolds.has(bId)) p.blindFoldVsOpenCount = (p.blindFoldVsOpenCount ?? 0) + 1;
    }

    const riverFaces = riverFacesFromEvents(riverActsByPId);
    if (riverFaces) {
      for (const [pId, face] of Object.entries(riverFaces)) {
        const p = profiles[pId];
        if (!p || !face.faced) continue;
        p.riverBetFaced = (p.riverBetFaced ?? 0) + 1;
        if (face.folded) p.riverBetFolded = (p.riverBetFolded ?? 0) + 1;
      }
    }

    const heroParticipated = heroActionSeenThisHand || !heroName;
    const countedByFallback = handTracker.fallbackSigs.has(sig);
    pipelineStats.actionsParsed += pipeParsed;
    pipelineStats.actionsAttributed += pipeAttributed;
    pipelineStats.nameMisses += pipeMisses;
    if (heroParticipated && !countedByFallback) {
      session.handsPlayed++;
      pipelineStats.handsRecorded++;
    }
    if (heroActionSeenThisHand) pipelineStats.heroHands++;
    if (lastHoleKey) recordedSessionHandKeys.add(lastHoleKey);

    try {
      const curHole = parseHoleCards();
      if (curHole.length === 2) recordedSessionHandKeys.add(curHole.join(','));
    } catch {  }
    tinfo(countedByFallback
      ? '[TNP] Session: hand already counted by fallback; action log refined opponent stats only'
      : (heroParticipated
        ? `[TNP] Session: hand #${session.handsPlayed} recorded via action log`
        : '[TNP] Session: opponents-only hand skipped (you were not dealt in)'));
    const myPlayer = heroPlayer ?? getHeroIdentity();
    if (myPlayer && !countedByFallback) {
      if (heroActionSeenThisHand) {
        session.handsVPIPKnown++;
        if (heroVoluntaryThisHand || vpipThisHand.has(myPlayer.id)) session.handsVPIP++;
      }

      const heroWon = handMsgs.some(m => {
        const ev = parseActionMessage(m);
        return ev && ev.action === 'win' && samePlayer(ev.name, myPlayer.name);
      });

      session.lastHandHeroWon = heroWon;
      tagDecisionOutcomes(heroWon, decisionHandStartedAt);
      const wasShowdown = showdownPlayers.size >= 2;
      if (heroOutcomeKnownThisHand) session.outcomeKnownHands++;
      if (heroWon) {
        session.handsWon++;
        if (wasShowdown) session.showdownWins++;
        const gain = estimateHandScore({
          won: true,
          handType: wasShowdown ? lastHeroEvalType : 0,
          opponents: Math.max(1, allPlayersInHand.size - 1),
          showdown: wasShowdown,
          bb: bbAmount || handTracker.bbAmount || 100
        });
        session.scoreEst += gain;
        lifetime.scoreEst += gain;
        lifetime.handsWon++;
        if (wasShowdown) {
          lifetime.showdownWins++;
          if (lastHeroEvalType > (lifetime.bestHandType ?? 0)) lifetime.bestHandType = lastHeroEvalType;
        }
      }
      if (heroParticipated) {
        lifetime.handsPlayed++;
        saveLifetime();
      }

      const heroId = myPlayer.id;
      const heroInShowdown = showdownPlayers.has(heroId)
        || handMsgs.some(m => {
          const ev = parseActionMessage(m);

          return ev && samePlayer(ev.name, myPlayer.name)
            && (ev.action === 'show'
              || (ev.action === 'win' && /with\s*\[/.test(ev.rest ?? '')));
        });
      if (heroActionSeenThisHand) {
        heroStats.hands++;
        if (heroVoluntaryThisHand || vpipThisHand.has(heroId)) heroStats.vpip++;
        if (pfrThisHand.has(heroId)) heroStats.pfr++;
        else if (limpers.has(heroId)) heroStats.limp++;
        if (firstIn.openOpp.has(heroId)) heroStats.openOpp = (heroStats.openOpp ?? 0) + 1;
        if (firstIn.openers.has(heroId)) heroStats.openRaise = (heroStats.openRaise ?? 0) + 1;
        if (sawFlopPlayers.has(heroId)) heroStats.sawFlop++;
        if (postAggThisHand.has(heroId)) heroStats.postAgg++;
        if (postTotalThisHand.has(heroId)) heroStats.postTotal++;
        heroStats.postAggActions = (heroStats.postAggActions ?? 0) + heroPostAggActions;
        heroStats.postCallActions = (heroStats.postCallActions ?? 0) + heroPostCallActions;
        if (heroInShowdown) heroStats.wtsd++;
        if (heroInShowdown && heroWon) heroStats.wsd++;
      }

      const ledgerMsgs = messages.slice(prevWinnerIdx + 1, latestWinnerIdx + 1);
      const heroLedger = heroLedgerFromMessages(ledgerMsgs, myPlayer.name);
      if (heroLedger && heroLedger.showed && wasShowdown
        && Number.isFinite(heroLedger.net) && Math.abs(heroLedger.net) < 1e12) {
        heroLedgerApply(heroStats, { t: lastHeroEvalType ?? 0, net: heroLedger.net });
      }
      saveHeroStats();
    }
    if (bbAmount > 0) handTracker.bbAmount = bbAmount;

    saveProfiles();

    saveSession();

    renderSessionPanel();
    renderBankrollPanel();
    renderMirrorPanel();
  };

  const getTableAdjust = () => {
    if (!settings.profileAdjusted) return { callAdj: 0, valueAdj: 0, bluffOk: true };
    try {
      let n = 0, vpipSum = 0, afqSum = 0, afqN = 0;
      const seats = getAllSeats();
      const me = findOwnSeat();
      for (const seat of seats) {
        if (isOwnPlayerSeat(seat, me)) continue;
        if (!isOpponentActive(seat)) continue;
        const player = getPlayerName(seat);
        const p = player ? profiles[player.id] : null;
        if (p && p.handsObserved >= 5) {
          const m = getProfileMetrics(p);
          if (m) {
            n++; vpipSum += m.vpip / 100;
            const afq = afqRate(p);
            if (afq !== null) { afqSum += afq; afqN++; }
          }
        }
      }
      if (n === 0) return { callAdj: 0, valueAdj: 0, bluffOk: true };
      const vpip = vpipSum / n;
      const afq = afqN > 0 ? afqSum / afqN : 0.30;
      return {
        callAdj: afq >= 0.40 ? -0.04 : (afq <= 0.20 ? 0.04 : 0),
        valueAdj: vpip >= 0.45 ? -0.05 : (vpip <= 0.18 ? 0.04 : 0),
        bluffOk: !(vpip >= 0.40 && afq <= 0.25)
      };
    } catch { return { callAdj: 0, valueAdj: 0, bluffOk: true }; }
  };

  const headsUpOpponentProfile = () => {
    const seats = getAllSeats();
    const me = findOwnSeat();
    for (const seat of seats) {
      if (isOwnPlayerSeat(seat, me)) continue;
      if (!isOpponentActive(seat)) continue;
      const player = getPlayerName(seat);
      return player ? (profiles[player.id] ?? null) : null;
    }
    return null;
  };

  const riverOverfoldCtx = () => {
    if (!settings.profileAdjusted) return null;
    if (gameState.street !== 'River' || gameState.activeOpponents !== 1) return null;
    if (gameState.toCall > 0 || !(gameState.pot > 0)) return null;
    return riverOverfoldRead(headsUpOpponentProfile(), gameState.pot, gameState.heroStack || 0);
  };

        const textForIntent = (intent, actionBtns, toCall = 0) => {
    if (!actionBtns) return '';
    if (intent === 'raise') {
      if (actionBtns.hasRaise) return toCall > 0 ? 'Raise' : 'Bet';
      if (actionBtns.hasCall) return actionBtns.callText;
      if (actionBtns.hasCheck) return actionBtns.checkText;
    } else if (intent === 'call') {
      if (actionBtns.hasCall) return actionBtns.callText;
      if (actionBtns.hasCheck) return actionBtns.checkText;
      if (actionBtns.hasFold) return actionBtns.foldText;
    } else if (intent === 'check') {
      if (actionBtns.hasCheck) return actionBtns.checkText;
      if (actionBtns.hasCall) return actionBtns.callText;
      if (actionBtns.hasFold) return actionBtns.foldText;
    } else if (intent === 'fold') {
      if (actionBtns.hasFold && !actionBtns.hasCheck) return actionBtns.foldText;
      if (actionBtns.hasCheck) return actionBtns.checkText;
      if (actionBtns.hasCall) return actionBtns.callText;
    }
    return '';
  };

  const getRecommendation = (equity, activeOpponents, toCall, pot, actionBtns, ctx = {}) => {
    if (equity === null) return { intent: 'wait', text: 'Wait for hand', badgeClass: '', badgeText: '', color: 'var(--tnp-muted)', confidence: null, why: '' };
    if (!actionBtns || !(actionBtns.hasFold || actionBtns.hasCheck || actionBtns.hasCall || actionBtns.hasRaise)) {
      return { intent: 'wait', text: 'Wait for your turn', badgeClass: '', badgeText: '', color: 'var(--tnp-muted)', confidence: null, why: 'No action buttons visible; advice returns when it is your turn.' };
    }
    const holeForGuards = ctx.hole || [];
    const boardForGuards = ctx.board || [];
    const danger = boardDanger(holeForGuards, boardForGuards);
    const exposed = danger.tag !== '';
    const risk = ctx.risk ?? boardRisk(holeForGuards, boardForGuards);
    const pressured = !!(risk.suitThreat || risk.straightThreat);

    const boardSuitCounts = {};
    for (const c of boardForGuards) boardSuitCounts[c[1]] = (boardSuitCounts[c[1]] || 0) + 1;
    const boardMaxSuit = Math.max(0, ...Object.values(boardSuitCounts));
    const boardRankMask = boardForGuards.reduce((m, c) => m | (1 << RANK_VALS[c[0]]), 0);
    let boardRunSeq = 0;
    for (let hi = 14; hi >= 5; hi--) {
      let run = 0;
      for (let r = hi; r >= hi - 4 && r >= 2; r--) if (boardRankMask & (1 << r)) run++;
      boardRunSeq = Math.max(boardRunSeq, run);
    }
    const heroMade = holeForGuards.length === 2 && boardForGuards.length >= 3
      ? evaluateHand(holeForGuards.concat(boardForGuards)) : null;
    const flushBoardExposed = boardMaxSuit >= 4 && (heroMade === null || heroMade.type < 5);
    const straightBoardExposed = boardRunSeq >= 4 && (heroMade === null || heroMade.type < 4)
      && !(heroMade && heroMade.type >= 5);
    const drawWarning = (flushBoardExposed || straightBoardExposed)
      ? (flushBoardExposed
        ? `board shows ${boardMaxSuit} to a flush and you cannot beat it`
        : `board runs four to a straight and you cannot beat it`)
      : '';
    const potOddsReq = (toCall > 0 && pot > 0) ? toCall / (pot + toCall) : 0;

    const applyBoardGuardsToRec = (rec) => {
      if (!rec) return;
      const fs = 1 / (activeOpponents + 1);
      if (rec.intent === 'raise' && exposed && danger.hard && equity <= fs * 1.8) {
        rec.intent = (toCall > 0) ? 'call' : 'check';
        rec.text = textForIntent(rec.intent, actionBtns, toCall);
        rec.why += ` · board warning: ${danger.message}`;
        rec.badgeClass = 'tnp-badge-warning';
        rec.badgeText = 'CAREFUL';
      } else if (rec.intent === 'raise' && pressured && ctx.oppAggressive && equity <= fs * 1.8) {
        rec.intent = (toCall > 0) ? 'call' : 'check';
        rec.text = textForIntent(rec.intent, actionBtns, toCall);
        rec.why += ` · board risk: ${risk.message}`;
      }
      if (drawWarning && (rec.intent === 'raise' || rec.intent === 'call') && boardForGuards.length >= 4) {
        if (rec.intent === 'raise') {
          rec.intent = (toCall > 0) ? 'call' : 'check';
          rec.text = textForIntent(rec.intent, actionBtns, toCall);
          rec.why += ` · ${drawWarning}: value-raise demoted`;
          rec.badgeClass = 'tnp-badge-warning';
          rec.badgeText = 'CAREFUL';
        }
        if (rec.intent === 'call' && toCall > 0 && pot > 0
          && equity < potOddsReq && toCall >= 0.4 * pot) {
          rec.intent = 'fold';
          rec.text = textForIntent('fold', actionBtns, toCall);
          rec.why += ` · ${drawWarning}: the call price needs ${(potOddsReq * 100).toFixed(1)}% and you have ${(equity * 100).toFixed(1)}%`;
          rec.badgeClass = 'tnp-badge-danger';
          rec.badgeText = 'BEAT';
        }
      }
    };

    const { street = 'Preflop', position = 'MP', raiseLevel = 0, outs = null, hole = [], board = [], boardTexture = [], ciWidth = 0.02, realizedEquity = null, overfold = null, raiseReliable = true, noPreFlop = false, effStack = 0, seats = 0, oppAggressive = false,
      toCallUnknown = false, readIssues = null, potStale = false, preflopOpp = null, flopCtx = null } = ctx;
    const fairShare = 1 / (activeOpponents + 1);
    const potOddsRequired = (toCall > 0 && pot > 0 && !toCallUnknown) ? toCall / (pot + toCall) : 0;

    if (readIssues && readIssues.length) {
      return {
        intent: 'wait', text: 'Holding: table reads inconsistent', badgeClass: '', badgeText: '',
        color: 'var(--tnp-muted)', confidence: null,
        why: `Reads disagree (${readIssues.join('; ')}). Advice resumes when the table reads clean.`
      };
    }

    const adj = ctx.tableAdjust ?? getTableAdjust();
    const prof = strategyProfile();
    const bluffOk = adj['bluffOk'] !== false && prof.bluff >= 1;
    const extraWhy = [];

    const eqrDial = 1;
    const pressureMargin = (pressured && oppAggressive) ? Math.max(0, 0.10 * eqrDial) : 0;

    let of = (overfold && street === 'River' && activeOpponents === 1
      && toCall === 0 && pot > 0 && overfold.ev > 0) ? overfold : null;
    if (exposed && danger.hard) of = null;

    let intent;
    if (street === 'Preflop' && hole.length === 2) {

      const effectiveRaiseLevel = raiseReliable ? raiseLevel : (toCall > 0 ? 1 : 0);
      const oppNotes = [];
      intent = getPreflopIntent(hole, position, effectiveRaiseLevel, activeOpponents,
        toCall,
        { noPreFlop: !!ctx.noPreFlop, seats: seats || 0, opp: preflopOpp, oppNotes, toCallUnknown: !!toCallUnknown });
      for (const n of oppNotes) extraWhy.push(n);
      if (intent === 'fold' && toCall > 0 && pot > 0 && !toCallUnknown && equity > potOddsRequired + 0.10) intent = 'call';
      if (intent === 'fold' && toCallUnknown && equity >= fairShare * 0.9) intent = 'call';

    } else if (toCall > 0 || toCallUnknown) {

      const eqEff = realizedEquity ?? equity;
      const isBigDraw = outs !== null && outs >= 8 && street !== 'River';

      const impliedOdds = (!toCallUnknown && isBigDraw && effStack >= toCall * 12) ? 0.03 : 0;
      const drawBonus = (outs !== null && street !== 'River') ? Math.min(0.06, outs * 0.006) : 0;
      const required = toCallUnknown
        ? fairShare * 0.95
        : potOddsRequired + adj.callAdj + pressureMargin + (exposed ? 0.08 + Math.min(0.08, 0.03 * (activeOpponents - 1)) : 0);
      const raiseMargin = (0.10 + 0.02 * activeOpponents + adj.valueAdj) * prof.value;
      if (eqEff > Math.max(required + raiseMargin, fairShare * 1.35)) intent = 'raise';
      else if (!toCallUnknown && isBigDraw && bluffOk && toCall <= pot * 0.5 && eqEff + drawBonus > required) intent = 'raise';
      else if (eqEff + drawBonus + impliedOdds > required) intent = 'call';
      else intent = 'fold';

      if (exposed && intent === 'raise') intent = 'call';

      if (pressured && oppAggressive && intent === 'raise' && equity <= fairShare * 1.8) intent = 'call';
    } else {
      const isBigDraw = outs !== null && outs >= 8 && street !== 'River';

      const valueCut = fairShare * (1.40 * prof.value + adj.valueAdj * 2 + (of ? 0.15 : 0));
      if (equity > valueCut) intent = 'raise';
      else if (isBigDraw && bluffOk) intent = 'raise';
      else if (bluffOk && activeOpponents === 1 && boardTexture.includes('Dry')
          && equity > fairShare * 0.9) intent = 'raise';

      else if (bluffOk && activeOpponents === 1 && street === 'Flop'
        && flopCtx && flopCtx.cbetFoldOpp >= 5 && flopCtx.cbetFold >= 65
        && equity > fairShare * 0.75) {
        intent = 'raise';
        extraWhy.push(`${flopCtx.name} folds ${flopCtx.cbetFold}% to c-bets (${flopCtx.cbetFoldOpp} faced): c-bet this flop`);
      }

      else if (of && bluffOk && equity < fairShare * 0.9 && of.ev > equity * pot) intent = 'raise';
      else intent = 'check';

      if (exposed && intent === 'raise' && equity <= fairShare * 1.8) intent = 'check';

      if (pressured && oppAggressive && intent === 'raise' && equity <= fairShare * 1.8) intent = 'check';
    }

    const decisionThreshold = toCallUnknown ? fairShare * 0.95 : (toCall > 0 ? potOddsRequired : fairShare);
    const edge = equity - decisionThreshold;
    let confidence = Math.max(0.5, Math.min(0.97, 0.5 + Math.abs(edge) * 1.8 - Math.min(0.15, ciWidth)));
    if (street === 'Preflop' && hole.length === 2) confidence = Math.min(confidence, 0.9);
    if (toCallUnknown || potStale) confidence = Math.min(confidence, 0.7);
    const confidenceWord = confidence >= 0.78 ? 'High' : confidence >= 0.62 ? 'Medium' : 'Low';

    let why;
    if (toCallUnknown) {
      why = `Facing a bet whose size did not read; priced by equity vs the ${(fairShare * 100).toFixed(0)}% field average, not pot odds`;
    } else if (toCall > 0 && pot > 0) {
      const eqShown = realizedEquity ?? equity;
      const adjusted = realizedEquity !== null && Math.abs(realizedEquity - equity) > 0.005;

      why = `Pot odds: call $${toCall.toLocaleString()} into $${Math.round(pot).toLocaleString()}. Break-even ${(potOddsRequired * 100).toFixed(1)}% vs ${Math.round(eqShown * 100)}%${adjusted ? ' (adj.)' : ''} equity`;
    } else {
      why = `Estimated equity ${(equity * 100).toFixed(0)}% vs ${(fairShare * 100).toFixed(0)}% field average (${activeOpponents} opp)`;
    }
    if (outs !== null && outs >= 8 && street !== 'River') why += ` · big draw (${outs} outs)`;
    if (adj.callAdj !== 0 || adj.valueAdj !== 0) why += ' · table-profile adjusted';
    if (noPreFlop && street === 'Preflop' && hole.length === 2) why += ' · No-Pre-flop table: raising is off before the flop';
    if (of) why += ` · river read: ${of.name} folds ${of.folded}/${of.faced} vs river bets (floor ${Math.round(of.lb * 100)}% vs ${Math.round(of.be * 100)}% needed)`;
    if (exposed) why += ` · board warning: ${danger.message}`;
    else if (pressured && oppAggressive) why += ` · board risk: ${risk.message} (call price +${Math.round(pressureMargin * 100)}%)`;
    else if (pressured) why += ` · board risk: ${risk.message}`;
    if (potStale) why += ' · pot read stale (using the last good pot)';
    if (settings.strategyProfile !== 'balanced') why += ` · ${strategyProfile().label} profile thresholds`;
    for (const n of extraWhy) why += ` · ${n}`;

    const ACT_COLORS = {
      fold: 'var(--tnp-act-fold)', check: 'var(--tnp-act-check)',
      call: 'var(--tnp-act-call)', raise: 'var(--tnp-act-raise)'
    };
        if (intent === 'fold' && actionBtns.hasCheck) intent = 'check';

    const actKind = classifyButtonAction(textForIntent(intent, actionBtns, toCall));
    const color = actKind ? ACT_COLORS[actKind] : 'var(--tnp-muted)';

    const recommendedText = textForIntent(intent, actionBtns, toCall);

    if (!recommendedText) return { intent: 'wait', text: 'Waiting...', badgeClass: '', badgeText: '', color: 'var(--tnp-muted)', confidence: null, why: '' };

    let badgeClass = 'tnp-badge-danger', badgeText = 'WEAK';
    if (equity > fairShare * 1.3) { badgeClass = 'tnp-badge-success'; badgeText = 'STRONG'; }
    else if (equity > fairShare * 0.8) { badgeClass = 'tnp-badge-warning'; badgeText = 'MARGINAL'; }

    return { intent, text: recommendedText, badgeClass, badgeText, color, confidence, confidenceWord, why,
      requiredEquity: decisionThreshold, edge, opponents: activeOpponents };
  };

  let highlightedCards = new Set();

  const clearCardHighlights = () => {
    for (const el of highlightedCards) {
      if (document.contains(el)) el.classList.remove('tnp-card-highlight');
    }
    highlightedCards.clear();
  };

  const highlightContributingCards = (hole, board, evalResult) => {
    if (!settings.cardHighlight || !hole?.length || !evalResult) return;

    const allCards = [...hole, ...board];
    if (allCards.length < 5) { clearCardHighlights(); return; }
    const { score, type } = evalResult;

    const ranks = allCards.map(c => RANK_VALS[c[0]]);
    const suits = allCards.map(c => c[1]);

    const contributing = new Set();

    if (type >= 8) {
      const suitCounts = {};
      for (const s of suits) suitCounts[s] = (suitCounts[s] ?? 0) + 1;
      let flushSuit = null;
      for (const s in suitCounts) if (suitCounts[s] >= 5) { flushSuit = s; break; }
      if (flushSuit !== null) {
        const flushCards = allCards.map((c, i) => ({ c, i, r: RANK_VALS[c[0]] }))
          .filter(x => x.c[1] === flushSuit).sort((a, b) => b.r - a.r);
        for (let i = 0; i < Math.min(5, flushCards.length); i++) contributing.add(flushCards[i].i);
      }
    } else if (type === 7) {
      const mainRank = (score >> 16) & 0xF;
      allCards.forEach((c, i) => { if (RANK_VALS[c[0]] === mainRank) contributing.add(i); });
    } else if (type === 6) {
      const mainRank = (score >> 16) & 0xF;
      const pairRank = (score >> 12) & 0xF;
      allCards.forEach((c, i) => {
        const r = RANK_VALS[c[0]];
        if (r === mainRank || r === pairRank) contributing.add(i);
      });
    } else if (type === 5) {
      const suitCounts = {};
      for (const s of suits) suitCounts[s] = (suitCounts[s] ?? 0) + 1;
      let flushSuit = null;
      for (const s in suitCounts) if (suitCounts[s] >= 5) { flushSuit = s; break; }
      if (flushSuit !== null) {
        const flushCards = allCards.map((c, i) => ({ c, i }))
          .filter(x => x.c[1] === flushSuit).sort((a, b) => RANK_VALS[b.c[0]] - RANK_VALS[a.c[0]]);
        for (let i = 0; i < Math.min(5, flushCards.length); i++) contributing.add(flushCards[i].i);
      }
    } else if (type === 4) {
      const uniqueRanks = [...new Set(ranks)].sort((a, b) => b - a);
      let straightHigh = (score >> 16) & 0xF;
      if (straightHigh === 5) {
        const wheelRanks = [14, 5, 4, 3, 2];
        for (const wr of wheelRanks) {
          const idx = allCards.findIndex((c, i) => RANK_VALS[c[0]] === wr && !contributing.has(i));
          if (idx >= 0) contributing.add(idx);
        }
      } else {
        for (let r = straightHigh; r > straightHigh - 5; r--) {
          const idx = allCards.findIndex((c, i) => RANK_VALS[c[0]] === r && !contributing.has(i));
          if (idx >= 0) contributing.add(idx);
        }
      }
    } else if (type === 3) {
      const mainRank = (score >> 16) & 0xF;
      allCards.forEach((c, i) => { if (RANK_VALS[c[0]] === mainRank) contributing.add(i); });
    } else if (type === 2) {
      const mainRank = (score >> 16) & 0xF;
      const pairRank = (score >> 12) & 0xF;
      allCards.forEach((c, i) => {
        const r = RANK_VALS[c[0]];
        if (r === mainRank || r === pairRank) contributing.add(i);
      });
    } else if (type === 1) {
      const mainRank = (score >> 16) & 0xF;
      allCards.forEach((c, i) => { if (RANK_VALS[c[0]] === mainRank) contributing.add(i); });
    }

    const nextHighlights = new Set();
    const seat = findOwnSeat();
    if (seat) {
      const gateway = document.querySelector('[class*="playerMeGateway___"]');
      const highlightRoot = gateway || seat;
      const holeCardEls = highlightRoot.querySelectorAll('[class*="card"], [role="img"], [class*="front___"] > div');
      const parsedEls = [];
      for (const el of holeCardEls) {
        if (el.closest?.('[class*="communityCards"]')) continue;
        for (const card of extractCardStrings(el)) parsedEls.push({ el, card });
      }
      const liveEls = parsedEls.slice(-2);
      for (let i = 0; i < liveEls.length && i < hole.length; i++) {
        if (contributing.has(i)) {
          nextHighlights.add(liveEls[i].el);
        }
      }
    }

    const boardEls = document.querySelectorAll('[class*="communityCards"] [class*="card"], [class*="communityCards"] [role="img"]');
    let boardIdx = 0;
    for (const el of boardEls) {
      const card = extractCardString(el);
      if (card && boardIdx < board.length) {
        if (contributing.has(hole.length + boardIdx)) {
          nextHighlights.add(el);
        }
        boardIdx++;
      }
    }

    for (const el of highlightedCards) {
      if (!nextHighlights.has(el) && document.contains(el)) el.classList.remove('tnp-card-highlight');
    }
    for (const el of nextHighlights) {
      if (!highlightedCards.has(el)) el.classList.add('tnp-card-highlight');
    }
    highlightedCards = nextHighlights;
  };

  const renderSeatBadges = () => {
    if (settings.hudEnabled === false) return;
    const seats = getAllSeats();
    const me = findOwnSeat();

    for (const seat of seats) {
      if (isOwnPlayerSeat(seat, me)) continue;
      if (isSeatEmpty(seat) || isSeatSittingOut(seat)) continue;

      const oldBadge = seat.querySelector('.tnp-seat-badge');
      if (!settings.showHUD) {
        if (oldBadge) oldBadge.remove();
        continue;
      }

      const player = getPlayerName(seat);
      if (!player) {
        if (oldBadge) oldBadge.remove();
        continue;
      }

      const p = profiles[player.id];

      if (!p || profileTier(p.handsObserved) === 'unknown') {
        if (oldBadge) oldBadge.remove();
        continue;
      }

      const type = classifyPlayer(p);
      const typeDef = PLAYER_TYPES[type];
      const metrics = getProfileMetrics(p);
      if (!metrics) {
        if (oldBadge) oldBadge.remove();
        continue;
      }

      const badgeKey = `${typeDef.short}|${metrics.vpip}|${metrics.pfr}|${metrics.afq}|${metrics.wtsd}|${metrics.hands}`;

      if (oldBadge && oldBadge.dataset.badgeKey === badgeKey) continue;
      if (oldBadge) oldBadge.remove();

      const badge = document.createElement('button');
      badge.type = 'button';
      badge.className = 'tnp-seat-badge';
      badge.dataset.badgeKey = badgeKey;
      badge.setAttribute('aria-label', `Open local profile for ${player.name} (${metrics.hands} hands, ${metrics.tierLabel})`);
      badge.innerHTML = `<div class="tnp-player-badge" style="background:${typeDef.color}" title="${typeDef.label} | VPIP:${metrics.vpip}% PFR:${metrics.pfr}% AFq:${metrics.afq}%${metrics.afqKnown ? '' : ` (thin: ${metrics.afqSample}/${MIN_AFQ_POSTFLOP_ACTIONS} postflop actions, not driving advice)`} WTSD:${metrics.wtsd}% | ${metrics.hands} hands | ${metrics.tierLabel}">${typeDef.short}</div>`;

      if (getComputedStyle(seat).position === 'static') seat.style.position = 'relative';
      seat.appendChild(badge);

      badge.addEventListener('click', (e) => {
        e.stopPropagation();
        showPlayerProfile(player.id);
      });
    }
  };

  const switchTab = (tabName) => {
    activeTab = tabName;
    if (!uiElement) return;
    uiElement.querySelectorAll('.tnp-tab').forEach(t => {
      const active = t.dataset.tab === tabName;
      t.classList.toggle('active', active);
      t.setAttribute('aria-selected', active ? 'true' : 'false');
      t.tabIndex = active ? 0 : -1;
    });
    uiElement.querySelectorAll('.tnp-panel').forEach(p => p.classList.toggle('active', p.id === `tnp-panel-${tabName}`));
  };

  const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, ch => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
  }[ch]));

  const showPlayerProfile = (playerId) => {
    const p = profiles[playerId];
    const note = playerNotes[playerId] || '';

    switchTab('opponents');
    renderUI();

    setTimeout(() => {
      const notesInput = document.getElementById('tnp-notes-textarea');
      if (notesInput) {
        notesInput.value = note;
        notesInput.dataset.playerId = playerId;
        notesInput.focus();
      }
      const profileDetail = document.getElementById('tnp-profile-detail');
      if (!profileDetail) return;
      const m = getProfileMetrics(p);
      if (!p || !m) {
        const fallbackName = (p?.name) ?? String(playerId).replace(/^(?:xid|name):/, '');
        profileDetail.innerHTML = `<div class="tnp-exploit-hint">No stats for ${escapeHtml(fallbackName)} yet; a few more hands will fill these in. Notes work below.</div>`;
        return;
      }
      const type = classifyPlayer(p);
      const typeDef = PLAYER_TYPES[type];
      const sv = (v, suffix = '%') => v === null || v === undefined ? '-' : `${v}${suffix}`;
      const statExploits = settings.showExploit ? getStatExploits(m) : [];
      const archetypeHint = settings.showExploit ? getExploitHint(type, m.hands) : null;
      const tierClass = { tentative: 'tnp-tier-tentative', developing: 'tnp-tier-developing', established: 'tnp-tier-established' }[m.tier] ?? '';
      const freshness = m.lastSeenAgeMin !== null
        ? `Last observed ${m.lastSeenAgeMin < 60 ? `${m.lastSeenAgeMin}m` : m.lastSeenAgeMin < 1440 ? `${Math.round(m.lastSeenAgeMin / 60)}h` : `${Math.round(m.lastSeenAgeMin / 1440)}d`} ago · decay keeps old samples ${m.decayPct}% relevant`
        : 'No freshness data';
      const adjNote = 'Share of hands entered by call or raise, blinds aside. Under 20% tight, 20-30% normal, over 40% loose. Small samples blend toward 30%.';
      profileDetail.innerHTML = `
          <div class="tnp-player-row">
            <div class="tnp-player-badge" style="background:${typeDef.color}">${typeDef.short}</div>
            <div class="tnp-player-name">${escapeHtml(p.name)}</div>
            <div class="tnp-player-stats" title="Read confidence grows with hands observed">conf ${m.confidence}%</div>
          </div>
          <div class="tnp-row" style="margin-top: 2px;">
            <span class="tnp-tier-tag ${tierClass}">${escapeHtml(m.tierLabel)}</span>
            <span class="tnp-freshness">${escapeHtml(freshness)}</span>
          </div>
          <div class="tnp-stat-grid">
            <div class="tnp-stat-box" title="${adjNote}"><div class="tnp-stat-label">VPIP (adj)</div><div class="tnp-stat-val">${m.vpip}%</div></div>
            <div class="tnp-stat-box" title="Share of hands opened with a raise. Close to VPIP: aggressive; far below: passive."><div class="tnp-stat-label">PFR (adj)</div><div class="tnp-stat-val">${m.pfr}%</div></div>
            <div class="tnp-stat-box" title="Bets and raises as a share of postflop actions. Under 30% passive, over 60% very aggressive."><div class="tnp-stat-label">AFq</div><div class="tnp-stat-val">${m.afq}%</div></div>
            <div class="tnp-stat-box" title="Classic aggression factor: postflop (bets+raises) divided by calls. 1.5-3 is aggressive, under 1 passive. Quoted after 6 postflop actions."><div class="tnp-stat-label">AF</div><div class="tnp-stat-val">${escapeHtml(afLabelOf(m.af))}${m.af.sample ? ` <span style="font-size:9px;color:var(--tnp-text-faint)">·${m.af.sample}</span>` : ''}</div></div>
            <div class="tnp-stat-box" title="Share of seen flops that reach showdown. Over 30% calls too much."><div class="tnp-stat-label">WTSD</div><div class="tnp-stat-val">${m.wtsd}%</div></div>
            <div class="tnp-stat-box" title="Hands actually observed at your tables."><div class="tnp-stat-label">Hands</div><div class="tnp-stat-val">${m.hands}</div></div>
            <div class="tnp-stat-box" title="Preflop re-raises over chances faced. Over 10% mixes in bluffs; under 5% premiums only."><div class="tnp-stat-label">3-Bet</div><div class="tnp-stat-val">${sv(m.threeBet)}</div></div>
            <div class="tnp-stat-box" title="Folds vs a preflop re-raise. Over 60% folds under pressure."><div class="tnp-stat-label">Fold→3B</div><div class="tnp-stat-val">${sv(m.foldTo3Bet)}</div></div>
            <div class="tnp-stat-box" title="Flop bets by the preflop raiser over chances. Over 70% bets any flop."><div class="tnp-stat-label">C-Bet</div><div class="tnp-stat-val">${sv(m.cbet)}</div></div>
            <div class="tnp-stat-box" title="Folds vs a flop continuation bet. Over 60% can be c-bet often."><div class="tnp-stat-label">Fold→CB</div><div class="tnp-stat-val">${sv(m.foldToCbet)}</div></div>
            <div class="tnp-stat-box" title="Entered by just calling the big blind. 30%+ marks a passive player; raise their limps."><div class="tnp-stat-label">Limp</div><div class="tnp-stat-val">${sv(m.limp)}</div></div>
            <div class="tnp-stat-box" title="First-in raises over first-in chances (position-blind: the log names no button)."><div class="tnp-stat-label">Open</div><div class="tnp-stat-val">${sv(m.open)}</div></div>
            <div class="tnp-stat-box" title="Blind folds vs a lone first-in raise."><div class="tnp-stat-label">Fold→Open</div><div class="tnp-stat-val">${sv(m.foldToOpen)}</div></div>
            <div class="tnp-stat-box" title="Folds vs heads-up river bets. Over 60%: river bluffs gain value."><div class="tnp-stat-label">Fold→RivBet</div><div class="tnp-stat-val">${sv(m.foldToRiverBet)}</div></div>
            <div class="tnp-stat-box" title="Aggression by street (flop / turn / river). A late drop means they slow down strong."><div class="tnp-stat-label">Agg F/T/R</div><div class="tnp-stat-val">${sv(m.aggFlop, '')}/${sv(m.aggTurn, '')}/${sv(m.aggRiver, '')}</div></div>
            <div class="tnp-stat-box" title="Average raise size in big blinds. Under 3bb passive; over 5bb punishes calls."><div class="tnp-stat-label">Avg Raise</div><div class="tnp-stat-val">${m.avgRaiseBB !== null ? m.avgRaiseBB + 'bb' : '-'}</div></div>
          </div>
          ${archetypeHint ? `<div class="tnp-exploit-hint">${archetypeHint}</div>` : ''}
          ${statExploits.map(t => `<div class="tnp-exploit-hint">${t}</div>`).join('')}
        `;
    }, 50);
  };

  const setText = (el, text) => {
    if (!el) return;
    const s = text === null || text === undefined ? '' : String(text);
    if (el.__tnpContent === 'T' + s) return;
    el.__tnpContent = 'T' + s;
    el.textContent = s;
  };
  const setSessionValue = (el, text, known = true) => {
    if (!el) return;
    el.classList.toggle('tnp-session-unknown', !known);
    el.title = known ? '' : 'Not observed yet, so this is not a confirmed zero.';
    setText(el, known ? text : 'n/a');
  };
  const setHTML = (el, html) => {
    if (!el) return;
    const s = html === null || html === undefined ? '' : String(html);
    if (el.__tnpContent === 'H' + s) return;
    el.__tnpContent = 'H' + s;
    el.innerHTML = s;
  };

  const injectCSS = () => {
    if (document.getElementById('tnp-style')) return;
    const style = document.createElement('style');
    style.id = 'tnp-style';
    style.textContent = NOIR_CSS + NOIR_UI2_CSS;
    (document.head || document.documentElement || document.body)?.appendChild(style);
  };

  const updateMobileMode = () => {
    if (!uiElement) return;
    const narrowViewport = typeof window.matchMedia === 'function'
      && window.matchMedia('(max-width: 768px)').matches;
    const mobile = isMobile() || narrowViewport;
    uiElement.classList.toggle('tnp-pda', mobile);
    uiElement.dataset.environment = mobile ? 'pda' : 'desktop';
  };

  const applyHudEnabled = () => {
    if (!uiElement) return;
    uiElement.classList.toggle('tnp-hidden', settings.hudEnabled !== true);
    if (settings.hudEnabled === false) {
      clearCardHighlights();
      document.querySelectorAll('.tnp-seat-badge').forEach(el => el.remove());
    }
  };
  const applyDisplayMode = () => {
    if (!uiElement) return;
    uiElement.classList.toggle('tnp-mode-compact', settings.displayMode === 'compact');
    uiElement.classList.toggle('tnp-mode-minimal', settings.displayMode === 'minimal');
  };

  const applyVisualSettings = () => {
    if (!uiElement) return;
    uiElement.style.setProperty('--tnp-scale', String(settings.fontScale));
    uiElement.classList.toggle('tnp-hc', settings.highContrast);
    uiElement.classList.toggle('tnp-opaque', settings.reducedTransparency);
    uiElement.style.opacity = String(settings.panelOpacity);
  };

  const buildUI = () => {
    const existing = document.getElementById('tnp-dossier');
    if (existing) {
      uiElement = existing;
      updateMobileMode();
      return;
    }

    uiElement = document.createElement('div');
    uiElement.id = 'tnp-dossier';

    uiElement.setAttribute('role', 'region');
    uiElement.setAttribute('aria-label', 'Poker analysis HUD');
    uiElement.innerHTML = `
      <div id="tnp-header">
        <div class="tnp-title-wrap">
          <div class="tnp-title">Poker Hold’em <span class="tnp-version">v${SCRIPT_VERSION}</span></div>
        </div>
        <div class="tnp-header-actions">
          <div id="tnp-status-chip" title="Analysis status" aria-live="off">Ready</div>
          <div id="tnp-health-badge" class="tnp-hidden" title="" aria-label="Table read warning"></div>
          <button type="button" id="tnp-toggle" aria-label="Minimize dossier" aria-expanded="true" aria-controls="tnp-body"></button>
        </div>
      </div>
      <div id="tnp-body">
        <div id="tnp-folded-overlay" class="tnp-hidden">YOU FOLDED</div>
        <div id="tnp-body-content" style="display: flex; flex-direction: column; gap: 10px;">

          <div id="tnp-pause-overlay" class="tnp-hidden" role="status">
            <div id="tnp-pause-msg">Paused: open and focus the table to resume.</div>
          </div>

          <div id="tnp-parser-banner" role="status">
            <span>Table layout changed. Analysis paused.</span>
            <button type="button" class="tnp-text-btn" id="tnp-parser-banner-dismiss">Dismiss</button>
          </div>

          <div id="tnp-compact-body">
            <div class="tnp-minimal-row"><span class="tnp-label">Equity (est.)</span><span class="tnp-value tnp-accent" id="tnp-compact-equity">-</span></div>
            <div class="tnp-compact-grid">
              <span class="tnp-label">Position</span><span class="tnp-value" id="tnp-compact-position">-</span>
              <span class="tnp-label">Pot odds</span><span class="tnp-value" id="tnp-compact-potodds">-</span>
              <span class="tnp-label">Hand</span><span class="tnp-value" id="tnp-compact-strength">-</span>
              <span class="tnp-label">Advice</span><span class="tnp-value" id="tnp-compact-signal">-</span>
            </div>
            <div class="tnp-freshness" id="tnp-compact-confidence">-</div>
            <button type="button" class="tnp-text-btn tnp-mode-restore" id="tnp-compact-restore">Full view</button>
          </div>

          <div id="tnp-minimal-body">
            <div class="tnp-minimal-row">
              <span class="tnp-minimal-status" id="tnp-minimal-status">Ready</span>
              <span class="tnp-value tnp-accent" id="tnp-minimal-equity">-</span>
            </div>
            <button type="button" class="tnp-text-btn tnp-mode-restore" id="tnp-minimal-restore">Full view</button>
          </div>

          <div id="tnp-action-banner" aria-live="polite">
            <div class="tnp-banner-action" id="tnp-banner-action">-</div>
            <div class="tnp-banner-sub" id="tnp-banner-sub"></div>
          </div>

          <div id="tnp-full-body" style="display: flex; flex-direction: column; gap: 10px;">
          <div class="tnp-tabs" role="tablist" aria-label="HUD sections">
            <button type="button" class="tnp-tab active" role="tab" aria-selected="true" data-tab="analysis">Analysis</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="opponents">Foes</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="you">You</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="session">Session</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="bankroll">Bankroll</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="replay">Replay</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="drill">Drill</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="diagnostics">Diag</button>
            <button type="button" class="tnp-tab" role="tab" aria-selected="false" data-tab="settings">Setup</button>
          </div>

          <div class="tnp-panel active" id="tnp-panel-analysis">
            <div class="tnp-row">
              <div class="tnp-label">Hole Cards</div>
              <div class="tnp-cards-display" id="tnp-hole-cards"></div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Board <span id="tnp-street" style="color:var(--tnp-muted)"></span></div>
              <div class="tnp-cards-display" id="tnp-board-cards"></div>
            </div>
            <div class="tnp-timeline" id="tnp-timeline" aria-label="Current hand streets">
              <span class="tnp-timeline-step tnp-timeline-now" data-street="Preflop">Pre</span>
              <span class="tnp-timeline-step" data-street="Flop">Flop</span>
              <span class="tnp-timeline-step" data-street="Turn">Turn</span>
              <span class="tnp-timeline-step" data-street="River">River</span>
            </div>
            <div class="tnp-row" style="margin-top: 2px;">
              <div class="tnp-label">Position</div>
              <div class="tnp-value" id="tnp-position-read" title="Your seat this hand; (est.) marks a fallback read.">-</div>
            </div>
            <div class="tnp-range-chips" id="tnp-range-chips"></div>
            <div class="tnp-row">
              <div class="tnp-label">Hand Strength</div>
              <div class="tnp-value" id="tnp-relative-strength" title="Your best five-card hand right now.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Pot Odds</div>
              <div class="tnp-value" id="tnp-potodds" title="The call price as a share of the pot; call when your win chance beats it. The HUD's most important number.">-</div>
            </div>
            <div id="tnp-decision" class="tnp-decision tnp-hidden">
              <div class="tnp-decision-verdict tnp-verdict-neutral" id="tnp-decision-verdict">—</div>
              <div class="tnp-stat-grid">
                <div class="tnp-stat-box"><div class="tnp-stat-label">Pot</div><div class="tnp-stat-val" id="tnp-d-pot">-</div></div>
                <div class="tnp-stat-box"><div class="tnp-stat-label">Call</div><div class="tnp-stat-val" id="tnp-d-call">-</div></div>
                <div class="tnp-stat-box"><div class="tnp-stat-label">Req. Eq.</div><div class="tnp-stat-val" id="tnp-d-req">-</div></div>
                <div class="tnp-stat-box"><div class="tnp-stat-label">Your Eq.</div><div class="tnp-stat-val" id="tnp-d-eq">-</div></div>
                <div class="tnp-stat-box"><div class="tnp-stat-label">Eq. Gap</div><div class="tnp-stat-val" id="tnp-d-gap">-</div></div>
                <div class="tnp-stat-box"><div class="tnp-stat-label">Call EV</div><div class="tnp-stat-val" id="tnp-d-ev">-</div></div>
              </div>
              <div class="tnp-ev-gauge" id="tnp-ev-gauge" title="Green bar: your win equity covers the call price (positive expected value). Red bar: calling loses money in the long run. The white tick marks the exact break-even percentage.">
                <div class="tnp-ev-gauge-fill" id="tnp-ev-gauge-fill"></div>
                <div class="tnp-ev-gauge-req" id="tnp-ev-gauge-req"></div>
              </div>
              <div class="tnp-freshness" id="tnp-ev-gauge-note"></div>
              <div class="tnp-freshness" id="tnp-decision-note"></div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Outs</div>
              <div class="tnp-value" id="tnp-outs" title="Live cards that make your hand the likely winner. x4 on the flop, x2 on the turn for the win %.">-</div>
            </div>
            <div class="tnp-outs-cards" id="tnp-outs-cards"></div>
            <hr class="tnp-divider">
            <button type="button" class="tnp-details-toggle" id="tnp-details-toggle">Details</button>
            <div id="tnp-detail-rows" style="display: flex; flex-direction: column; gap: 8px;">
            <div class="tnp-row">
              <div class="tnp-label">Blockers</div>
              <div class="tnp-value" id="tnp-blockers" title="Cards you hold that opponents cannot have.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Context</div>
              <div class="tnp-value" id="tnp-context" title="Pot size, players in, your seat.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Call EV</div>
              <div class="tnp-value" id="tnp-callev" title="Expected chips from calling: your pot share minus the call cost.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">MDF</div>
              <div class="tnp-value" id="tnp-mdf" title="How often you must not fold, or pure bluffs profit. Early streets can sit below it.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">SPR</div>
              <div class="tnp-value" id="tnp-spr" title="Effective stack divided by pot (this read uses your stack). Under 3 committed, above 7 room to play.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Realized Eq.</div>
              <div class="tnp-value" id="tnp-realized" title="Equity adjusted for position and opponent count.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Opponents</div>
              <div class="tnp-value" id="tnp-opponents" title="Players still in against you.">-</div>
            </div>
            </div>
            <hr class="tnp-divider">
            <div class="tnp-row">
              <div class="tnp-label">Advice</div>
              <div class="tnp-value" id="tnp-advice" title="The suggested play, from pot odds, equity and opponents." style="color: var(--tnp-muted); text-align: right; max-width: 200px;">-</div>
            </div>
            <div id="tnp-bet-sizing" style="font-size: var(--tnp-fz-xs); color: var(--tnp-muted); text-align: right;"></div>
            <button type="button" class="tnp-details-toggle" id="tnp-why-toggle">Why this advice</button>
            <div id="tnp-why-panel"></div>
            <div id="tnp-last-decision" class="tnp-last-decision"></div>
            <div class="tnp-row" style="margin-top: 4px;">
              <div class="tnp-label" style="color: var(--tnp-accent-2);">Win Equity</div>
              <div class="tnp-value tnp-accent" id="tnp-equity" title="Your chance to win at showdown, from the visible cards.">-</div>
            </div>
            <div class="tnp-equity-bar">
              <div class="tnp-equity-fill" id="tnp-equity-fill"></div>
              <div class="tnp-equity-ci" id="tnp-equity-ci"></div>
              <div class="tnp-equity-tick" id="tnp-equity-tick"></div>
            </div>
            <div id="tnp-equity-ci-text" style="font-size: var(--tnp-fz-2xs); color: var(--tnp-muted); text-align: center;" title="The 95% band around the estimate. Sampling carries noise; exact enumeration does not."></div>
            <div id="tnp-hand-type-dist" style="font-size: var(--tnp-fz-2xs); color: var(--tnp-muted); display: flex; flex-wrap: wrap; gap: 4px;"></div>
          </div>

          <div class="tnp-panel" id="tnp-panel-opponents">
            <div class="tnp-heat-line" id="tnp-table-heat"></div>
            <button type="button" class="tnp-details-toggle" id="tnp-stat-guide-toggle" title="Plain-English definitions of the numbers this HUD shows">Stat guide (new to poker?)</button>
            <div id="tnp-stat-guide" class="tnp-hidden">
              <div class="tnp-guide-row"><b>VPIP</b><span>Enters by call or raise. Under 20% tight, 20-30% normal, over 40% loose.</span></div>
              <div class="tnp-guide-row"><b>PFR</b><span>Opens with a raise. Close to VPIP: aggressive. Far below: passive.</span></div>
              <div class="tnp-guide-row"><b>AFq</b><span>Bets and raises as a share of postflop actions. Under 30% passive, over 60% very aggressive.</span></div>
              <div class="tnp-guide-row"><b>WTSD</b><span>Seen flops that reach showdown. Over 30% calls too much.</span></div>
              <div class="tnp-guide-row"><b>3-Bet</b><span>A preflop re-raise. Over 10% mixes in bluffs; under 5% premiums only.</span></div>
              <div class="tnp-guide-row"><b>C-Bet</b><span>The preflop raiser betting the flop. Over 70% bets any flop.</span></div>
              <div class="tnp-guide-row"><b>Pot odds</b><span>The call price as a share of the pot. Call when your win chance beats it.</span></div>
              <div class="tnp-guide-row"><b>Outs</b><span>Live cards that make your hand. Outs x4 on the flop, x2 on the turn = win %.</span></div>
              <div class="tnp-guide-row"><b>Equity</b><span>Your chance to win at showdown, from the visible cards.</span></div>
              <div class="tnp-guide-row"><b>Workers</b><span>Sampler threads behind the last estimate. More threads tighten the band faster.</span></div>
              <div class="tnp-guide-row"><b>Implied odds</b><span>Pot odds plus the chips you expect to win when a draw hits.</span></div>
              <div class="tnp-guide-row"><b>Reverse implied odds</b><span>Chips you lose when your hand improves but stays second-best.</span></div>
              <div class="tnp-guide-row"><b>Set mining</b><span>Calling with a small pair to flop trips (about 1 in 8.5), so the price must be small and the payoff large.</span></div>
              <div class="tnp-guide-row"><b>MDF</b><span>The share you must not fold so pure bluffs cannot profit.</span></div>
              <div class="tnp-guide-row"><b>Effective stack</b><span>The smaller stack in the hand; it sets the true all-in limit.</span></div>
              <div class="tnp-guide-row"><b>SPR</b><span>Effective stack divided by pot. Under 3 committed, above 7 room to play.</span></div>
              <div class="tnp-guide-row"><b>(adj)</b><span>Small samples blend toward a neutral 30% prior. Raw counts stay on your device.</span></div>
            </div>
            <div id="tnp-opponents-list" style="display: flex; flex-direction: column; gap: 5px;"></div>
            <hr class="tnp-divider">
            <div id="tnp-profile-detail"></div>
            <div class="tnp-label">Player Notes</div>
            <textarea class="tnp-notes-input" id="tnp-notes-textarea" placeholder="Select an opponent above to add notes..."></textarea>
          </div>

          <div class="tnp-panel" id="tnp-panel-you">
            <div id="tnp-mirror-head"></div>
            <div class="tnp-stat-grid" id="tnp-mirror-grid"></div>
            <hr class="tnp-divider">
            <div class="tnp-label">Showdown ledger</div>
            <div id="tnp-mirror-ledger"></div>
            <hr class="tnp-divider">
            <div class="tnp-label" title="Patterns in your own play the sample supports.">Leak notes</div>
            <div id="tnp-mirror-leaks"></div>
            <div style="font-size:var(--tnp-fz-xs); color:var(--tnp-muted); margin-top:6px;">Counted from hands where the log shows your action. Ledger net = pots won minus every chip you put in, blinds included. Stays on your device.</div>
          </div>

          <div class="tnp-panel" id="tnp-panel-session">
            <div class="tnp-stat-grid">
              <div class="tnp-stat-box" title="Chips won or lost this session."><div class="tnp-stat-label">Net Chips</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-net">n/a</div></div>
              <div class="tnp-stat-box" title="Hands recorded this session."><div class="tnp-stat-label">Hands</div><div class="tnp-stat-val" id="tnp-session-hands">0</div></div>
              <div class="tnp-stat-box" title="Hands won, win rate in brackets."><div class="tnp-stat-label">Won</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-won">n/a</div></div>
              <div class="tnp-stat-box" title="Share of hands you entered voluntarily. 20-30% is healthy."><div class="tnp-stat-label">VPIP</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-vpip">n/a</div></div>
              <div class="tnp-stat-box" title="Largest single-hand gain this session."><div class="tnp-stat-label">Biggest Win</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-win">n/a</div></div>
              <div class="tnp-stat-box" title="Largest single-hand loss this session."><div class="tnp-stat-label">Biggest Loss</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-loss">n/a</div></div>
              <div class="tnp-stat-box" title="Chips you brought back to the table after busting (rebuys). Amounts are not reliably readable; the count is."><div class="tnp-stat-label">Rebuys</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-rebuys">n/a</div></div>
              <div class="tnp-stat-box" title="Average chips per hour."><div class="tnp-stat-label">$/Hour</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-perhour">n/a</div></div>
              <div class="tnp-stat-box" title="Net chips per 100 hands expressed in big blinds of the current table."><div class="tnp-stat-label">BB/100</div><div class="tnp-stat-val tnp-session-unknown" id="tnp-session-bb100">n/a</div></div>
              <div class="tnp-stat-box" title="Time since the session started."><div class="tnp-stat-label">Duration</div><div class="tnp-stat-val" id="tnp-session-duration">0m</div></div>
            </div>
            <div id="tnp-tilt-warning" class="tnp-warn-box tnp-hidden"></div>
            <div id="tnp-session-recording-hint" class="tnp-caution-box tnp-hidden"></div>
            <hr class="tnp-divider">
            <div class="tnp-row">
              <div class="tnp-label" title="Torn ranks poker by Poker Score; the formula is not public, so these are estimates. Only won hands score.">Score est.</div>
              <div class="tnp-value tnp-accent" id="tnp-score-session" title="Estimated score this session / lifetime; showdown wins session / lifetime.">n/a</div>
            </div>
            <hr class="tnp-divider">
            <div class="tnp-row">
              <div class="tnp-label">Tracked Players</div>
              <div class="tnp-value" id="tnp-session-players">0</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label" title="Diagnostics of the action-log pipeline: how many completed hands, parsed actions and seat-matched actions the HUD saw. Unmatched names usually mean a seat's name did not read.">Log pipeline</div>
              <div class="tnp-value" id="tnp-pipeline-stats" style="font-size: var(--tnp-fz-2xs); max-width: 78%;">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label" title="Which table this session is on. Confirmed from the game list or the table art; unconfirmed reads say so.">Table</div>
              <div class="tnp-value" id="tnp-session-table">n/a</div>
            </div>
            <div class="tnp-info-box">"n/a" means <b>not observed yet</b>, not zero.</div>
            <hr class="tnp-divider">
            <div class="tnp-label" title="Every fold, check, call, bet or raise you clicked, graded against pot odds, equity, position and SPR at that exact moment.">Decision Debrief</div>
            <div id="tnp-decision-score" class="tnp-freshness"></div>
            <div id="tnp-decision-log"></div>
            <div id="tnp-session-chart" class="tnp-chart-box"></div>
            <div style="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap;">
              <button class="tnp-text-btn" id="tnp-reset-session">End &amp; Reset Session</button>
            </div>
          </div>

          <div class="tnp-panel" id="tnp-panel-bankroll">
            <div class="tnp-setting-row">
              <label class="tnp-label" title="Cash you are willing to risk at poker; only stake advice uses it." for="tnp-bankroll-total">Poker Bankroll $</label>
              <input type="text" class="tnp-input" id="tnp-bankroll-total" placeholder="e.g. 5000000">
            </div>
            <div class="tnp-setting-row">
              <label class="tnp-label" title="Session ends as a loss after this many buy-ins down. Two is common." for="tnp-bankroll-stoploss">Stop-Loss (buy-ins)</label>
              <input type="text" class="tnp-input" id="tnp-bankroll-stoploss" placeholder="2">
            </div>
            <div class="tnp-setting-row">
              <label class="tnp-label" title="Profit target; 0 turns the alert off." for="tnp-bankroll-goal">Session Goal $ (0=off)</label>
              <input type="text" class="tnp-input" id="tnp-bankroll-goal" placeholder="0">
            </div>
            <hr class="tnp-divider">
            <div id="tnp-bankroll-warning" class="tnp-warn-box tnp-hidden"></div>
            <div class="tnp-stat-grid">
              <div class="tnp-stat-box" title="Conservative stake: about 1/40 of bankroll."><div class="tnp-stat-label">Safe Buy-In</div><div class="tnp-stat-val tnp-success" id="tnp-bk-cons">-</div></div>
              <div class="tnp-stat-box" title="Recommended stake: about 1/25 of bankroll."><div class="tnp-stat-label">Standard</div><div class="tnp-stat-val" id="tnp-bk-std">-</div></div>
              <div class="tnp-stat-box" title="Upper bound: about 1/15. Expect bigger swings."><div class="tnp-stat-label">Aggressive</div><div class="tnp-stat-val tnp-danger" id="tnp-bk-aggr">-</div></div>
            </div>
            <div id="tnp-bankroll-status" style="font-size: var(--tnp-fz-xs); color: var(--tnp-muted);"></div>
            <div id="tnp-bankroll-risk" class="tnp-info-box"></div>
            <div id="tnp-table-card" class="tnp-info-box tnp-hidden"></div>
            <hr class="tnp-divider">
            <div class="tnp-label">Past Sessions</div>
            <div id="tnp-bankroll-history" style="display: flex; flex-direction: column; gap: 3px;"></div>
            <div id="tnp-bankroll-chart" class="tnp-chart-box"></div>
            <div class="tnp-info-box">
              Leaderboards reward volume of <i>won</i> hands at the biggest stakes you can
              afford. Buy-in tiers are guardrails, not exact math. Ratholing rule: leave a
              table after winning and you cannot return at the minimum buy-in for two hours.
            </div>
          </div>

          <div class="tnp-panel" id="tnp-panel-replay">
            <div class="tnp-replay-bar">
              <button type="button" class="tnp-text-btn" id="tnp-replay-prev-hand" title="Previous recorded hand">‹</button>
              <span class="tnp-value" id="tnp-replay-which">no recorded hands yet</span>
              <button type="button" class="tnp-text-btn" id="tnp-replay-next-hand" title="Next recorded hand">›</button>
            </div>
            <div class="tnp-cards-display" id="tnp-replay-cards"></div>
            <div class="tnp-timeline" id="tnp-replay-streets" aria-label="Replay streets"></div>
            <div class="tnp-row">
              <div class="tnp-label">At this point</div>
              <div class="tnp-value" id="tnp-replay-state" title="Pot, price, position and equity recorded at this decision point.">-</div>
            </div>
            <div class="tnp-row">
              <div class="tnp-label">Advice then</div>
              <div class="tnp-value" id="tnp-replay-advice" title="The recommendation the engine gave at this point.">-</div>
            </div>
            <div class="tnp-replay-cf" id="tnp-replay-cf"></div>
            <div class="tnp-replay-actions" id="tnp-replay-actions"></div>
            <div class="tnp-freshness">Counterfactual EVs compare fold, call and raise estimates at each recorded decision point; they are estimates, not the actual historical outcome.</div>
          </div>

          <div class="tnp-panel" id="tnp-panel-drill">
            <div class="tnp-freshness">Training sandbox: synthetic scenarios generated locally. Drills never mix into session records, hand histories or opponent profiles.</div>
            <button type="button" class="tnp-text-btn" id="tnp-drill-new">New scenario</button>
            <div class="tnp-cards-display" id="tnp-drill-cards"></div>
            <div class="tnp-value" id="tnp-drill-scenario">Press "New scenario" to generate a synthetic practice hand.</div>
            <div class="tnp-drill-answers" id="tnp-drill-answers">
              <button type="button" class="tnp-drill-btn" data-act="fold">Fold</button>
              <button type="button" class="tnp-drill-btn" data-act="check">Check</button>
              <button type="button" class="tnp-drill-btn" data-act="call">Call</button>
              <button type="button" class="tnp-drill-btn" data-act="raise">Raise</button>
            </div>
            <div class="tnp-value" id="tnp-drill-verdict"></div>
            <div class="tnp-freshness" id="tnp-drill-score">No drills answered yet.</div>
          </div>

          <div class="tnp-panel" id="tnp-panel-diagnostics">
            <div class="tnp-diag-table" id="tnp-diag-rows"></div>
            <div class="tnp-diag-integrity" id="tnp-diag-integrity"></div>

          </div>

          <div class="tnp-panel" id="tnp-panel-settings">
            <div class="tnp-setting-row">
              <label class="tnp-label" title="Master switch: hides the whole HUD, badges and banner. Data collection, profiles and sessions keep recording while it is off." for="tnp-setting-hudmaster">HUD</label>
              <input type="checkbox" class="tnp-checkbox" id="tnp-setting-hudmaster" ${settings.hudEnabled ? 'checked' : ''}>
            </div>
            <div class="tnp-label">Display</div>
            <div class="tnp-mode-btns" id="tnp-display-btns"></div>
            <div class="tnp-label" title="Adjusts the open, defend, 3-bet and value-bet thresholds. Every explanation still shows the underlying math.">Strategy</div>
            <div class="tnp-quality-btns" id="tnp-strategy-btns"></div>
            <div class="tnp-setting-row">
              <label class="tnp-label" title="Master switch for every profile-driven adjustment: opponent range narrowing, table-wide call/value adjustments, river overfold reads, and opponent-aware preflop. Off = pure math, no profiling. Tracking itself always runs." for="tnp-setting-profile">Opponent tracking</label>
              <input type="checkbox" class="tnp-checkbox" id="tnp-setting-profile" ${settings.profileAdjusted ? 'checked' : ''}>
            </div>
            <div class="tnp-setting-row">
              <label class="tnp-label" title="Shows the suggested play above the table on your turn." for="tnp-setting-banner">Advice banner</label>
              <input type="checkbox" class="tnp-checkbox" id="tnp-setting-banner" ${settings.actionBanner ? 'checked' : ''}>
            </div>
            <div class="tnp-info-box">Equity always runs a fixed 1,000,000-iteration Monte Carlo in pooled Web Workers with a reproducible seed — no setting needed. Provisional numbers appear while it runs.</div>
            <hr class="tnp-divider">
            <button type="button" class="tnp-details-toggle" id="tnp-advanced-toggle">Advanced</button>
            <div id="tnp-advanced-section" class="tnp-hidden">
              <div class="tnp-label">Appearance</div>
              <div class="tnp-setting-row">
                <span class="tnp-label">Font Scale</span>
                <div class="tnp-quality-btns" id="tnp-fontscale-btns"></div>
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" for="tnp-setting-hc">High Contrast</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-hc" ${settings.highContrast ? 'checked' : ''}>
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" for="tnp-setting-opaque">Reduced Transparency</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-opaque" ${settings.reducedTransparency ? 'checked' : ''}>
              </div>
              <div class="tnp-setting-row">
                <span class="tnp-label">Panel Position</span>
                <button class="tnp-text-btn" id="tnp-reset-position">Reset Position</button>
              </div>
              <hr class="tnp-divider">
              <div class="tnp-setting-row">
                <label class="tnp-label" for="tnp-setting-highlight">Card Highlighting</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-highlight" ${settings.cardHighlight ? 'checked' : ''}>
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" title="Off by default: a hidden table must never generate attention." for="tnp-setting-flash">Turn Flash Alert</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-flash" ${settings.turnFlash ? 'checked' : ''}>
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" title="For tables where the game disables preflop raises: advice then says call or fold only, with wider defends." for="tnp-setting-nopf">No-Pre-flop table</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-nopf" ${settings.noPreFlopMode ? 'checked' : ''}>
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" title="Type badges on seat plates at the table. Turning them off never stops data collection." for="tnp-setting-hud">Seat Profile Badges</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-hud" ${settings.showHUD ? 'checked' : ''}>
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" title="Short behavior notes once enough hands are seen." for="tnp-setting-exploit">Tendency Notes</label>
                <input type="checkbox" class="tnp-checkbox" id="tnp-setting-exploit" ${settings.showExploit ? 'checked' : ''}>
              </div>
              <hr class="tnp-divider">
              <div class="tnp-label">Local Data Retention</div>
              <div class="tnp-setting-row">
                <label class="tnp-label" for="tnp-retention-days">Delete profiles unseen for (days)</label>
                <input type="text" class="tnp-input" id="tnp-retention-days" value="${settings.profileRetentionDays}">
              </div>
              <div class="tnp-setting-row">
                <label class="tnp-label" for="tnp-retention-max">Max saved profiles</label>
                <input type="text" class="tnp-input" id="tnp-retention-max" value="${settings.maxProfiles}">
              </div>
              <div class="tnp-info-box">Structured data (profiles, notes, self stats, sessions) lives in IndexedDB with bounded retention; localStorage only keeps settings and acts as fallback. Least-recently-seen profiles evict first.</div>
              <hr class="tnp-divider">
              <div class="tnp-label">Data Inventory (this device only)</div>
              <div id="tnp-data-inventory" style="display: flex; flex-direction: column;"></div>
              <div id="tnp-storage-dashboard" style="font-size: var(--tnp-fz-2xs); color: var(--tnp-muted); margin: 6px 0;"></div>
              <div style="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap;">
                <button class="tnp-text-btn" id="tnp-clear-profiles">Clear Profiles + Notes</button>
                <button class="tnp-text-btn" id="tnp-clear-financial">Clear Financial Data</button>
                <button class="tnp-text-btn" id="tnp-clear-all-data">Clear All Local HUD Data</button>
              </div>
              <div style="font-size: var(--tnp-fz-2xs); color: var(--tnp-muted); text-align: center; line-height: 1.5;">
                Everything stays on this device. Nothing is sent anywhere.
              </div>
              <hr class="tnp-divider">
              <div class="tnp-setting-row" style="display:block;">
                <span class="tnp-label" title="A local JSON snapshot of parser health, selector stats, table identity, game state and storage: exactly what a bug report needs, and nothing leaves the device unless you send it." >Diagnostics</span>
                <div style="display:flex; gap:6px; margin-top:4px; flex-wrap:wrap;">
                  <button class="tnp-text-btn" id="tnp-debug-export">Export debug snapshot</button>
                </div>
              </div>
              <div class="tnp-setting-row" style="display:block;">
                <span class="tnp-label" title="Brings back profiles, notes, self stats, bankroll rows and settings from a backup file.">Full local backup</span>
                <div style="display:flex; gap:6px; margin-top:4px; flex-wrap:wrap;">
                  <button class="tnp-text-btn" id="tnp-backup-export">Save backup file</button>
                  <button class="tnp-text-btn" id="tnp-backup-import">Restore from file</button>
                  <input type="file" id="tnp-backup-file" accept="application/json,.json" style="display:none;">
                </div>
                <div style="font-size:var(--tnp-fz-2xs); color:var(--tnp-muted); margin-top:2px;" id="tnp-backup-note">Everything stays on this device: export writes a JSON file you choose where to keep.</div>
              </div>
            </div>
          </div>

        </div>
      </div>
`;
    document.body.appendChild(uiElement);
    updateMobileMode();
            if (activeTab !== 'analysis') switchTab(activeTab);

    const clampPanelPos = (x, y) => {
      const w = window.innerWidth || 1024, h = window.innerHeight || 768;
      const panelW = (uiElement && uiElement.offsetWidth) || 348;
      return {
        x: Math.max(-(panelW - 90), Math.min(w - 90, Math.round(x))),
        y: Math.max(0, Math.min(h - 40, Math.round(y)))
      };
    };

    if (settings.panelPos && typeof settings.panelPos.x === 'number') {
      const clamped = clampPanelPos(settings.panelPos.x, settings.panelPos.y);
      uiElement.style.right = 'auto';
      uiElement.style.bottom = 'auto';
      uiElement.style.left = `${clamped.x}px`;
      uiElement.style.top = `${clamped.y}px`;
      dragPos = clamped;
    }

    const header = uiElement.querySelector('#tnp-header');
    let isDragging = false, startX, startY;
    const applyPanelPos = (clamped) => {
      dragPos = clamped;
      uiElement.style.right = 'auto';
      uiElement.style.bottom = 'auto';
      uiElement.style.left = `${clamped.x}px`;
      uiElement.style.top = `${clamped.y}px`;
    };
    const onDragStart = (clientX, clientY) => {
      isDragging = true;
      startX = clientX - uiElement.offsetLeft;
      startY = clientY - uiElement.offsetTop;
    };
    const onDragMove = (clientX, clientY) => {
      if (!isDragging) return;
      applyPanelPos(clampPanelPos(clientX - startX, clientY - startY));
    };
    const onDragEnd = () => {
      if (isDragging) {
        const clamped = clampPanelPos(dragPos.x, dragPos.y);
        settings.panelPos = clamped;
        saveSettings();
      }
      isDragging = false;
    };
    const isHeaderControl = (target) => !!(target?.closest?.('#tnp-toggle, #tnp-status-chip, #tnp-health-badge, button'));
    header.setAttribute('tabindex', '0');
    header.setAttribute('aria-label', 'Poker Hold\'em panel header: drag with the mouse, or use the arrow keys while focused to move the panel.');
    header.addEventListener('pointerdown', (e) => {
      if (e.button !== 0 || isHeaderControl(e.target)) return;
      onDragStart(e.clientX, e.clientY);
      if (header.setPointerCapture) {
        try { header.setPointerCapture(e.pointerId); } catch {  }
      }
    });
    header.addEventListener('pointermove', (e) => {
      if (!isDragging) return;
      if (header.hasPointerCapture && header.hasPointerCapture(e.pointerId)) {
        onDragMove(e.clientX, e.clientY);
        e.preventDefault();
      }
    });
    header.addEventListener('lostpointercapture', onDragEnd);
    header.addEventListener('pointercancel', onDragEnd);
    header.addEventListener('keydown', (e) => {
      if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(e.key)) return;
      e.preventDefault();
      const step = e.shiftKey ? 60 : 15;
      let { x, y } = clampPanelPos(dragPos.x, dragPos.y);
      if (e.key === 'ArrowLeft') x -= step;
      else if (e.key === 'ArrowRight') x += step;
      else if (e.key === 'ArrowUp') y -= step;
      else if (e.key === 'ArrowDown') y += step;
      else if (e.key === 'Home') { x = 0; y = 0; }
      else { x = (window.innerWidth || 1024) - 90; y = (window.innerHeight || 768) - 40; }
      applyPanelPos(clampPanelPos(x, y));
      settings.panelPos = dragPos;
      saveSettings();
    });
    const reClampOnResize = () => {
      if (settings.panelPos && typeof settings.panelPos.x === 'number') {
        applyPanelPos(clampPanelPos(settings.panelPos.x, settings.panelPos.y));
      }
    };
    window.addEventListener('resize', reClampOnResize, { passive: true });
    uiCleanupFns.push(() => {
      window.removeEventListener('resize', reClampOnResize);
    });

    const detailsToggle = document.getElementById('tnp-details-toggle');
    const detailRows = document.getElementById('tnp-detail-rows');
    const applyDetailsCollapsed = () => {
      if (!detailsToggle || !detailRows) return;
      detailRows.style.display = settings.detailsCollapsed ? 'none' : 'flex';
      detailsToggle.classList.toggle('tnp-toggle-open', !settings.detailsCollapsed);
    };
    if (detailsToggle) {
      detailsToggle.addEventListener('click', () => {
        settings.detailsCollapsed = !settings.detailsCollapsed;
        saveSettings();
        applyDetailsCollapsed();
      });
      applyDetailsCollapsed();
    }

    const wireBankrollInput = (id, key, parse) => {
      const el = document.getElementById(id);
      if (!el) return;
      el.value = bankroll[key] ? String(bankroll[key]) : '';
      el.addEventListener('change', () => {
        const v = parse(el.value);
        bankroll[key] = Number.isFinite(v) && v >= 0 ? v : 0;
        saveBankroll();
        renderBankrollPanel();
      });
    };
    wireBankrollInput('tnp-bankroll-total', 'total', v => parseTornNumber(v));
    wireBankrollInput('tnp-bankroll-stoploss', 'stopLossBuyIns', v => parseNonNegativeDecimal(v, 0));
    wireBankrollInput('tnp-bankroll-goal', 'sessionGoal', v => parseTornNumber(v));

    const toggleBtn = document.getElementById('tnp-toggle');
    const applyMinimizedState = () => {
      if (!uiElement || !toggleBtn) return;
      const bodyInDom = document.getElementById('tnp-body');
      if (!isMinimized && !bodyInDom && minimizedBodyEl && minimizedBodyPlaceholder?.parentNode === uiElement) {
        minimizedBodyPlaceholder.parentNode.insertBefore(minimizedBodyEl, minimizedBodyPlaceholder);
        minimizedBodyPlaceholder.remove();
        minimizedBodyPlaceholder = null;
      }

      uiElement.classList.toggle('tnp-minimized', isMinimized);

      toggleBtn.setAttribute('aria-label', isMinimized ? 'Restore dossier' : 'Minimize dossier');
      toggleBtn.setAttribute('aria-expanded', isMinimized ? 'false' : 'true');

      const bodyEl = document.getElementById('tnp-body') || minimizedBodyEl;
      const minimizedStyleProps = [
        'position', 'top', 'right', 'bottom', 'left', 'width', 'max-width',
        'height', 'min-width', 'min-height', 'max-height', 'display',
        'flex', 'overflow', 'align-self'
      ];
      if (isMinimized) {
        if (!minimizedStyleBackup) {
          minimizedStyleBackup = Object.fromEntries(minimizedStyleProps.map(prop => [
            prop, uiElement.style.getPropertyValue(prop), uiElement.style.getPropertyPriority(prop)
          ]));
        }
        if (bodyEl && bodyEl.parentNode === uiElement) {
          minimizedBodyEl = bodyEl;
          minimizedBodyPlaceholder = document.createComment('tnp-body-placeholder');
          uiElement.insertBefore(minimizedBodyPlaceholder, bodyEl);
          bodyEl.hidden = true;
          bodyEl.style.removeProperty('display');
          bodyEl.remove();
        }

        const headerEl = document.getElementById('tnp-header');
        const headerHeight = Math.max(1, Math.ceil(headerEl?.getBoundingClientRect().height || 78));
        uiElement.style.setProperty('position', 'fixed', 'important');
        uiElement.style.setProperty('top', 'auto', 'important');
        uiElement.style.setProperty('left', 'auto', 'important');
        uiElement.style.setProperty('right', '8px', 'important');
        uiElement.style.setProperty('bottom', 'calc(8px + env(safe-area-inset-bottom, 0px))', 'important');
        uiElement.style.setProperty('display', 'block', 'important');
        uiElement.style.setProperty('width', 'min(420px, calc(100vw - 16px))', 'important');
        uiElement.style.setProperty('height', `${headerHeight}px`, 'important');
        uiElement.style.setProperty('min-width', '0', 'important');
        uiElement.style.setProperty('min-height', `${headerHeight}px`, 'important');
        uiElement.style.setProperty('max-height', `${headerHeight}px`, 'important');
        uiElement.style.setProperty('flex', 'none', 'important');
        uiElement.style.setProperty('align-self', 'auto', 'important');
        uiElement.style.setProperty('overflow', 'hidden', 'important');
      } else {
        if (bodyEl && bodyEl.parentNode !== uiElement && minimizedBodyPlaceholder?.parentNode === uiElement) {
          minimizedBodyPlaceholder.parentNode.insertBefore(bodyEl, minimizedBodyPlaceholder);
          minimizedBodyPlaceholder.remove();
          minimizedBodyPlaceholder = null;
        }
        if (bodyEl) {
          bodyEl.hidden = false;
          bodyEl.style.removeProperty('display');
        }
        if (minimizedStyleBackup) {
          for (const prop of minimizedStyleProps) {
            const [value, priority] = minimizedStyleBackup[prop];
            if (value) uiElement.style.setProperty(prop, value, priority);
            else uiElement.style.removeProperty(prop);
          }
          minimizedStyleBackup = null;
        }
      }
    };
    const toggleMinimize = (e) => {
      if (e) { e.preventDefault(); e.stopPropagation(); }
      isMinimized = !isMinimized;
      applyMinimizedState();
    };
    applyMinimizedState();
    toggleBtn.addEventListener('click', (e) => {
      if (suppressNextToggleClick) {
        suppressNextToggleClick = false;
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      toggleMinimize(e);
    });

    toggleBtn.addEventListener('touchend', (e) => {
      e.preventDefault();
      suppressNextToggleClick = true;
      toggleMinimize(e);
      setTimeout(() => { suppressNextToggleClick = false; }, 500);
    }, { passive: false });
    toggleBtn.addEventListener('touchstart', (e) => {
      e.stopPropagation();
    }, { passive: true });
    toggleBtn.addEventListener('keydown', (e) => {
      if (e.key !== ' ' && e.key !== 'Enter') return;
      e.preventDefault();
      toggleMinimize();
    });

    const tabButtons = Array.from(uiElement.querySelectorAll('.tnp-tab'));
    tabButtons.forEach(tab => {
      tab.addEventListener('click', () => {
        switchTab(tab.dataset.tab);
        renderNow();
      });
      tab.addEventListener('keydown', (e) => {

        const idx = tabButtons.indexOf(tab);
        let next = null;
        if (e.key === 'ArrowRight') next = tabButtons[(idx + 1) % tabButtons.length];
        else if (e.key === 'ArrowLeft') next = tabButtons[(idx - 1 + tabButtons.length) % tabButtons.length];
        else if (e.key === 'Home') next = tabButtons[0];
        else if (e.key === 'End') next = tabButtons[tabButtons.length - 1];
        if (next) {
          e.preventDefault();
          switchTab(next.dataset.tab);
          renderNow();
          next.focus();
        }
      });
    });

    const wireCheckbox = (id, key, after) => {
      const el = document.getElementById(id);
      if (!el) return;
      el.addEventListener('change', () => {
        settings[key] = el.checked;
        saveSettings();
        if (after) after();
      });
    };
    wireCheckbox('tnp-setting-highlight', 'cardHighlight', () => {
      if (!settings.cardHighlight) clearCardHighlights();
    });
    wireCheckbox('tnp-setting-flash', 'turnFlash');
    wireCheckbox('tnp-setting-profile', 'profileAdjusted', () => {
      gameState.lastCardHash = '';
      gameState.lastStateHash = '';
      mcJobId++;
      setTimeout(computeState, 0);
    });
    wireCheckbox('tnp-setting-nopf', 'noPreFlopMode');
    wireCheckbox('tnp-setting-hud', 'showHUD');
    const hudMaster = document.getElementById('tnp-setting-hudmaster');
    if (hudMaster) {
      hudMaster.addEventListener('change', () => {
        settings.hudEnabled = hudMaster.checked;
        saveSettings();
        applyHudEnabled();
      });
    }
    const strategyBtns = document.getElementById('tnp-strategy-btns');
    if (strategyBtns) {
      [['tight', 'Tight'], ['balanced', 'Balanced'], ['aggressive', 'Aggressive']].forEach(([value, label]) => {
        const b = document.createElement('button');
        b.type = 'button';
        b.className = `tnp-quality-btn ${settings.strategyProfile === value ? 'active' : ''}`;
        b.textContent = label;
        b.title = STRATEGY_PROFILES[value].note;
        b.addEventListener('click', () => {
          settings.strategyProfile = value;
          saveSettings();
          strategyBtns.querySelectorAll('.tnp-quality-btn').forEach((x, i) =>
            x.classList.toggle('active', ['tight', 'balanced', 'aggressive'][i] === value));
          gameState.lastCardHash = '';
          gameState.lastStateHash = '';
          mcJobId++;
          setTimeout(() => computeState(), 0);
        });
        strategyBtns.appendChild(b);
      });
    }
    const advancedToggle = document.getElementById('tnp-advanced-toggle');
    const advancedSection = document.getElementById('tnp-advanced-section');
    if (advancedToggle && advancedSection) {
      advancedToggle.addEventListener('click', () => {
        const open = !advancedSection.classList.toggle('tnp-hidden');
        advancedToggle.classList.toggle('tnp-toggle-open', open);
      });
    }
    const debugExportBtn = document.getElementById('tnp-debug-export');
    if (debugExportBtn) debugExportBtn.addEventListener('click', exportDebugState);
    wireCheckbox('tnp-setting-exploit', 'showExploit');
    wireCheckbox('tnp-setting-banner', 'actionBanner');

    const notesInput = document.getElementById('tnp-notes-textarea');
    if (notesInput) {
      notesInput.addEventListener('blur', () => {
        const pId = notesInput.dataset.playerId;
        if (pId) {
          let value = notesInput.value ?? '';
          if (value.length > 4000) {
            value = value.slice(0, 4000);
            notesInput.value = value;
            tnpToast('warn', 'Note trimmed to 4,000 characters (the stored-notes limit).');
          }
          delete playerNotes[pId];
          playerNotes[pId] = value;
          saveNotes();
        }
      });
    }

    const oppListEl = document.getElementById('tnp-opponents-list');
    if (oppListEl) {
      oppListEl.addEventListener('click', (e) => {
        const row = e.target.closest?.('.tnp-player-row');
        if (row && row.dataset.playerId) showPlayerProfile(row.dataset.playerId);
      });
    }

    const backupExportBtn = document.getElementById('tnp-backup-export');
    if (backupExportBtn) {
      backupExportBtn.addEventListener('click', () => {
        try {
          const payload = {
            app: 'poker-holdem', version: SCRIPT_VERSION, exportedAt: new Date().toISOString(),
            profiles, playerNotes, heroStats, lifetime, bankroll, settings
          };
          const blob = new Blob([JSON.stringify(payload, null, 1)], { type: 'application/json' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `poker-holdem-backup-${new Date().toISOString().slice(0, 10)}.json`;
          document.body.appendChild(a);
          a.click();
          a.remove();
          setTimeout(() => URL.revokeObjectURL(url), 4000);
          const note = document.getElementById('tnp-backup-note');
          if (note) { note.textContent = `Backup saved: ${Object.keys(profiles).length} profiles · ${heroStats.hands} self hands.`; }
        } catch (err) {
          window.alert(`Backup failed: ${err && err.message ? err.message : err}`);
        }
      });
    }
    const backupImportBtn = document.getElementById('tnp-backup-import');
    const backupFileInput = document.getElementById('tnp-backup-file');
    if (backupImportBtn && backupFileInput) {
      backupImportBtn.addEventListener('click', () => backupFileInput.click());
      backupFileInput.addEventListener('change', () => {
        const file = backupFileInput.files && backupFileInput.files[0];
        backupFileInput.value = '';
        if (!file) return;
        const reader = new FileReader();
        reader.onload = () => {
          try {
            const restored = applyBackupData({ settings }, String(reader.result ?? ''));
            const ok = window.confirm(
              `Restore backup?\n` +
              `${Object.keys(restored.profiles).length} opponent profiles (you have ${Object.keys(profiles).length})\n` +
              `${Object.keys(restored.playerNotes).length} notes (you have ${Object.keys(playerNotes).length})\n` +
              `${restored.heroStats.hands} self hands and ${restored.heroStats.ring.length} showdowns (you have ${heroStats?.hands ?? 0})\n` +
              `${restored.bankroll.history?.length ?? 0} bankroll sessions (you have ${bankroll.history?.length ?? 0})\n\n` +
              `This replaces the current local data on this device.`
            );
            if (!ok) return;
            profiles = restored.profiles;
            playerNotes = restored.playerNotes;
            heroStats = restored.heroStats;
            lifetime = restored.lifetime;
            bankroll = restored.bankroll;
            settings = restored.settings;
            saveProfiles(); saveNotes(); saveHeroStats(); saveLifetime(); saveBankroll(); saveSettings();
            renderUI();
            const note = document.getElementById('tnp-backup-note');
            if (note) { note.textContent = `Restored ${Object.keys(profiles).length} profiles · ${heroStats.hands} self hands from backup.`; }
          } catch (err) {
            window.alert(`Restore failed: ${err && err.message ? err.message : 'unreadable file'}`);
          }
        };
        reader.onerror = () => window.alert('Restore failed: could not read the file.');
        reader.readAsText(file);
      });
    }

    const resetBtn = document.getElementById('tnp-reset-session');
    if (resetBtn) {
      resetBtn.addEventListener('click', () => {
        if (session.handsPlayed > 0 && !window.confirm('End this session, save it to history, and reset the live counters?')) return;
        if (session.handsPlayed > 0) {
          bankroll.history.push({
            date: new Date().toISOString().slice(0, 16).replace('T', ' '),
            net: session.netChips,
            hands: session.handsPlayed,
            won: session.handsWon,
            mins: Math.round((Date.now() - session.startTime) / 60000),
            table: currentTableName() || null
          });
          if (bankroll.history.length > 50) bankroll.history = bankroll.history.slice(-50);
          const normalizedBankroll = parseTornNumber(bankroll.total);
          const sessionNet = Number(session.netChips);
          if (normalizedBankroll > 0 && Number.isFinite(sessionNet)) {
            bankroll.total = Math.max(0, normalizedBankroll + sessionNet);
          }
          lifetime.sessions++;
          saveLifetime();
          saveBankroll();
          const totalInput = document.getElementById('tnp-bankroll-total');
          if (totalInput && bankroll.total > 0) totalInput.value = String(bankroll.total);
        }
        session = freshSession();
        resetProfileSessionCounters();
        recordedSessionHandKeys.clear();
        seenAwardLines.clear();
        lastHoleKey = '';
        handEvidence = { key: '', messages: [], heroName: '', heroVoluntary: false, heroWon: false, heroShowed: false };
        queueSave('bankroll');

        saveSession();
        flushAllSaves('end-session');
        renderUI();
        renderDataLifecycleCards();
      });
    }

    const clearBtn = document.getElementById('tnp-clear-profiles');
    if (clearBtn) {
      clearBtn.addEventListener('click', () => {
        if (!window.confirm('Clear every locally stored opponent profile and note? This cannot be undone.')) return;
        profiles = {};
        playerNotes = {};
        queueSave('profiles');
        queueSave('notes');
        flushAllSaves('clear-profiles');
        renderUI();
      });
    }

    const displayBtns = document.getElementById('tnp-display-btns');
    if (displayBtns) {
      [['full', 'Full Dossier'], ['compact', 'Compact'], ['minimal', 'Minimal']].forEach(([value, label]) => {
        const b = document.createElement('button');
        b.type = 'button';
        b.className = `tnp-quality-btn ${settings.displayMode === value ? 'active' : ''}`;
        b.textContent = label;
        b.addEventListener('click', () => {
          settings.displayMode = value;
          saveSettings();
          applyDisplayMode();
          displayBtns.querySelectorAll('.tnp-quality-btn').forEach((x, i) =>
            x.classList.toggle('active', ['full', 'compact', 'minimal'][i] === value));
          renderNow();
        });
        displayBtns.appendChild(b);
      });
    }

    ['tnp-compact-restore', 'tnp-minimal-restore'].forEach((id) => {
      const btn = document.getElementById(id);
      if (!btn) return;
      btn.addEventListener('click', () => {
        settings.displayMode = 'full';
        saveSettings();
        applyDisplayMode();
        const seg = document.getElementById('tnp-display-btns');
        if (seg) seg.querySelectorAll('.tnp-quality-btn').forEach((x, i) =>
          x.classList.toggle('active', i === 0));
        renderNow();
      });
    });
    applyDisplayMode();

    const fontScaleBtns = document.getElementById('tnp-fontscale-btns');
    if (fontScaleBtns) {
      [[0.9, 'S'], [1.0, 'M'], [1.1, 'L']].forEach(([value, label]) => {
        const b = document.createElement('button');
        b.type = 'button';
        b.className = `tnp-quality-btn ${settings.fontScale === value ? 'active' : ''}`;
        b.textContent = label;
        b.addEventListener('click', () => {
          settings.fontScale = value;
          saveSettings();
          applyVisualSettings();
          fontScaleBtns.querySelectorAll('.tnp-quality-btn').forEach((x, i) =>
            x.classList.toggle('active', [0.9, 1.0, 1.1][i] === value));
        });
        fontScaleBtns.appendChild(b);
      });
    }
    wireCheckbox('tnp-setting-hc', 'highContrast', applyVisualSettings);
    wireCheckbox('tnp-setting-opaque', 'reducedTransparency', applyVisualSettings);
    applyVisualSettings();

    const resetPosBtn = document.getElementById('tnp-reset-position');
    if (resetPosBtn) {
      resetPosBtn.addEventListener('click', () => {
        settings.panelPos = null;
        saveSettings();
        dragPos = { x: 0, y: 0 };
        if (uiElement) {
          uiElement.style.left = '';
          uiElement.style.top = '';
          uiElement.style.right = '';
          uiElement.style.bottom = '';
        }
      });
    }

    const retentionDays = document.getElementById('tnp-retention-days');
    if (retentionDays) {
      retentionDays.addEventListener('change', () => {
        const v = Math.max(7, Math.min(365, Math.round(parseNonNegativeDecimal(retentionDays.value, 90)) || 90));
        settings.profileRetentionDays = v;
        retentionDays.value = String(v);
        saveSettings();
        pruneProfiles();
      });
    }
    const retentionMax = document.getElementById('tnp-retention-max');
    if (retentionMax) {
      retentionMax.addEventListener('change', () => {
        const v = Math.max(50, Math.min(2000, Math.round(parseNonNegativeDecimal(retentionMax.value, 800)) || 800));
        settings.maxProfiles = v;
        retentionMax.value = String(v);
        saveSettings();
        pruneProfiles();
      });
    }

    const parserBannerDismiss = document.getElementById('tnp-parser-banner-dismiss');
    if (parserBannerDismiss) {
      parserBannerDismiss.addEventListener('click', () => {
        document.getElementById('tnp-parser-banner')?.classList.remove('tnp-banner-active');
      });
    }

    const whyToggle = document.getElementById('tnp-why-toggle');
    const whyPanel = document.getElementById('tnp-why-panel');
    if (whyToggle && whyPanel) {
      whyToggle.addEventListener('click', () => {
        const open = whyPanel.classList.toggle('tnp-banner-active');
        whyToggle.classList.toggle('tnp-toggle-open', open);
      });
    }

    const replayPrevBtn = document.getElementById('tnp-replay-prev-hand');
    if (replayPrevBtn) replayPrevBtn.addEventListener('click', () => replayMoveHand(-1));
    const replayNextBtn = document.getElementById('tnp-replay-next-hand');
    if (replayNextBtn) replayNextBtn.addEventListener('click', () => replayMoveHand(1));
    const replayStreetsEl = document.getElementById('tnp-replay-streets');
    if (replayStreetsEl) {
      replayStreetsEl.addEventListener('click', (e) => {
        const btn = e.target && e.target.closest ? e.target.closest('[data-replay-step]') : null;
        if (btn) replayStepTo(Number(btn.dataset.replayStep) || 0);
      });
    }

    const drillNewBtn = document.getElementById('tnp-drill-new');
    if (drillNewBtn) drillNewBtn.addEventListener('click', () => { drillNew(); });
    const drillAnswersEl = document.getElementById('tnp-drill-answers');
    if (drillAnswersEl) {
      drillAnswersEl.addEventListener('click', (e) => {
        const btn = e.target && e.target.closest ? e.target.closest('[data-act]') : null;
        if (!btn) return;
        if (!drillState.active || drillState.answered) return;
        void drillAnswer(btn.dataset.act);
      });
    }

    const guideToggle = document.getElementById('tnp-stat-guide-toggle');
    const guidePanel = document.getElementById('tnp-stat-guide');
    if (guideToggle && guidePanel) {
      guideToggle.addEventListener('click', () => {
        const open = !guidePanel.classList.toggle('tnp-hidden');
        guideToggle.classList.toggle('tnp-toggle-open', open);
      });
    }

    const clearFinancialBtn = document.getElementById('tnp-clear-financial');
    if (clearFinancialBtn) {
      clearFinancialBtn.addEventListener('click', () => {
        if (!window.confirm('Clear bankroll total, stop-loss settings, and all saved session history? This cannot be undone.')) return;
        bankroll = { total: 0, stopLossBuyIns: 2, sessionGoal: 0, history: [] };
        bankroll = normalizeBankrollState(bankroll);
        queueSave('bankroll');
        flushAllSaves('clear-financial');
        const totalInput = document.getElementById('tnp-bankroll-total');
        if (totalInput) totalInput.value = '';
        renderBankrollPanel();
        renderDataLifecycleCards();
      });
    }

    const clearAllBtn = document.getElementById('tnp-clear-all-data');
    if (clearAllBtn) {
      clearAllBtn.addEventListener('click', async () => {
        const msg = 'This erases EVERYTHING the HUD stored on this device:\n\n'
          + '• Settings and panel layout\n'
          + `• ${Object.keys(profiles).length} local opponent profile(s)\n`
          + `• ${Object.keys(playerNotes).length} note(s)\n`
          + '• Session/lifetime statistics\n'
          + '• Your self profile and showdown ledger (You tab)\n'
          + '• Bankroll total and history\n\n'
          + 'Nothing is ever sent anywhere; it is deleted from this device only. Continue?';
        if (!window.confirm(msg)) return;
        await storage.removeAll();
        void TNP6.clearIdbData();
        healStore = { features: {} };
        profiles = {};
        playerNotes = {};
        lifetime = normalizeLifetime({});
        bankroll = normalizeBankrollState({ total: 0, stopLossBuyIns: 2, sessionGoal: 0, history: [] });
        heroStats = freshHeroStats();
        session = freshSession();
        resetProfileSessionCounters();
        recordedSessionHandKeys.clear();
        seenAwardLines.clear();
        settings = { ...DEFAULT_SETTINGS };
        queueSave('settings');
        queueSave('profiles');
        queueSave('notes');
        queueSave('lifetime');
        queueSave('bankroll');
        queueSave('hero');
        saveSession();
        flushAllSaves('clear-all');
        applyDisplayMode();
        applyVisualSettings();
        renderUI();
        renderDataLifecycleCards();
      });
    }


  };

  const renderDataLifecycleCards = () => {
    const inv = document.getElementById('tnp-data-inventory');
    if (inv) {
      const rows = [
        ['Settings & panel layout', 'Until cleared', `${Object.keys(settings).length} keys`],
        ['Opponent profiles', `TTL ${settings.profileRetentionDays}d · max ${settings.maxProfiles} · ≤ ${(STORAGE_BUDGETS.profiles / 1024) | 0} KB`, `${Object.keys(profiles).length} saved`],
        ['Player notes', `Until cleared · ≤ ${(STORAGE_BUDGETS.notes / 1024) | 0} KB · max ${NOTES_MAX_ROWS} rows`, `${Object.keys(playerNotes).length} saved`],
        ['Session metrics', 'In memory', `${session.handsPlayed} hands this session`],
        ['Self profile (You tab)', `Until cleared · ≤ ${(STORAGE_BUDGETS.hero / 1024) | 0} KB`, `${heroStats.hands} hands · ${heroStats.ring.length} showdowns`],
        ['Lifetime aggregates', 'Until cleared', `${Math.round(lifetime.handsPlayed)} hands total`],
        ['Bankroll history', `Last ${bankroll.history?.length ?? 0} of max 50 sessions · ≤ ${(STORAGE_BUDGETS.bankroll / 1024) | 0} KB`, `${bankroll.history?.length ?? 0} saved`],
        ['Table context', 'This tab only (sessionStorage), 8 h cap', currentTableName() || 'none yet'],
        ['Backup restore', 'Only after your tap', 'from a backup file you pick'],
        ['Network / API data', 'None, by design', 'no requests, ever']
      ];
      setHTML(inv, rows.map(([a, b, c]) =>
        `<div class="tnp-inventory-row"><b>${escapeHtml(a)}</b><span>${escapeHtml(b)} · ${escapeHtml(c)}</span></div>`).join(''));
    }
    const dash = document.getElementById('tnp-storage-dashboard');
    if (dash) {

      refreshStorageBytes();
      const report = storageBudgetReport(storageState.bytes);
      const kb = (n) => (n / 1024).toFixed(1);
      const stateWord = storageState.degraded.size
        ? 'memory-only: writes failing, clear old HUD data'
        : (report.totalOver ? 'over budget: trimming on next save' : 'within budget');
      const perCat = report.rows.map((r) => `${r.category} ${kb(r.used)}/${kb(r.budget)}KB${r.over ? ' ⚠' : ''}`).join(' · ');
      setHTML(dash, `<div>Backend: ${escapeHtml(storage.backendName())} · ${kb(report.total)} KB of ${kb(report.totalBudget)} KB budget · ${escapeHtml(stateWord)}</div>`
        + `<div style="margin-top:2px;">${escapeHtml(perCat)}</div>`
        + `<div style="margin-top:2px;">Shares this origin's localStorage pool with every other script (${(originPoolBytes() / 1024).toFixed(0)} KB in use overall); the governor keeps this HUD under its own budgets and shrinks itself if the pool runs hot.</div>`);
    }
  };

  const renderCard = (cardString) => {
    if (!cardString) return `<div class="tnp-card-mini tnp-empty-card"></div>`;
    const suit = cardString[1];
    const colorClass = (suit === '♥' || suit === '♦') ? 'tnp-card-red' : 'tnp-card-black';
    return `<div class="tnp-card-mini ${colorClass}">${cardString[0]}${suit}</div>`;
  };

    let _boardRootCache = { at: 0, root: null };
  const getBoardCardsRoot = () => {
    try {
      if (_boardRootCache.root && document.contains(_boardRootCache.root)) return _boardRootCache.root;
      const root = document.querySelector('[data-board-cards]')
        || document.querySelector('[class*="communityCards"]');
      _boardRootCache = { at: Date.now(), root };
      return root;
    } catch { return null; }
  };

        const getBoardCardElements = () => {
    try {
      const root = getBoardCardsRoot();
      if (!root) return [];
      let els = Array.from(root.querySelectorAll('div[role="img"][aria-label]'));
      if (!els.length) {
        els = Array.from(root.querySelectorAll('[class*="front___"] > div[role="img"], [class*="card"]'))
          .filter(el => el.getAttribute('aria-hidden') !== 'true');
      }
      return els.filter(el =>
        !el.closest('#tnp-dossier')
        && el.getAttribute('aria-hidden') !== 'true'
        && isCardVisible(el));
    } catch { return []; }
  };

  const TNP_DOM_CARD_MAX_W = 34, TNP_DOM_CARD_MAX_H = 47;

              const getHoleCardElements = () => {
    try {
      const own = findOwnSeat();
      const dataScope = document.querySelector('[data-player-cards]');
      const gateway = document.querySelector('[class*="playerMeGateway___"]');
      const scopes = [];
      if (dataScope) scopes.push(dataScope);
      if (gateway) scopes.push(gateway);
      if (own) scopes.push(own);
      if (!scopes.length) return [];
      const seenEls = new Set();
      const parsed = [];
      for (const scope of scopes) {
        let els = Array.from(scope.querySelectorAll('div[role="img"][aria-label]'));
        if (!els.length) {
          els = Array.from(scope.querySelectorAll('[class*="front___"] > div, [class*="cardFace"] > div'));
        }
        for (const el of els) {
          if (seenEls.has(el)) continue;
          seenEls.add(el);
          if (el.closest('[class*="communityCards"]')) continue;
          if (el.getAttribute('aria-hidden') === 'true') continue;
          if (own && scope === own) {
            const seatWrap = el.closest?.('[id^="player-"]');
            if (seatWrap && !(own === seatWrap || own.contains(seatWrap) || seatWrap.contains(own))) continue;
          }
          if (!isCardVisible(el)) continue;
          const cards = extractCardStrings(el);
          if (cards.length > 0 && cards.length <= 2) parsed.push({ el, cards });
        }
        if (parsed.filter(d => d.cards.length === 1).length >= 2 && (dataScope || scope === gateway)) break;
      }
      const singles = parsed.filter(d => d.cards.length === 1);
      if (singles.length >= 2) return singles;
      const out = [];
      for (const d of parsed) {
        if (d.cards.length === 2) {
          const childFaces = Array.from(d.el.querySelectorAll(':scope > div[role="img"][aria-label], :scope div[role="img"][aria-label]'))
            .filter(c => isCardVisible(c) && c.getAttribute('aria-hidden') !== 'true');
          const childParsed = childFaces
            .map(c => ({ el: c, cards: extractCardStrings(c) }))
            .filter(cd => cd.cards.length >= 1);
          if (childParsed.length >= 2) { out.push(...childParsed); continue; }
        }
        out.push(d);
      }
      return out;
    } catch { return []; }
  };

  const getHoleCardElementForCard = (card, domCards) => {
    for (const d of domCards) {
      if (d.cards.length === 1 && d.cards[0] === card && !d.used) {
        d.used = true;
        return d.el;
      }
    }
    for (const d of domCards) {
      if (d.cards.includes(card) && !d.used) {
        d.used = true;
        return d.el;
      }
    }
    return null;
  };

  const domCardHtml = (el) => {
    try {
      const rect = el.getBoundingClientRect();
      if (rect.width < 4 || rect.height < 4) return `<div class="tnp-card-mini tnp-empty-card"></div>`;
      const scale = Math.min(TNP_DOM_CARD_MAX_W / rect.width, TNP_DOM_CARD_MAX_H / rect.height);
      const clone = el.cloneNode(true);
      clone.removeAttribute('id');
      clone.setAttribute('aria-hidden', 'true');
      for (const nested of Array.from(clone.querySelectorAll('[id]') ?? [])) nested.removeAttribute('id');
      for (const token of Array.from(clone.classList ?? [])) {
        if (/^(?:glow|dimOut)___/i.test(token)) clone.classList.remove(token);
      }
      for (const nested of Array.from(clone.querySelectorAll('[class]') ?? [])) {
        for (const token of Array.from(nested.classList ?? [])) {
          if (/^(?:glow|dimOut)___/i.test(token)) nested.classList.remove(token);
        }
        nested.setAttribute?.('aria-hidden', 'true');
      }
      clone.style.transform = `scale(${Math.round(scale * 1000) / 1000})`;
      clone.style.transformOrigin = 'top left';
      clone.style.margin = '0';
      const wrap = document.createElement('div');
      wrap.className = 'tnp-dom-card';
      wrap.style.width = Math.round(rect.width * scale) + 'px';
      wrap.style.height = Math.round(rect.height * scale) + 'px';
      wrap.appendChild(clone);
      return wrap.outerHTML;
    } catch { return `<div class="tnp-card-mini tnp-empty-card"></div>`; }
  };

        let boardRetryTimer = null;
  let boardRetrySig = '';
  const cancelBoardRetry = () => {
    if (boardRetryTimer) { clearTimeout(boardRetryTimer); boardRetryTimer = null; }
  };
  const renderBoardRow = () => {
    const host = document.getElementById('tnp-board-cards');
    if (!host) return;
    if (!gameState.boardCards.length) {
      cancelBoardRetry();
      boardRetrySig = '';
      setHTML(host, `<span style="color:var(--tnp-muted); font-size:var(--tnp-fz-xs);">Waiting for Flop</span>`);
      return;
    }
    const seenDomCards = new Set();
    const domCards = getBoardCardElements()
      .map(el => ({ el, card: extractCardString(el) }))
      .filter(d => d.card && !seenDomCards.has(d.card) && seenDomCards.add(d.card));
    let html = '';
    let missing = 0;
    for (const card of gameState.boardCards) {
      const hit = domCards.find(d => d.card === card && !d.used);
      if (hit) { hit.used = true; html += domCardHtml(hit.el); }
      else { missing++; html += `<div class="tnp-card-mini tnp-empty-card"></div>`; }
    }
    setHTML(host, html);
                const sig = gameState.boardCards.join(',');
    if (missing > 0 && boardRetrySig !== sig) {
      boardRetrySig = sig;
      cancelBoardRetry();
      boardRetryTimer = setTimeout(() => {
        boardRetryTimer = null;
        try { renderBoardRow(); } catch { }
      }, 350);
    } else if (missing === 0) {
      cancelBoardRetry();
      boardRetrySig = '';
    }
  };

            let holeRetryTimer = null;
  let holeRetrySig = '';
  let holeRetryAttempts = 0;
  const cancelHoleRetry = () => {
    if (holeRetryTimer) { clearTimeout(holeRetryTimer); holeRetryTimer = null; }
    holeRetryAttempts = 0;
  };
  const renderHoleCardsRow = () => {
    const host = document.getElementById('tnp-hole-cards');
    if (!host) return;
    if (!gameState.holeCards.length) {
      cancelHoleRetry();
      holeRetrySig = '';
      setHTML(host, renderCard(null) + renderCard(null));
      return;
    }
    if (gameState.holeCards.length === 2 && gameState.holeCards[0] === gameState.holeCards[1]) {
      cancelHoleRetry();
      holeRetrySig = '';
      setHTML(host, renderCard(null) + renderCard(null));
      return;
    }
    const domCards = getHoleCardElements();
    let html = '';
    let missing = 0;
    for (const card of gameState.holeCards) {
      const el = getHoleCardElementForCard(card, domCards);
      if (el) {
        html += domCardHtml(el);
      } else {
        const siteFallback = siteCardHtml(card, '', 'rendered from the verified site card kit');
        if (/tnp-site-card/.test(siteFallback)) {
          html += siteFallback;
        } else {
          missing++;
          html += `<div class="tnp-card-mini tnp-card-back" title="hole card image not read yet"></div>`;
        }
      }
    }
    setHTML(host, html);
    const sig = gameState.holeCards.join(',');
    if (missing > 0 && holeRetrySig !== sig) {
      holeRetrySig = sig;
      holeRetryAttempts = 1;
      cancelHoleRetry();
      holeRetryTimer = setTimeout(() => {
        holeRetryTimer = null;
        try { renderHoleCardsRow(); } catch { }
      }, 350);
    } else if (missing > 0 && !holeRetryTimer) {
      holeRetryAttempts++;
      const delay = Math.min(2000, 350 * Math.pow(1.6, Math.min(holeRetryAttempts, 6)));
      holeRetryTimer = setTimeout(() => {
        holeRetryTimer = null;
        try { renderHoleCardsRow(); } catch { }
      }, delay);
    } else if (missing === 0) {
      cancelHoleRetry();
      holeRetrySig = '';
    }
  };

  const updateEqrNote = () => {
  };

          const renderDecisionBlock = () => {
    const box = document.getElementById('tnp-decision');
    if (!box) return;
    const verdict = document.getElementById('tnp-decision-verdict');
    const noteEl = document.getElementById('tnp-decision-note');
    const set = (id, text) => setText(document.getElementById(id), text);
    const color = (id, positive) => {
      const el = document.getElementById(id);
      if (!el) return;
      el.classList.toggle('tnp-d-pos', positive === true);
      el.classList.toggle('tnp-d-neg', positive === false);
    };
    const facing = gameState.holeCards.length === 2 && !gameState.userFolded
      && gameState.pot > 0 && (gameState.toCall > 0 || gameState.toCallUnknown);
    if (!facing) {
      box.classList.add('tnp-hidden');
      return;
    }
    box.classList.remove('tnp-hidden');
    set('tnp-d-pot', '$' + Math.round(gameState.pot).toLocaleString());
    if (gameState.toCallUnknown) {
      set('tnp-d-call', 'unreadable');
      set('tnp-d-req', '—');
      set('tnp-d-eq', gameState.equity !== null ? `${(gameState.equity * 100).toFixed(1)}%` : '—');
      set('tnp-d-gap', '—');
      set('tnp-d-ev', 'suspended');
      color('tnp-d-ev', null); color('tnp-d-gap', null);
      if (verdict) { verdict.className = 'tnp-decision-verdict tnp-verdict-neutral'; setText(verdict, 'Call size unreadable — priced by equity vs the field, not pot odds'); }
      setText(noteEl, 'The call button text did not parse, so the price-based math is off for this one decision.');
      return;
    }
    const call = gameState.toCall;
    const pot = gameState.pot;
    const req = call / (pot + call);
    set('tnp-d-call', '$' + call.toLocaleString());
    set('tnp-d-req', `${(req * 100).toFixed(1)}%`);
    if (gameState.equity === null) {
      set('tnp-d-eq', '…');
      set('tnp-d-gap', '—');
      set('tnp-d-ev', '…');
      color('tnp-d-ev', null); color('tnp-d-gap', null);
      if (verdict) { verdict.className = 'tnp-decision-verdict tnp-verdict-neutral'; setText(verdict, 'Calculating equity…'); }
      setText(noteEl, '');
      return;
    }
    const eq = gameState.equity;
    const ev = eq * (pot + call) - call;
    const gap = eq - req;
    const gaugeFill = document.getElementById('tnp-ev-gauge-fill');
    const gaugeReq = document.getElementById('tnp-ev-gauge-req');
    const gaugeNote = document.getElementById('tnp-ev-gauge-note');
    if (gaugeFill && gaugeReq) {
      gaugeFill.style.width = `${Math.min(100, Math.max(0, eq * 100)).toFixed(1)}%`;
      const marginal = Math.abs(gap) < 0.03 || Math.abs(ev) < Math.max(1, 0.02 * (pot + call));
      gaugeFill.classList.toggle('tnp-ev-pos', ev >= 0 && !marginal);
      gaugeFill.classList.toggle('tnp-ev-neg', ev < 0 && !marginal);
      gaugeFill.classList.toggle('tnp-ev-marginal', marginal);
      gaugeReq.style.left = `${Math.min(99, Math.max(0, req * 100)).toFixed(1)}%`;
    }
    if (gaugeNote) {
      const sprNow = gameState.effStack > 0 && pot > 0 ? (gameState.effStack / pot).toFixed(1) : null;
      setText(gaugeNote, ev >= 0
        ? `Calling is +EV: ${(eq * 100).toFixed(1)}% equity vs ${(req * 100).toFixed(1)}% break-even${sprNow ? ` · SPR ${sprNow}` : ''}`
        : `Calling is -EV: ${(eq * 100).toFixed(1)}% equity vs ${(req * 100).toFixed(1)}% break-even${sprNow ? ` · SPR ${sprNow}` : ''}`);
    }
    set('tnp-d-eq', `${(eq * 100).toFixed(1)}%`);
    set('tnp-d-gap', `${gap >= 0 ? '+' : ''}${(gap * 100).toFixed(1)}pp`);
    set('tnp-d-ev', `${ev >= 0 ? '+$' : '-$'}${Math.abs(Math.round(ev)).toLocaleString()}`);
    color('tnp-d-gap', Math.abs(gap) < 0.005 ? null : gap > 0);
    color('tnp-d-ev', Math.abs(ev) < 1 ? null : ev > 0);
    const ok = gap > 0.005, bad = gap < -0.005;
    if (verdict) {
      verdict.className = 'tnp-decision-verdict ' + (ok ? 'tnp-verdict-ok' : bad ? 'tnp-verdict-bad' : 'tnp-verdict-neutral');
      setText(verdict, ok
        ? `Priced in: ${(eq * 100).toFixed(1)}% equity beats the ${(req * 100).toFixed(1)}% break-even`
        : bad
          ? `Priced out: ${(eq * 100).toFixed(1)}% equity is below the ${(req * 100).toFixed(1)}% break-even`
          : 'Break-even: equity sits on the call price');
    }
    const notes = [];
    if (gameState.potStale) notes.push('pot read stale');
    if (gameState.equityMethod === 'monte-carlo' && gameState.equityCI) {
      notes.push(`±${((gameState.equityCI.upper - gameState.equityCI.lower) / 2 * 100).toFixed(1)}pp sampling band`);
    }
    if (gameState.equityProvisional) notes.push('estimate still refining');
    setText(noteEl, notes.length ? `Caveats: ${notes.join(' · ')}` : 'Pot odds alone do not decide the hand: position, ranges and board texture weigh in too.');
  };

  const SITE_SUIT_NAME = { '♥': 'hearts', '♦': 'diamonds', '♠': 'spades', '♣': 'clubs' };
  let _siteCardKit = { at: 0, ok: false, base: '', size: '', w: 0, h: 0, rankMap: null };
  const harvestSiteCardKit = () => {
    if (_siteCardKit.ok && Date.now() - _siteCardKit.at < 30000) return _siteCardKit;
    const kit = { at: Date.now(), ok: false, base: '', size: '', w: 0, h: 0, rankMap: null };
    try {
      let template = null;
      for (const el of getBoardCardElements()) { template = el; break; }
      if (!template) {
        for (const d of getHoleCardElements()) { template = d.el; break; }
      }
      if (!template) return (_siteCardKit = kit);
      const rect = template.getBoundingClientRect();
      if (rect.width < 4 || rect.height < 4) return (_siteCardKit = kit);
      const tClasses = Array.from(template.classList ?? []);
      const base = tClasses.find((c) => /^(?:four|two)Colors___/.test(c)) || '';
      const size = tClasses.find((c) => /^cardSize___/.test(c)) || '';
      if (!base) return (_siteCardKit = kit);
      const cardRe = /\.((hearts|diamonds|spades|clubs)-(?:A|K|Q|J|10|[2-9])___[A-Za-z0-9_-]+)/;
      let rankMap = null;
      for (const sheet of document.styleSheets) {
        let rules = null;
        try { rules = sheet.cssRules; } catch { continue; }
        if (!rules || !rules.length) continue;
        const map = {};
        let found = 0;
        for (const rule of rules) {
          const sel = rule.selectorText;
          if (!sel || sel.indexOf('hearts-') === -1 && sel.indexOf('spades-') === -1
            && sel.indexOf('diamonds-') === -1 && sel.indexOf('clubs-') === -1) continue;
          const m = sel.match(cardRe);
          if (!m) continue;
          const key = m[2].toLowerCase();
          if (!map[key]) { map[key] = m[1]; found++; }
        }
        if (found >= 40) { rankMap = map; break; }
      }
      if (!rankMap) return (_siteCardKit = kit);
      kit.ok = true; kit.base = base; kit.size = size;
      kit.w = Math.round(rect.width); kit.h = Math.round(rect.height);
      kit.rankMap = rankMap;
    } catch { }
    _siteCardKit = kit;
    return kit;
  };
  const siteCardHtml = (card, extraClass, titleText) => {
    const kit = harvestSiteCardKit();
    const rankToken = card[0] === 'T' ? '10' : card[0];
    const key = `${SITE_SUIT_NAME[card[1]]}-${rankToken}`.toLowerCase();
    const cls = kit.ok ? kit.rankMap[key] : null;
    if (!cls) return `<div class="tnp-card-mini tnp-card-noasset${extraClass || ''}" data-noasset="1" title="${escapeHtml(titleText || card)} — no loaded card artwork for this rank/suit; text fallback">${escapeHtml(card[0] + card[1])}</div>`;
    const scale = Math.min(20 / kit.w, 28 / kit.h);
    return `<div class="tnp-site-card${extraClass || ''}" title="${escapeHtml(titleText || card)}">` +
      `<div class="${kit.base} ${cls}${kit.size ? ' ' + kit.size : ''}" style="transform:scale(${Math.round(scale * 1000) / 1000});transform-origin:top left;" aria-hidden="true"></div></div>`;
  };

  const renderOutsChips = (hole, board) => {
    const outsCardsEl = document.getElementById('tnp-outs-cards');
    if (!outsCardsEl) return;
    const cards = analyzeOutsCards(hole, board);
    if (!cards || !cards.length) { setHTML(outsCardsEl, ''); return; }
    const clean = cards.filter(c => !c.dirty).length;
    const dirty = cards.length - clean;
    const chips = cards.slice(0, 12).map(c =>
      siteCardHtml(c.card, c.dirty ? ' tnp-out-dirty tnp-out-chip' : ' tnp-out-chip',
        `${c.label}${c.dirty ? ' · dirty out (discounted)' : ' · clean out'}${c.weight < 1 ? ` · weight ${c.weight}` : ''}`)
    ).join('');
    const odds = [];
    const next = nextCardImprovement(hole, board);
    if (next) odds.push(`next ${next.improve}/${next.unseen} = ${Math.round(next.pct * 100)}%`);
    const draws = classifyDraws(hole, board);
    const eqOuts = gameState.equityOuts;
    const eqChips = (eqOuts && Array.isArray(eqOuts.cards) && eqOuts.cards.length)
      ? eqOuts.cards.slice(0, 8).map(c =>
        siteCardHtml(c.card, ' tnp-out-eq tnp-out-chip', `raises win equity vs a random hand: +${(c.delta * 100).toFixed(1)}pp to ${(c.equity * 100).toFixed(1)}% (exact enumeration)`))
        .join('') + (eqOuts.cards.length > 8 ? `<span class="tnp-outs-more">+${eqOuts.cards.length - 8} more</span>` : '')
      : '';
    const eqLabel = (eqOuts && Array.isArray(eqOuts.cards))
      ? ` · ${eqOuts.cards.length} card${eqOuts.cards.length === 1 ? '' : 's'} raise win equity`
      : '';
    setHTML(outsCardsEl, chips
      + (cards.length > 12 ? `<span class="tnp-outs-more">+${cards.length - 12} more</span>` : '')
      + `<span class="tnp-outs-count">${clean} clean${dirty ? ` · ${dirty} dirty` : ''}${odds.length ? ` · ${escapeHtml(odds.join(' · '))}` : ''}</span>`
      + (draws.labels.length ? `<span class="tnp-outs-count tnp-outs-draws">${escapeHtml(draws.labels.join(' · '))}</span>` : '')
      + (eqChips ? `<span class="tnp-outs-count">equity outs (exact, vs random hand)${escapeHtml(eqLabel)}:</span>${eqChips}` : ''));
  };

  const renderActionBanner = () => {
    if (settings.hudEnabled === false) return;
    const banner = document.getElementById('tnp-action-banner');
    if (!banner) return;
    const actionEl = document.getElementById('tnp-banner-action');
    const subEl = document.getElementById('tnp-banner-sub');

    let targetClass = '';
    let actionText = '';
    let actionColor = '';
    let subText = '';
    let whyHtml = '';
    let overfold = null;

    const suppressedByQuality = hudStatus === 'paused' || hudStatus === 'parser-issue';

    if (settings.actionBanner && !suppressedByQuality && !gameState.userFolded && gameState.holeCards.length && isHeroTurn()) {
      if (gameState.isCalculating || gameState.equity === null) {
        targetClass = 'tnp-banner-active';
        actionText = '···';
        actionColor = 'var(--tnp-muted)';
        subText = 'Calculating equity…';
      } else {
        const actionBtns = getActiveActionButtons();

        const realized = gameState.equity === null ? null
          : gameState.equity * eqrFactor(gameState.position, gameState.activeOpponents, gameState.street);
        overfold = riverOverfoldCtx();
        const rec = getRecommendation(gameState.equity, gameState.activeOpponents, gameState.toCall, gameState.pot, actionBtns, {
          street: gameState.street,
          position: gameState.position,
          raiseLevel: gameState.raiseLevel,
          outs: gameState.outs,
          hole: gameState.holeCards,
          board: gameState.boardCards,
          boardTexture: gameState.boardTexture,
          ciWidth: gameState.equityCI ? gameState.equityCI.upper - gameState.equityCI.lower : 0.02,
          realizedEquity: realized,
          overfold,
          raiseReliable: gameState.raiseReliable,
          noPreFlop: settings.noPreFlopMode,
          effStack: gameState.effStack || gameState.heroStack || 0,
          seats: gameState.occupiedSeats || 0,
          oppAggressive: !!gameState.oppAggressive,
          risk: gameState.boardRiskRead || null,
          tableAdjust: gameState.tableAdjust,
          toCallUnknown: !!gameState.toCallUnknown,
          readIssues: gameState.readIssues,
          potStale: !!gameState.potStale,
          preflopOpp: gameState.preflopOpp,
          flopCtx: gameState.flopCtx
        });
        if (rec.intent && rec.intent !== 'wait') {
          lastRecAt = Date.now();
          lastRecIntent = rec.text || rec.intent;
          replayAttachAdvice({ intent: rec.intent, text: rec.text, why: rec.why, requiredEquity: rec.requiredEquity, edge: rec.edge });
          const btnType = classifyButtonAction(rec.text) ?? rec.intent;
          const cls = { fold: 'fold', check: 'check', call: 'call', raise: 'raise' }[btnType] ?? 'check';
          targetClass = `tnp-banner-active tnp-banner-${cls}`;
          actionText = rec.text;

          const ciHalfPct = gameState.equityCI && gameState.equityMethod === 'monte-carlo'
            ? ` ±${((gameState.equityCI.upper - gameState.equityCI.lower) / 2 * 100).toFixed(1)}` : '';
          const edgePct = Math.round(rec.edge * 100);

          const whyShort = String(rec.why || '').split(' · ')[0];
          subText = [
            `Equity ${Math.round(gameState.equity * 100)}%${ciHalfPct} vs ${(rec.requiredEquity * 100).toFixed(1)}% required (${edgePct >= 0 ? '+' : ''}${edgePct})`,
            `${rec.opponents} opp · ${rec.confidenceWord.toLowerCase()} confidence`,
            whyShort
          ].join('\n');

          if (rec.intent === 'raise') {
            const legalFloor = readBetInputFloorDom();
            if (legalFloor > 0) {
              subText += `\n<span class="tnp-legal-floor">Legal raise floor: $${legalFloor.toLocaleString()} · verified from server state</span>`;
            } else if (/\$[\d,]/.test(rec.text)) {
              subText += '\n<span class="tnp-legal-unverified">Raise size is an estimate — the server minimum is not in this frame</span>';
            }
          }
        }
      }

      const ciHalf = gameState.equityCI ? (gameState.equityCI.upper - gameState.equityCI.lower) / 2 : 0.005;
      const method = gameState.equityMethod === 'exact'
        ? 'Exact result.'
        : gameState.equityMethod === 'preflop-table'
          ? 'Preflop table: equity vs a random hand (offline reference).'
          : `${gameState.equityProvisional ? 'Refining' : 'Estimate'} ±${(ciHalf * 100).toFixed(1)}% · ${gameState.mcSamples.toLocaleString()} simulations.`;
      const rangeNote = gameState.liveRangeDisplay?.length
        ? `Ranges from this hand's actions: ${gameState.liveRangeDisplay.map(d => `${d.pos ?? 'seat?'} top ${Math.round(d.frac * 100)}%`).join(' · ')}.`
        : 'Ranges assumed random to moderately wide.';

      const bannerRealized = gameState.equity === null ? null
        : gameState.equity * eqrFactor(gameState.position, gameState.activeOpponents, gameState.street);
      const evs = gameState.toCallUnknown
        ? { fold: 0, call: null, shove: null, shoveFe: null, shoveAssumed: null }
        : evOptions(bannerRealized, gameState.pot, gameState.toCall, gameState.effStack || gameState.heroStack || 0,
          overfold ? overfold.lb : null);
      const evLine = gameState.toCallUnknown
        ? 'Call size unreadable: EV math is off for this decision; decide by equity vs the field.'
        : (gameState.toCall > 0 && evs.call !== null)
          ? `Calling is worth ${evs.call >= 0 ? '+' : '-'}$${Math.abs(Math.round(evs.call)).toLocaleString()} in EV; folding is $0.${gameState.potStale ? ' Pot read stale.' : ''}`
          : (evs.shove !== null
            ? `Shove model (¾ pot): +$${Math.round(evs.shove).toLocaleString()} at their ${(evs.shoveFe * 100).toFixed(0)}% floor fold rate; called equity ~15% below headline.`
            : (evs.shoveAssumed !== null
              ? `Shove model (¾ pot): +$${Math.round(evs.shoveAssumed).toLocaleString()} assuming 40% folds (no fold stat yet); called equity ~15% below headline.`
              : ''));

      const mdf = mdfVsBet(gameState.pot, gameState.toCall);
      const mdfLine = mdf !== null
        ? `MDF ${Math.round(mdf * 100)}%: fold more than ${100 - Math.round(mdf * 100)}% here and pure bluffs profit; early streets can defend less.`
        : '';
      const multiwayLine = gameState.activeOpponents >= 2
        ? `Multiway (${gameState.activeOpponents} opp): draws lose value, strong hands gain.`
        : '';
      const dangerRead = boardDanger(gameState.holeCards, gameState.boardCards);
      const dangerLine = dangerRead.tag
        ? `Board warning: ${dangerRead.message ?? dangerRead.tag + ' risk on board'}.`
        : '';

      const riskRead = gameState.boardRiskRead;
      const riskLine = (!dangerRead.tag && riskRead && (riskRead.suitThreat || riskRead.straightThreat))
        ? `Board risk: ${riskRead.message}${gameState.oppAggressive ? ' They bet this street, so the call is priced harder.' : ''}`
        : '';
      const exploitLine = (overfold && !dangerRead.tag)
        ? `${escapeHtml(overfold.name)} folds ${overfold.folded}/${overfold.faced} vs river bets. Bluff more; bet big only with strong hands.`
        : '';
      const unknowns = [];
      if (!gameState.pot) unknowns.push('pot size');
      if (!gameState.toCall && !gameState.toCallUnknown) unknowns.push('amount to call');
      if (gameState.toCallUnknown) unknowns.push('call size (unreadable)');
      whyHtml = `
        <b>${method}</b>
        ${rangeNote}<br>
        ${evLine ? evLine + '<br>' : ''}${dangerLine ? dangerLine + '<br>' : ''}${riskLine ? riskLine + '<br>' : ''}${mdfLine ? mdfLine + '<br>' : ''}${multiwayLine ? multiwayLine + '<br>' : ''}
        ${exploitLine ? exploitLine + '<br>' : ''}
        ${unknowns.length ? `Missing: ${unknowns.join(', ')}; sizing hints off.` : ''}
      `;
    }

    if (banner.className !== targetClass) banner.className = targetClass;
    if (actionEl && actionEl.style.color !== actionColor) actionEl.style.color = actionColor;
    setText(actionEl, actionText);
    if (/<span class="tnp-legal/.test(subText)) setHTML(subEl, subText);
    else setText(subEl, subText);
    setHTML(document.getElementById('tnp-why-panel'), whyHtml);
  };

  const renderUI = () => {
    if (!uiElement) return;

    renderActionBanner();

    const foldedVisible = gameState.userFolded && activeTab === 'analysis';
    const bodyContent = document.getElementById('tnp-body-content');
    const foldedOverlay = document.getElementById('tnp-folded-overlay');
    if (bodyContent && bodyContent.classList.contains('tnp-hidden') !== foldedVisible) {
      bodyContent.classList.toggle('tnp-hidden', foldedVisible);
    }
    if (foldedOverlay && foldedOverlay.classList.contains('tnp-hidden') === foldedVisible) {
      foldedOverlay.classList.toggle('tnp-hidden', !foldedVisible);
    }
    if (foldedVisible) return;

    renderHoleCardsRow();
    renderBoardRow();
    if (gameState.holeCards.length === 2) renderOutsChips(gameState.holeCards, gameState.boardCards);

    const textureTag = gameState.boardTexture.length && gameState.boardTexture[0] !== 'Dry'
      ? ` · ${gameState.boardTexture.join(' · ')}` : '';
    setText(document.getElementById('tnp-street'), gameState.street !== 'Preflop' ? `(${gameState.street}${textureTag})` : (textureTag ? `(${textureTag.slice(3)})` : ''));
    setText(document.getElementById('tnp-opponents'), gameState.activeOpponents);

    document.querySelectorAll('#tnp-timeline .tnp-timeline-step').forEach(step => {
      const order = ['Preflop', 'Flop', 'Turn', 'River'];
      const stepIdx = order.indexOf(step.dataset.street);
      const nowIdx = order.indexOf(gameState.street);
      step.classList.toggle('tnp-timeline-now', stepIdx === nowIdx);
      step.classList.toggle('tnp-timeline-done', stepIdx < nowIdx);
    });

    const chipsEl = document.getElementById('tnp-range-chips');
    if (chipsEl) {
      if (gameState.liveRangeDisplay && gameState.liveRangeDisplay.length && gameState.holeCards.length) {
        setHTML(chipsEl, '<span class="tnp-range-lead">Ranges</span>' + gameState.liveRangeDisplay
          .map(d => `<span class="tnp-range-chip" title="Estimated range for ${escapeHtml(d.name)} after observed actions this hand">${escapeHtml(d.name)}: top ${Math.max(2, Math.round(d.frac * 100))}%</span>`)
          .join(''));
      } else {
        setHTML(chipsEl, '');
      }
    }

    if (gameState.evalResult && gameState.holeCards.length) {
      setText(document.getElementById('tnp-relative-strength'), evaluateRelativeStrength(gameState.holeCards, gameState.boardCards, gameState.evalResult));
      setText(document.getElementById('tnp-blockers'), detectBlockers(gameState.holeCards, gameState.boardCards));
    } else {
      setText(document.getElementById('tnp-relative-strength'), '-');
      setText(document.getElementById('tnp-blockers'), '-');
    }

    const eqEl = document.getElementById('tnp-equity');
    const fillEl = document.getElementById('tnp-equity-fill');
    const ciEl = document.getElementById('tnp-equity-ci');
    const ciTextEl = document.getElementById('tnp-equity-ci-text');
    const adviceEl = document.getElementById('tnp-advice');
    const sizingEl = document.getElementById('tnp-bet-sizing');
    const distEl = document.getElementById('tnp-hand-type-dist');

    if (!gameState.holeCards.length) {
      setText(eqEl, 'Waiting');
      eqEl.style.color = 'var(--tnp-muted)';
      fillEl.style.width = '0%';
      if (ciEl) ciEl.style.width = '0%';
      setText(ciTextEl, '');
      gameState.mcSamples = 0;
      setHTML(distEl, '');
      setText(adviceEl, 'Wait for hand');
      adviceEl.style.color = 'var(--tnp-muted)';
      setText(sizingEl, '');
      setText(document.getElementById('tnp-callev'), 'n/a');
      setText(document.getElementById('tnp-realized'), 'n/a');
    } else if (gameState.isCalculating && gameState.equity === null) {
      setText(eqEl, 'Calc...');
      eqEl.style.color = 'var(--tnp-muted)';
      if (isHeroTurn()) {
        setText(adviceEl, 'Analyzing...');
        adviceEl.style.color = 'var(--tnp-muted)';
      } else {
        setText(adviceEl, 'Waiting for turn...');
        adviceEl.style.color = 'var(--tnp-muted)';
      }
      setText(sizingEl, '');
    } else if (gameState.equity !== null) {
      const eqPercent = (gameState.equity * 100).toFixed(1);

      const eqBand = (gameState.equityMethod === 'monte-carlo' && gameState.equityCI)
        ? ` ±${((gameState.equityCI.upper - gameState.equityCI.lower) / 2 * 100).toFixed(1)}` : '';
      setText(eqEl, `${eqPercent}%${eqBand}`);
      eqEl.style.color = 'var(--tnp-accent-2)';
      fillEl.style.width = `${Math.min(100, Math.max(0, gameState.equity * 100))}%`;
      if (gameState.equity < 0.25) fillEl.style.background = 'var(--tnp-danger)';
      else if (gameState.equity > 0.6) fillEl.style.background = 'var(--tnp-success)';
      else fillEl.style.background = 'var(--tnp-accent-2)';

      if (ciEl && ciTextEl && gameState.equityCI) {
        const lo = gameState.equityCI.lower * 100;
        const hi = gameState.equityCI.upper * 100;
        ciEl.style.left = `${lo}%`;
        ciEl.style.width = `${hi - lo}%`;

        const poolNote = gameState.mcWorkers > 1
          ? ` · ${gameState.mcWorkers} workers`
          : (gameState.mcWorkers === 1 ? '' : ' · main thread');
        const ws = gameState.winSplit;
        const wsTotal = ws ? (ws.win + ws.tie + ws.loss) : 0;
        const splitNote = ws && wsTotal > 0
          ? ` · W/T/L ${Math.round(ws.win / wsTotal * 100)}/${Math.round(ws.tie / wsTotal * 100)}/${Math.round(ws.loss / wsTotal * 100)}%`
          : '';
        const mandateNote = gameState.equityMethod === 'monte-carlo'
          ? (gameState.equityTrialsComplete
            ? (gameState.equityCached ? ' · 1,000,000 trials (cached)' : ' · 1,000,000 trials')
            : ` · ${(gameState.mcSamples || 0).toLocaleString()} of ${(gameState.equityMandatedTrials || 1000000).toLocaleString()} trials (resource-limited)`)
          : '';
        const exactNote = (gameState.exactEquity !== null && gameState.exactSamples > 0)
          ? ` · exact complement ${(gameState.exactEquity * 100).toFixed(2)}% (${gameState.exactSamples.toLocaleString()} deals)`
          : '';
        setText(ciTextEl, gameState.equityMethod === 'exact'
          ? `Exact enumeration · ${gameState.mcSamples.toLocaleString()} deals${splitNote}`
          : gameState.equityMethod === 'preflop-table'
            ? `Table lookup · provisional, 1M simulation running${exactNote}`
            : `${gameState.equityProvisional ? 'Provisional (refining)' : '95% range'}: ${lo.toFixed(1)}% – ${hi.toFixed(1)}%${splitNote}${mandateNote}${exactNote}`);
      }

      if (distEl && gameState.handTypeDist) {
        const dist = gameState.handTypeDist;
        const top = dist.map((pct, i) => ({ name: HAND_TYPE_NAMES[i], pct }))
          .filter(x => x.pct > 0.02)
          .sort((a, b) => b.pct - a.pct)
          .slice(0, 4);
        setHTML(distEl, top.map(x => `<span>${x.name}: ${(x.pct * 100).toFixed(0)}%</span>`).join(' '));
      }

      const realized = gameState.equity * eqrFactor(gameState.position, gameState.activeOpponents, gameState.street);
      const callEvEl = document.getElementById('tnp-callev');
      if (callEvEl) {
        if (gameState.toCallUnknown) {
          setText(callEvEl, 'call size unreadable');
          callEvEl.style.color = '';
          callEvEl.title = 'The call button text did not parse; EV math is suspended for this decision.';
        } else {
          const evs = evOptions(realized, gameState.pot, gameState.toCall, gameState.effStack || gameState.heroStack || 0,
            riverOverfoldCtx()?.lb ?? null);
          if (evs.call !== null) {
            const sign = evs.call >= 0 ? '+' : '-';
            const shoveNote = evs.shove !== null
              ? ` · shove ${evs.shove >= 0 ? '+' : '-'}$${Math.abs(Math.round(evs.shove)).toLocaleString()}`
              : (evs.shoveAssumed !== null ? ` · shove ${evs.shoveAssumed >= 0 ? '+' : '-'}$${Math.abs(Math.round(evs.shoveAssumed)).toLocaleString()}~` : '');
            setText(callEvEl, `${sign}$${Math.abs(Math.round(evs.call)).toLocaleString()} · call $${gameState.toCall.toLocaleString()}${shoveNote}${gameState.potStale ? ' · pot stale' : ''}`);
            callEvEl.style.color = evs.call >= 0 ? 'var(--tnp-success)' : 'var(--tnp-danger)';
            callEvEl.title = 'Call EV: equity share of pot minus call cost. Shove EV is a model (¾-pot, fold rate as noted, called equity ~15% below headline).';
          } else {
            setText(callEvEl, 'n/a');
            callEvEl.style.color = '';
          }
        }
      }
      const realizedEl = document.getElementById('tnp-realized');
      if (realizedEl) {
        const adj = Math.abs(realized - gameState.equity) > 0.005;
        setText(realizedEl, `${(realized * 100).toFixed(1)}%${adj ? ' · pos/mw adj' : ''}`);
        realizedEl.style.color = adj ? 'var(--tnp-accent-2)' : '';
      }

      if (isHeroTurn()) {
        if (hudStatus === 'parser-issue' || hudStatus === 'paused') {
          setText(adviceEl, 'Holding: table read issue');
          adviceEl.style.color = 'var(--tnp-muted)';
          adviceEl.title = (gameState.readIssues && gameState.readIssues.length)
            ? `Reads disagree (${gameState.readIssues.join('; ')}). Advice resumes when the table reads clean.`
            : 'A table read is broken; advice resumes when the HUD reads the table cleanly.';
          if (sizingEl) setText(sizingEl, '');
        } else {
          const actionBtns = getActiveActionButtons();
          const overfold = riverOverfoldCtx();
          const danger = boardDanger(gameState.holeCards, gameState.boardCards);
          const rec = getRecommendation(gameState.equity, gameState.activeOpponents, gameState.toCall, gameState.pot, actionBtns, {
            street: gameState.street,
            position: gameState.position,
            raiseLevel: gameState.raiseLevel,
            outs: gameState.outs,
            hole: gameState.holeCards,
            board: gameState.boardCards,
            boardTexture: gameState.boardTexture,
            ciWidth: gameState.equityCI ? gameState.equityCI.upper - gameState.equityCI.lower : 0.02,
            realizedEquity: realized,
            overfold,
            raiseReliable: gameState.raiseReliable,
            noPreFlop: settings.noPreFlopMode,
            effStack: gameState.effStack || gameState.heroStack || 0,
            seats: gameState.occupiedSeats || 0,
            oppAggressive: !!gameState.oppAggressive,
            risk: gameState.boardRiskRead || null,
            tableAdjust: gameState.tableAdjust,
            toCallUnknown: !!gameState.toCallUnknown,
            readIssues: gameState.readIssues,
            potStale: !!gameState.potStale,
            preflopOpp: gameState.preflopOpp,
            flopCtx: gameState.flopCtx
          });
          if (rec.badgeText) {
            setHTML(adviceEl, `<span class="tnp-badge ${rec.badgeClass}">${escapeHtml(rec.badgeText)}</span> ${escapeHtml(rec.text)}`);
          } else {
            setText(adviceEl, rec.text);
          }
          adviceEl.style.color = rec.color;
          if (rec.why) adviceEl.title = rec.why;

          if (sizingEl) {
            const serverFloor = readBetInputFloorDom();
            const sizing = gameState.toCallUnknown ? null
              : getBetSizingAdvice(gameState.equity, gameState.pot, gameState.toCall, gameState.activeOpponents, gameState.street, gameState.boardTexture, gameState.bbAmount, gameState.raiseLevel, gameState.effStack || gameState.heroStack || 0, danger, gameState.boardRiskRead || null, !!gameState.oppAggressive, serverFloor);

            const exploitSizing = (overfold && rec.intent === 'raise'
              && gameState.equity < 1 / (gameState.activeOpponents + 1) * 0.9)
              ? overfoldSizingText(overfold) : '';
            setText(sizingEl, sizing || exploitSizing || '');
          }
        }
      } else {
        setText(adviceEl, 'Waiting for turn...');
        adviceEl.style.color = 'var(--tnp-muted)';
        setText(sizingEl, '');
      }
    }

    const engineReportEl = document.getElementById('tnp-engine-report');
    if (engineReportEl) {
      const last = gameState.equityMethod === 'exact'
        ? `last: exact · ${gameState.mcSamples.toLocaleString()} deals${gameState.mcElapsedMs ? ` · ${Math.max(1, Math.round(gameState.mcElapsedMs))} ms` : ''}`
        : gameState.equityMethod === 'preflop-table'
          ? 'last: preflop 169-table (vs random)'
        : (gameState.equity !== null
          ? `last: ${(gameState.mcSamples || 0).toLocaleString()} samples · ${gameState.mcWorkers || 0} worker${(gameState.mcWorkers || 0) === 1 ? '' : 's'}${gameState.mcElapsedMs ? ` · ${(gameState.mcElapsedMs / 1000).toFixed(1)} s` : ''}`
          : 'waiting for the first hand');
      setText(engineReportEl, `sampler · visible-DOM read-only · ${last}`);
    }

    gameState.potOdds = (gameState.toCall > 0 && gameState.pot > 0)
      ? (gameState.toCall / (gameState.pot + gameState.toCall)) * 100
      : 0;
    const potOddsEl = document.getElementById('tnp-equity-tick');
    if (potOddsEl && gameState.potOdds && gameState.holeCards.length) {
      potOddsEl.style.left = Math.min(100, gameState.potOdds) + '%';
      potOddsEl.style.display = 'block';
    } else if (potOddsEl) {
      potOddsEl.style.display = 'none';
    }
    renderDecisionBlock();

    const compactEquity = document.getElementById('tnp-compact-equity');
    const compactPotOdds = document.getElementById('tnp-compact-potodds');
    const compactStrength = document.getElementById('tnp-compact-strength');
    const compactSignal = document.getElementById('tnp-compact-signal');
    const compactConfidence = document.getElementById('tnp-compact-confidence');
    if (compactEquity) {
      setText(compactEquity, gameState.equity !== null && gameState.holeCards.length
        ? `${(gameState.equity * 100).toFixed(1)}%${gameState.equityMethod === 'exact' ? ' · exact' : gameState.equityMethod === 'preflop-table' ? ' · table' : ''}`
        : 'n/a');
      setText(compactPotOdds, gameState.toCall > 0 && gameState.pot > 0
        ? `${((gameState.toCall / (gameState.pot + gameState.toCall)) * 100).toFixed(1)}% needed`
        : 'n/a');
      if (compactPotOdds) {
        if (gameState.toCall > 0 && gameState.pot > 0 && !gameState.toCallUnknown && gameState.equity !== null) {
          const reqC = gameState.toCall / (gameState.pot + gameState.toCall);
          compactPotOdds.style.color = gameState.equity > reqC + 0.005
            ? 'var(--tnp-success)'
            : gameState.equity < reqC - 0.005 ? 'var(--tnp-danger)' : '';
        } else {
          compactPotOdds.style.color = '';
        }
      }
      setText(compactStrength, gameState.holeCards.length && gameState.evalResult
        ? evaluateRelativeStrength(gameState.holeCards, gameState.boardCards, gameState.evalResult)
        : 'n/a');
      const bannerSignal = document.getElementById('tnp-banner-action');
      const bannerLive = bannerSignal && bannerSignal.textContent
        && bannerSignal.textContent !== '-' && bannerSignal.textContent !== '···';
      setText(compactSignal, bannerLive ? bannerSignal.textContent : 'n/a');
      compactSignal.style.color = bannerLive && bannerSignal.style.color
        ? bannerSignal.style.color : '';
      if (compactConfidence) {
        const ci = gameState.equityCI;
        setText(compactConfidence, ci && gameState.equity !== null
          ? (gameState.equityMethod === 'exact'
            ? 'Exact result'
            : `${gameState.equityProvisional ? 'Refining' : '95% range'} ${(ci.lower * 100).toFixed(0)}–${(ci.upper * 100).toFixed(0)}%`)
          : '');
      }
    }
    const minimalStatus = document.getElementById('tnp-minimal-status');
    if (minimalStatus) {
      const def = HUD_STATUS[hudStatus] ?? HUD_STATUS.ready;
      setText(minimalStatus, def.label);
      minimalStatus.style.color = def.color;
    }
    const minimalEquity = document.getElementById('tnp-minimal-equity');
    if (minimalEquity) {
      setText(minimalEquity, gameState.equity !== null && gameState.holeCards.length
        ? `${(gameState.equity * 100).toFixed(0)}%`
        : '');
    }

    renderOpponentsPanel();
    renderMirrorPanel();
    renderSessionPanel();
    renderBankrollPanel();

    if (activeTab === 'settings') updateEqrNote();
  };

  const lastPlayerStats = {};

  const HEAT_MIN_RECENT = 6;
  const HEAT_MIN_BASELINE = 20;
  const heatRead = (p) => {
    if (!p) return null;
    const all = Array.isArray(p.recent) ? p.recent : [];
    const recent = all.slice(-10);
    const windows = {};
    for (const size of [10, 25, 50]) {
      const slice = all.slice(-size);
      windows[size] = { hands: slice.length, vpip: slice.length ? slice.filter(r => r.v).length / slice.length : null };
    }
    const baseHands = p.handsObserved || 0;
    if (recent.length < HEAT_MIN_RECENT || baseHands < HEAT_MIN_BASELINE) {
      return { hidden: true, recent: recent.length, baseHands, windows };
    }
    const baseV = (p.vpipCount || 0) / baseHands;
    const recV = recent.filter(r => r.v).length / recent.length;
    const baseA = (p.postTotal || 0) > 0 ? (p.postAgg || 0) / p.postTotal : null;
    const recAggHands = recent.filter(r => r.a).length;
    const reasons = [];
    let dir = 'steady';
    if (recV - baseV >= 0.15) {
      dir = 'heating';
      reasons.push(`entering ${Math.round(recV * 100)}% of the last ${recent.length} hands vs ${Math.round(baseV * 100)}% all-time`);
    } else if (baseV - recV >= 0.15) {
      dir = 'cooling';
      reasons.push(`entering ${Math.round(recV * 100)}% of the last ${recent.length} hands vs ${Math.round(baseV * 100)}% all-time`);
    }
    if (dir !== 'steady') {
      for (const size of [25, 50]) {
        const w = windows[size].vpip;
        if (w !== null && windows[size].hands >= size) {
          reasons.push(`last ${size} hands: ${Math.round(w * 100)}% entered`);
        }
      }
    }
    if (recAggHands >= 3 && (baseA === null || recAggHands / recent.length >= baseA + 0.15)) {
      if (dir === 'steady') dir = 'heating';
      reasons.push(`aggressive in ${recAggHands} of the last ${recent.length} hands${baseA !== null ? ` vs ${Math.round(baseA * 100)}% before` : ''}`);
    }
    if (dir === 'steady') return { dir, reasons: [`no meaningful shift: ${Math.round(recV * 100)}% recent vs ${Math.round(baseV * 100)}% baseline`], recent: recent.length, baseHands, windows };
    return { dir, reasons, recent: recent.length, baseHands, windows };
  };

  const renderOpponentsPanel = () => {
    const listEl = document.getElementById('tnp-opponents-list');
    if (!listEl) return;

    const seats = getAllSeats();
    const me = findOwnSeat();
    const playerList = [];
    const listedIds = new Set();

    for (const seat of seats) {
      if (isOwnPlayerSeat(seat, me)) continue;
      if (isSeatEmpty(seat)) continue;
      const player = getPlayerName(seat);
      if (!player) continue;
      if (listedIds.has(player.id)) continue;
      listedIds.add(player.id);
      const p = profiles[player.id];
      const type = p ? classifyPlayer(p) : 'UNKNOWN';
      const typeDef = PLAYER_TYPES[type];
      const m = getProfileMetrics(p);
      playerList.push({ player, p, type, typeDef, m, isFolded: isSeatFolded(seat), isSittingOut: isSeatSittingOut(seat) });
    }

    for (const key of Object.keys(lastPlayerStats)) {
      if (!listedIds.has(key)) delete lastPlayerStats[key];
    }

    const heatEl = document.getElementById('tnp-table-heat');
    if (heatEl) {
      const typeCounts = {};
      playerList.forEach(p => { if (p.type !== 'UNKNOWN') typeCounts[p.type] = (typeCounts[p.type] || 0) + 1; });
      const profiled = playerList.filter(p => p.type !== 'UNKNOWN');
      const reading = playerList.length - profiled.length;
      const parts = [];
      if (profiled.length) {
        parts.push(Object.entries(typeCounts)
          .map(([t, c]) => `${c} ${PLAYER_TYPES[t]?.short || t}`)
          .join(' · '));
        const samples = profiled.map(p => p.m ? p.m.hands : 0).filter(h => h > 0);
        if (samples.length) {
          const avg = Math.round(samples.reduce((a, b) => a + b, 0) / samples.length);
          const shown = samples.slice(0, 5).join('/');
          parts.push(`samples ${shown}${samples.length > 5 ? '…' : ''} (avg ${avg}h)`);
        }
      }
      if (reading) parts.push(`${reading} still reading`);
      const heatLine = parts.join(' · ')
        || (logCapture.seenAny ? 'reading table…' : "waiting for the table's action feed…");
      setHTML(heatEl, `Table heat: <b>${escapeHtml(heatLine)}</b>`);
      heatEl.title = 'Observed opponent tendencies at this table with their sample sizes. '
        + 'A "?" means fewer than 10 hands: too thin to classify, not a zero.';
    }

    if (playerList.length === 0) {
      setHTML(listEl, `<div style="color:var(--tnp-muted); font-size:var(--tnp-fz-xs); text-align:center; padding:10px;">No opponents at the table</div>`);
      return;
    }

    setHTML(listEl, playerList.map(({ player, p, type, typeDef, m, isFolded, isSittingOut }) => {
      const hands = m ? m.hands : 0;

      let ring;
      if (hands < 20) ring = `opacity:0.75; border-color:var(--tnp-text-faint);`;
      else if (hands < 75) ring = `opacity:0.7; border-color:${typeDef.color} ${typeDef.color} var(--tnp-border) var(--tnp-border);`;
      else ring = `opacity:1; border-color:${typeDef.color};`;

      const style = isFolded || isSittingOut ? 'opacity:0.55;' : '';

      const stats = m && m.tier !== 'unknown'
        ? `V${m.vpip} P${m.pfr} A${m.afqKnown ? m.afq : `~${m.afq}`}${m.af && (m.af.af !== null || m.af.infinite) ? ` AF ${afLabelOf(m.af)}` : ''} · ${m.hands}h`
        : (m ? `${m.hands}h · thin sample` : 'No data yet');
      const tierTag = m ? `<span class="tnp-tier-tag tnp-tier-${m.tier}">${escapeHtml(m.tier === 'unknown' ? '?' : typeDef.short)}</span>` : '';
      const pulse = lastPlayerStats[player.id] !== undefined && lastPlayerStats[player.id] !== stats ? ' tnp-pulse' : '';
      lastPlayerStats[player.id] = stats;
      const trend = (() => {
        const pr = p || null;
        if (!pr || !pr.sess || !pr.sess.hands) return '';
        const parts = [];
        const sessEntry = Math.round(100 * pr.sess.vpip / Math.max(1, pr.sess.hands));
        parts.push(`session: entered ${sessEntry}% of ${pr.sess.hands}`);
        const rec = Array.isArray(pr.recent) ? pr.recent : [];
        if (rec.length >= 3) {
          const last10V = rec.filter(x => x.v).length;
          const last10R = rec.filter(x => x.r).length;
          const last10A = rec.filter(x => x.a).length;
          parts.push(`last ${rec.length}: ${last10V} entered · ${last10R} raised · ${last10A} aggressive`);
        }
        const hr = heatRead(pr);
        if (hr && hr.hidden) {
          parts.push(`<span title="Heat compares the last 10 hands with the all-time baseline; it stays hidden until ${HEAT_MIN_RECENT} recent and ${HEAT_MIN_BASELINE} baseline hands exist.">heat: needs ${Math.min(rec.length, HEAT_MIN_RECENT)}/${HEAT_MIN_RECENT} recent · ${Math.min(pr.handsObserved || 0, HEAT_MIN_BASELINE)}/${HEAT_MIN_BASELINE} baseline</span>`);
        } else if (hr) {
          const arrow = hr.dir === 'heating' ? '▲' : hr.dir === 'cooling' ? '▼' : '=';
          parts.push(`<b title="${escapeHtml(hr.reasons.join(' · '))}">heat ${arrow} ${hr.dir}</b>`);
        }
        return `<div class="tnp-player-trend">${parts.join(' · ')}</div>`;
      })();
      return `
        <div class="tnp-player-row${pulse}" style="${style}" data-player-id="${escapeHtml(player.id)}">
          <div class="tnp-player-badge" style="color:${typeDef.color}; ${ring}">${m && m.tier !== 'unknown' ? typeDef.short : '?'}</div>
          <div class="tnp-player-name" data-player-id="${escapeHtml(player.id)}">${escapeHtml(player.name)}</div>
          <div class="tnp-player-stats">${stats}</div>
          ${tierTag}
          ${trend}
        </div>
      `;
    }).join(''));
  };

  const renderMirrorPanel = () => {
    if (!uiElement) return;
    const headEl = document.getElementById('tnp-mirror-head');
    const gridEl = document.getElementById('tnp-mirror-grid');
    const ledgerEl = document.getElementById('tnp-mirror-ledger');
    const leaksEl = document.getElementById('tnp-mirror-leaks');
    if (!headEl || !gridEl || !ledgerEl || !leaksEl) return;

    const m = getHeroMetrics(heroStats);
    const typeDef = PLAYER_TYPES[m.archetype] ?? PLAYER_TYPES.UNKNOWN;
    const fmtNet = (v) => (v < 0 ? '-$' : '+$') + Math.abs(Math.round(v)).toLocaleString();

    setHTML(headEl, `
      <div class="tnp-player-row">
        <div class="tnp-player-badge" style="background:${typeDef.color}" title="${escapeHtml(typeDef.label)}: the Foes classifier aimed at your own logged actions">${m.hands >= 10 ? typeDef.short : '?'}</div>
        <div class="tnp-player-name">You</div>
        <div class="tnp-player-stats" title="Read confidence grows with hands observed">conf ${m.confidence}%</div>
      </div>
      <div class="tnp-row" style="margin-top: 2px;">
        <span class="tnp-tier-tag tnp-tier-${m.tier}">${escapeHtml(m.tierLabel)}</span>
        <span class="tnp-freshness">Your table image as the log saw it · ${m.hands} hands</span>
      </div>
    `);

    const box = (label, val, title = '') =>
      `<div class="tnp-stat-box" ${title ? `title="${escapeHtml(title)}"` : ''}><div class="tnp-stat-label">${label}</div><div class="tnp-stat-val">${val}</div></div>`;
    const afHero = m.af;
    setHTML(gridEl, [
      box('VPIP', m.hands > 0 ? `${m.vpip}%` : 'n/a', 'Hands you entered voluntarily, over hands with logged action. 20-30% is healthy.'),
      box('PFR', m.hands > 0 ? `${m.pfr}%` : 'n/a', 'Hands you raised first in'),
      box('Limp', m.hands > 0 ? `${m.limp}%` : 'n/a', 'Hands you entered by calling an unraised pot'),
      box('AFq', (heroStats.postTotal ?? 0) >= MIN_AFQ_POSTFLOP_ACTIONS ? `${m.afq}%` : 'n/a',
        `Bets and raises over all your postflop actions (shown after ${MIN_AFQ_POSTFLOP_ACTIONS} postflop actions; ${heroStats.postTotal ?? 0} so far)`),
      box('AF', afLabelOf(afHero), `Classic aggression factor: your postflop (bets+raises)/calls · ${afHero.sample} actions counted (quoted after ${MIN_AF_ACTIONS})`),
      box('WTSD', heroStats.sawFlop > 0 ? `${m.wtsd}%` : 'n/a', 'Showdowns you reached, over flops you saw'),
      box('WSD', heroStats.wtsd > 0 ? `${m.wsd}%` : 'n/a', 'Showdowns you won, over showdowns you reached'),
      box('Open', heroStats.openOpp > 0 ? `${m.open}%` : 'n/a', 'First-in raises over first-in chances.')
    ].join(''));

    const view = heroLedgerView(heroStats);
    if (view.length === 0) {
      setHTML(ledgerEl, `<div style="color:var(--tnp-muted); font-size:var(--tnp-fz-xs); text-align:center; padding:10px;">No showdowns yet; the ledger fills as hands complete.</div>`);
    } else {
      setHTML(ledgerEl, view.map(r => `
        <div class="tnp-ledger-row" title="${escapeHtml(madeHandLabel(r.t))}: ${r.n} showdown${r.n === 1 ? '' : 's'} in the ring · avg ${fmtNet(r.avg)} per hand">
          <span class="tnp-ledger-name">${escapeHtml(madeHandLabel(r.t))}</span>
          <span class="tnp-ledger-count">${r.n} hand${r.n === 1 ? '' : 's'} · avg ${fmtNet(r.avg)}</span>
          <span class="tnp-ledger-net" style="color:${r.net < 0 ? 'var(--tnp-danger)' : 'var(--tnp-success)'}">${fmtNet(r.net)}</span>
        </div>
      `).join(''));
    }

    const tips = getSelfLeaks(m, heroStats);
    if (tips.length === 0) {
      setHTML(leaksEl, `<div class="tnp-exploit-hint">${m.hands < 40
        ? `Not enough hands yet (leak notes start at 40, ledger buckets at 5-10 showdowns; ${m.hands} so far).`
        : 'No leak crosses its sample threshold in this window.'}</div>`);
    } else {
      setHTML(leaksEl, tips.map(t => `<div class="tnp-exploit-hint">${escapeHtml(t)}</div>`).join(''));
    }
  };

  const renderSessionPanel = () => {
    const handsEl = document.getElementById('tnp-session-hands');
    const vpipEl = document.getElementById('tnp-session-vpip');
    const netEl = document.getElementById('tnp-session-net');
    const winEl = document.getElementById('tnp-session-win');
    const lossEl = document.getElementById('tnp-session-loss');
    const durEl = document.getElementById('tnp-session-duration');
    const playersEl = document.getElementById('tnp-session-players');

    setSessionValue(handsEl, session.handsPlayed, true);
    const vpipKnown = session.handsVPIPKnown > 0;
    setSessionValue(vpipEl, vpipKnown ? `${Math.round(session.handsVPIP / session.handsVPIPKnown * 100)}%` : '', vpipKnown);
    if (netEl) {
      const netKnown = !!session.stackDeltaKnown;
      setSessionValue(netEl, (session.netChips >= 0 ? '+$' : '-$') + Math.abs(session.netChips).toLocaleString(), netKnown);
      const netCls = `tnp-stat-val ${netKnown && session.netChips >= 0 ? 'tnp-success' : netKnown ? 'tnp-danger' : 'tnp-session-unknown'}`;
      if (netEl.className !== netCls) netEl.className = netCls;
    }
    const deltaKnown = !!session.stackDeltaKnown;
    setSessionValue(winEl, '+$' + Math.abs(session.biggestWin).toLocaleString(), deltaKnown);
    setSessionValue(lossEl, '-$' + Math.abs(session.biggestLoss).toLocaleString(), deltaKnown);
    const rebuysEl = document.getElementById('tnp-session-rebuys');
    if (rebuysEl) setSessionValue(rebuysEl, String(session.rebuys | 0), !!session.stackKnown);
    const pipeEl = document.getElementById('tnp-pipeline-stats');
    if (pipeEl) {
      const p = pipelineStats;
      const lastHand = p.lastHandAt ? ` · last ${Math.max(0, Math.round((Date.now() - p.lastHandAt) / 60000))}m ago` : '';
      setText(pipeEl, `${p.awardWindows} hands seen · ${p.actionsParsed} actions · ${p.actionsAttributed} matched`
        + (p.nameMisses ? ` · ${p.nameMisses} unmatched` : '') + lastHand);
      pipeEl.title = 'Completed hands seen in the log, actions parsed from those hands, and how many matched a seat. '
        + 'Many unmatched names usually mean a seat name is not rendering; zero hands seen means the log feed is not being read.';
    }
    const mins = Math.floor((Date.now() - session.startTime) / 60000);
    if (durEl) {
      const hrs = Math.floor(mins / 60);
      setSessionValue(durEl, hrs > 0 ? `${hrs}h ${mins % 60}m` : `${mins}m`, true);
    }
    setText(playersEl, Object.keys(profiles).length);

    const tableEl = document.getElementById('tnp-session-table');
    if (tableEl) {

      const ident = resolveTableIdentity();
      const known = ident && ident.confidence === 'confirmed';
      setText(tableEl, known ? `${ident.table.name} · ${ident.table.seats} seats` : (ident ? `${ident.table.name}? (unconfirmed)` : 'n/a'));
      tableEl.title = known
        ? `Confirmed via ${ident.sourceLabel}. Buy-in bracket ${fmtDollarsFromCents(ident.table.minBuy)}–${fmtDollarsFromCents(ident.table.maxBuy)}.`
        : (ident ? `Not locked yet: ${ident.basisLine}. Open the in-game game list once while seated.` : 'No stakes read yet; the table card fills in once the blinds show.');
    }

    const wonEl = document.getElementById('tnp-session-won');
    if (wonEl) {
      const outcomeKnown = session.outcomeKnownHands > 0;
      const rate = outcomeKnown ? ` (${Math.round(session.handsWon / session.outcomeKnownHands * 100)}%)` : '';
      setSessionValue(wonEl, `${session.handsWon}${rate}`, outcomeKnown);
    }
    const perHourEl = document.getElementById('tnp-session-perhour');
    if (perHourEl) {
      const perHourKnown = session.stackDeltaKnown && mins >= 5;
      setSessionValue(perHourEl, perHourKnown
        ? `${session.netChips < 0 ? '-' : ''}$${Math.abs(Math.round(session.netChips / (mins / 60))).toLocaleString()}`
        : '', perHourKnown);
    }

    const bb100El = document.getElementById('tnp-session-bb100');
    if (bb100El) {
      let bbDollars = 0;
      try {
        const identBb = resolveTableIdentity();
        if (identBb && identBb.table && identBb.table.bb) bbDollars = identBb.table.bb / 100;
      } catch { }
      if (!(bbDollars > 0) && tableStakesRead && tableStakesRead.bb > 0) bbDollars = tableStakesRead.bb / 100;
      const knownBb100 = session.stackDeltaKnown && session.handsPlayed >= 5 && bbDollars > 0;
      setSessionValue(bb100El, knownBb100
        ? `${session.netChips < 0 ? '-' : '+'}${Math.abs(Math.round(session.netChips / bbDollars / (session.handsPlayed / 100))).toLocaleString()}`
        : '', knownBb100);
      bb100El.title = knownBb100
        ? `Net $${Math.round(session.netChips).toLocaleString()} over ${session.handsPlayed} hands at $${bbDollars.toLocaleString()} per big blind.`
        : 'Needs a readable stack, at least 5 hands, and the table stakes.';
    }

    const scoreEl = document.getElementById('tnp-score-session');
    if (scoreEl) {
      const known = session.outcomeKnownHands > 0 || lifetime.handsWon > 0;
      setSessionValue(scoreEl, known
        ? `${Math.round(session.scoreEst).toLocaleString()} · lifetime ${Math.round(lifetime.scoreEst).toLocaleString()}`
        : '', known);
      scoreEl.title = `Estimated Torn poker score: ${Math.round(session.scoreEst).toLocaleString()} this session, ${Math.round(lifetime.scoreEst).toLocaleString()} lifetime · showdown wins ${session.showdownWins}/${lifetime.showdownWins} (session/lifetime). Torn's exact formula is not public; only won hands score.`;
    }

    const recHintEl = document.getElementById('tnp-session-recording-hint');
    if (recHintEl) {

      const logDegraded = !!(domHealth.log && domHealth.log.warned);
      const stackDegraded = !!(domHealth.stack && domHealth.stack.warned);
      const showHint = session.handsPlayed === 0 && (logDegraded || stackDegraded);
      if (recHintEl.classList.contains('tnp-hidden') === !showHint) {
        recHintEl.classList.toggle('tnp-hidden', !showHint);
      }
      if (showHint) {
        setText(recHintEl, logDegraded
          ? 'Hand recording is waiting on a readable action log.'
          : 'Chip tracking is waiting on a readable stack; net figures fill in once it reads.');
      }
    }

    const tiltEl = document.getElementById('tnp-tilt-warning');
    if (tiltEl) {
      const tiltMsg = tiltCheck(session.recentDeltas, session.startStack);
      if (tiltMsg) {
        setText(tiltEl, tiltMsg);
        if (tiltEl.classList.contains('tnp-hidden')) tiltEl.classList.remove('tnp-hidden');
      } else if (!tiltEl.classList.contains('tnp-hidden')) {
        tiltEl.classList.add('tnp-hidden');
      }
    }
  };

  const fmtDollarsFromCents = (cents) => {
    const d = cents / 100;
    return '$' + (Number.isInteger(d) ? d.toLocaleString() : d.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
  };
  const renderTableCard = () => {
    const cardEl = document.getElementById('tnp-table-card');
    if (!cardEl) return;
    const ident = resolveTableIdentity();
    if (!ident || !ident.table) {
      cardEl.classList.add('tnp-hidden');
      return;
    }
    const t = ident.table;
    if (t.bb == null || t.sb == null) {
      parts.push(`<b>${escapeHtml(t.name)}</b> · stakes not in the local catalog · identified by ${escapeHtml(ident.sourceLabel || 'table art')}`);
      parts.push('This table is newer than the catalog data; its blinds, buy-in and seat count were not verifiable, so bracket advice is off for it.');
      if (t.anomaly) parts.push(`Note: ${escapeHtml(t.anomaly)}`);
      cardEl.innerHTML = parts.map((p) => `<div>${p}</div>`).join('');
      cardEl.classList.remove('tnp-hidden');
      return;
    }
    const bbDollars = t.bb / 100;
    const stack = session.currentStack || session.startStack || 0;
    const stackBB = bbDollars > 0 && stack > 0 ? Math.round(stack / bbDollars) : null;
    const buyIns = bankroll.total > 0 ? Math.floor((bankroll.total * 100) / Math.max(1, t.maxBuy)) : null;
    const parts = [];

    if (ident.confidence === 'confirmed') {
      parts.push(`<div class="tnp-idpill"><span class="tnp-pill tnp-pill-ok">Confirmed · ${escapeHtml(ident.sourceLabel || 'game list')}</span></div>`);
    } else if (ident.confidence === 'likely') {
      parts.push('<div class="tnp-idpill"><span class="tnp-pill tnp-pill-dim">Likely · only table at these stakes</span></div>');
    } else {
      parts.push(`<div class="tnp-idpill"><span class="tnp-pill tnp-pill-warn" title="${escapeHtml(ident.basisLine || '')}">Unconfirmed${ident.table.alternates?.length ? ` · ${ident.table.alternates.length + 1} candidates` : ''}</span></div>`);
    }

    if (ident.confidence === 'confirmed') {
      const seatedNow = getAllSeats().length;
      parts.push(`<b>${escapeHtml(t.name)}</b> · ${fmtDollarsFromCents(t.sb)}/${fmtDollarsFromCents(t.bb)} · ${t.seats} seats${seatedNow > 0 ? ` (${seatedNow} seated)` : ''} · ${t.timer}s`);
    } else if (ident.confidence === 'likely') {
      parts.push(`<b>${escapeHtml(t.name)}</b> · ${fmtDollarsFromCents(t.sb)}/${fmtDollarsFromCents(t.bb)} · ${t.seats} seats · ${t.timer}s`);
    } else {
      const rivals = t.alternates?.length ? ` (or ${t.alternates.map(escapeHtml).join(' / ')})` : '';
      parts.push(`<b>${escapeHtml(t.name)}</b>${rivals} · ${fmtDollarsFromCents(t.sb)}/${fmtDollarsFromCents(t.bb)} · <b>unconfirmed</b>`);
      parts.push('Open the in-game game list once while seated: your row is marked and locks the name.');
    }
    parts.push(`Buy-in ${fmtDollarsFromCents(t.minBuy)}\u2013${fmtDollarsFromCents(t.maxBuy)} · stack ${stackBB !== null ? `${stackBB} BB` : 'n/a'}`
      + (buyIns !== null ? ` · bankroll covers ${buyIns} max buy-in${buyIns < 25 ? 's (25+ is comfortable)' : 's'}` : ''));
    if (t.anomaly) parts.push(`Note: this table's wiki row is self-inconsistent (${t.anomaly})`);
    cardEl.innerHTML = parts.map((p) => `<div>${p}</div>`).join('');
    cardEl.classList.remove('tnp-hidden');
  };

  const renderBankrollPanel = () => {
    const consEl = document.getElementById('tnp-bk-cons');
    if (!consEl) return;
    const stdEl = document.getElementById('tnp-bk-std');
    const aggrEl = document.getElementById('tnp-bk-aggr');
    const warnEl = document.getElementById('tnp-bankroll-warning');
    const statusEl = document.getElementById('tnp-bankroll-status');
    const historyEl = document.getElementById('tnp-bankroll-history');

    const buyIn = session.startStack || 0;
    const advice = bankrollAdvice(bankroll.total, buyIn, session.netChips, { stopLossBuyIns: bankroll.stopLossBuyIns || 2 });

    const fmt = (v) => v > 0 ? '$' + v.toLocaleString() : '-';
    setText(consEl, fmt(advice.maxBuyInConservative));
    setText(stdEl, fmt(advice.maxBuyInStandard));
    setText(aggrEl, fmt(advice.maxBuyInAggressive));

    if (warnEl) {
      let warning = null;
      if (advice.stopLossHit) {
        warning = `Stop-loss hit: down $${Math.abs(session.netChips).toLocaleString()} `
          + `(limit ${bankroll.stopLossBuyIns || 2} buy-ins). End the session and protect the bankroll.`;
      } else if (bankroll.sessionGoal > 0 && session.netChips >= bankroll.sessionGoal) {
        warning = `Session goal reached: up $${session.netChips.toLocaleString()}. Consider banking the win.`;
      } else if (advice.stakeWarning) {
        warning = advice.stakeWarning;
      }
      if (warning) {
        setText(warnEl, warning);
        if (warnEl.classList.contains('tnp-hidden')) warnEl.classList.remove('tnp-hidden');
      } else if (!warnEl.classList.contains('tnp-hidden')) {
        warnEl.classList.add('tnp-hidden');
      }
    }

    if (statusEl) {
      const parts = [];
      if (bankroll.total > 0) parts.push(`Bankroll: $${bankroll.total.toLocaleString()}`);
      if (buyIn > 0) parts.push(`Table buy-in: $${buyIn.toLocaleString()}`);
      if (advice.stopLossAmount > 0) parts.push(`Stop-loss at -$${advice.stopLossAmount.toLocaleString()}`);
      setText(statusEl, parts.length ? parts.join(' · ') : 'Enter your poker bankroll above to get stake-sizing guidance.');
    }

    renderTableCard();

    const riskEl = document.getElementById('tnp-bankroll-risk');
    if (riskEl) {
      const risk = bankrollRiskRead(session.recentDeltas, bankroll.total);
      if (!risk) {
        setText(riskEl, `Variance: needs ${30 - (session.recentDeltas || []).filter(x => x !== 0).length} more settled hands and a bankroll figure to estimate risk of ruin.`);
      } else {
        const mu = `${risk.mean >= 0 ? '+' : '-'}$${Math.abs(Math.round(risk.mean)).toLocaleString()}/hand`;
        const sig = `$${Math.round(risk.sigma).toLocaleString()}`;
        const rorPct = risk.ror >= 1 ? '100%' : `${(risk.ror * 100).toFixed(1)}%`;
        setText(riskEl, `Variance: ${mu} · σ ${sig} · risk of ruin ≈ ${rorPct} at your $${bankroll.total.toLocaleString()} bankroll${risk.note ? ` · ${risk.note}` : ''} · estimate from ${risk.n} settled hands, not a guarantee`);
      }
      riskEl.title = 'Risk of ruin uses the exponential approximation RoR = exp(-2·μ·B/σ²) on your observed per-hand results. Small samples mislead; treat it as a smoke alarm, not a forecast.';
    }

    if (historyEl) {
      const recent = (bankroll.history || []).slice(-8).reverse();

      const histDate = (h) => escapeHtml(h.date
        || (Number.isFinite(h.ts) ? new Date(h.ts).toISOString().slice(0, 16).replace('T', ' ') : 'n/a'));
      setHTML(historyEl, recent.length
        ? recent.map(h => {
          const sign = h.net >= 0 ? '+' : '-';
          const color = h.net >= 0 ? 'var(--tnp-success)' : 'var(--tnp-danger)';
          return `<div class="tnp-history-row" title="${escapeHtml(h.table ? `Table: ${h.table}` : 'Table not recorded (pre-3.0.1 session)')}"><span>${histDate(h)}</span><span class="tnp-history-net" style="color:${color}">${sign}$${Math.abs(h.net).toLocaleString()}</span><span class="tnp-history-tail">${h.hands}h/${h.won ?? 0}w</span><span class="tnp-history-tail">${h.mins}m</span></div>`;
        }).join('')
        : '<div>No finished sessions yet. Use "End &amp; Reset Session" to log one.</div>');
    }
  };

  const sparklineSvg = (points, { height = 34 } = {}) => {
    const n = points.length;
    if (n < 2) return '';
    const W = 240, H = height, pad = 5;
    let min = Math.min(...points), max = Math.max(...points);
    if (min === max) { min -= 1; max += 1; }
    const x = (i) => (i * W) / (n - 1);
    const y = (v) => pad + ((max - v) / (max - min)) * (H - 2 * pad);
    const last = points[n - 1];
    const stroke = last >= 0 ? 'var(--tnp-success)' : 'var(--tnp-danger)';
    const d = points.map((v, i) => `${i ? 'L' : 'M'}${x(i).toFixed(2)} ${y(v).toFixed(2)}`).join(' ');
    const zero = (min <= 0 && max >= 0)
      ? `<line x1="0" x2="${W}" y1="${y(0).toFixed(2)}" y2="${y(0).toFixed(2)}" stroke="var(--tnp-border-hi)" stroke-dasharray="4 4" vector-effect="non-scaling-stroke"/>`
      : '';
    const tick = `<line x1="${x(n - 1).toFixed(2)}" x2="${x(n - 1).toFixed(2)}" y1="${(y(last) - 5).toFixed(2)}" y2="${(y(last) + 5).toFixed(2)}" stroke="${stroke}" stroke-width="3" vector-effect="non-scaling-stroke"/>`;
    return `<svg class="tnp-spark-svg" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true">`
      + zero
      + `<path d="${d}" fill="none" stroke="${stroke}" stroke-width="1.5" vector-effect="non-scaling-stroke"/>`
      + tick
      + '</svg>';
  };

  const sparkHead = (cap, cls, val) =>
    `<div class="tnp-spark-head"><span class="tnp-spark-cap">${cap}</span><span class="tnp-spark-now ${cls}">${val}</span></div>`;
  const sparkMoney = (v) => `${v < 0 ? '-' : '+'}$${Math.abs(v).toLocaleString()}`;

  const barSparkSvg = (values) => {
    const n = values.length;
    if (!n) return '';
    const W = 240, H = 40, pad = 3;
    const maxAbs = Math.max(1, ...values.map(v => Math.abs(v)));
    const zero = H / 2;
    const bw = Math.max(2, (W - pad * 2) / n - 2);
    let bars = '';
    values.forEach((v, i) => {
      const h = Math.max(1, Math.round((Math.abs(v) / maxAbs) * (H / 2 - pad)));
      const x = pad + i * ((W - pad * 2) / n);
      const y = v >= 0 ? zero - h : zero;
      bars += `<rect x="${x.toFixed(1)}" y="${y}" width="${bw.toFixed(1)}" height="${h}" fill="${v >= 0 ? 'var(--tnp-success)' : 'var(--tnp-danger)'}" opacity="0.85"/>`;
    });
    return `<svg class="tnp-spark-svg" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true"><line x1="0" x2="${W}" y1="${zero}" y2="${zero}" stroke="var(--tnp-border-hi)" stroke-dasharray="4 4" vector-effect="non-scaling-stroke"/>${bars}</svg>`;
  };

  let _storageMetersRenderedAt = 0;


  const chartInstances = {};
  const CHART_COLORS = {
    grid: 'rgba(43, 33, 38, 0.9)',
    tick: '#A899A0',
    up: '#3ECF7A',
    down: '#FF5A5A'
  };
  const moneyTick = (v) => {
    const n = Number(v) || 0;
    const abs = Math.abs(n);
    if (abs >= 1e9) return `${n < 0 ? '-' : ''}$${(abs / 1e9).toFixed(1)}b`;
    if (abs >= 1e6) return `${n < 0 ? '-' : ''}$${(abs / 1e6).toFixed(1)}m`;
    if (abs >= 1e3) return `${n < 0 ? '-' : ''}$${(abs / 1e3).toFixed(0)}k`;
    return `${n < 0 ? '-' : ''}$${abs.toFixed(0)}`;
  };

      const renderSessionChart = () => {
    const host = document.getElementById('tnp-session-chart');
    if (!host) return;
    const series = Array.isArray(session.netSeries) ? session.netSeries : [];
    if (series.length < 2) {
      host.innerHTML = '<div class="tnp-spark-note">The performance chart appears after a few settled hands (needs readable stacks).</div>';
      return;
    }
    let run = 0;
    const pts = series.map(p => (run += Number(p.net) || 0, run));
    const last = pts[pts.length - 1];
    setHTML(host, sparkHead(`Session · ${series.length} settled hands`, last > 0 ? 'tnp-up' : last < 0 ? 'tnp-down' : 'tnp-flat', sparkMoney(last))
      + sparklineSvg(pts)
      + '<div class="tnp-spark-note">Cumulative net per settled hand (local SVG, no external chart library).</div>');
  };

    const renderBankrollChart = () => {
    const host = document.getElementById('tnp-bankroll-chart');
    if (!host) return;
    const hist = bankroll.history || [];
    if (hist.length < 2) {
      host.innerHTML = '<div class="tnp-spark-note">The bankroll chart appears after two logged sessions (End &amp; Reset Session logs one).</div>';
      return;
    }
    const pts = hist.map(h => Number(h.net) || 0);
    const last = pts[pts.length - 1];
    setHTML(host, sparkHead(`Bankroll · ${hist.length} sessions`, last > 0 ? 'tnp-up' : last < 0 ? 'tnp-down' : 'tnp-flat', sparkMoney(last))
      + barSparkSvg(pts)
      + '<div class="tnp-spark-note">Net per logged session (local SVG bars, no external chart library).</div>');
  };

  const renderStorageMeters = () => {
    const dash = document.getElementById('tnp-storage-dashboard');
    if (!dash) return;
    const now = Date.now();
    if (now - _storageMetersRenderedAt < 5000) return;
    _storageMetersRenderedAt = now;
    let box = document.getElementById('tnp-storage-meters');
    if (!box) {
      box = document.createElement('div');
      box.id = 'tnp-storage-meters';
      box.className = 'tnp-meters';
      dash.appendChild(box);
    }
    refreshStorageBytes();
    const report = storageBudgetReport(storageState.bytes);
    const kb = (n) => `${(n / 1024).toFixed(1)}`;
    const poolBytes = originPoolBytes();
    const oursPct = poolBytes > 0 ? Math.round(report.total / poolBytes * 100) : 0;
    const row = (label, used, budget, pct, state, extra = '') => {
      const stateCls = state === 'dead' ? 'tnp-dead' : state === 'over' ? 'tnp-over' : '';
      const width = Math.max(2, Math.min(100, Math.round(pct)));
      return `<div class="tnp-meter-row ${stateCls}${extra ? ' ' + extra : ''}">`
        + `<span class="tnp-meter-label">${label}</span>`
        + `<span class="tnp-meter-track"><span class="tnp-meter-fill" style="width:${width}%"></span></span>`
        + `<span class="tnp-meter-val">${kb(used)}/${kb(budget)} KB</span></div>`;
    };
    const rows = report.rows.map((r) => row(r.category, r.used, r.budget, r.pct,
      storageState.degraded.has(r.category) ? 'dead' : (r.over ? 'over' : ''))).join('');
    const deadAny = storageState.degraded.size > 0;
    const total = row('total', report.total, report.totalBudget,
      report.totalBudget ? (report.total / report.totalBudget * 100) : 0,
      deadAny ? 'dead' : (report.totalOver ? 'over' : ''), 'tnp-meter-total');
    const poolLine = `<div class="tnp-meter-pool">All scripts on torn.com use ${(poolBytes / 1024).toFixed(0)} KB of this browser's shared pool; this HUD holds ${kb(report.total)} KB (${oursPct}%).</div>`;
    setHTML(box, rows + total + poolLine);
  };

  const toastHost = () => {
    const dossier = document.getElementById('tnp-dossier');
    if (!dossier) return null;
    let host = document.getElementById('tnp-toasts');
    if (!host) {
      host = document.createElement('div');
      host.id = 'tnp-toasts';
      host.className = 'tnp-toasts';
      host.setAttribute('role', 'status');
      host.setAttribute('aria-live', 'polite');
      dossier.appendChild(host);
    }
    return host;
  };

  const tnpToast = (kind, text, ms = 6000) => {
    const host = toastHost();
    if (!host) return;
    while (host.children.length >= 3) host.firstElementChild.remove();
    const el = document.createElement('div');
    el.className = `tnp-toast tnp-toast-${kind}`;
    el.innerHTML = `<span class="tnp-toast-dot" aria-hidden="true"></span><span>${escapeHtml(text)}</span><button type="button" class="tnp-toast-x" aria-label="Dismiss">×</button>`;
    let timer = 0;
    const kill = () => { clearTimeout(timer); el.remove(); };
    const x = el.querySelector('.tnp-toast-x');
    if (x) x.addEventListener('click', kill);
    host.appendChild(el);
    timer = setTimeout(() => {
      el.classList.add('tnp-toast-out');
      setTimeout(() => el.remove(), 220);
    }, ms);
  };

  const buildDebugState = () => {
    let ident = null, parser = [], diag = {};
    try { ident = tableIdentityDebug(); } catch (e) { ident = { error: String(e && e.message || e) }; }
    try { parser = buildParserReport(); } catch (e) { parser = [{ error: String(e && e.message || e) }]; }
    try { diag = TNP6.diagnostics(); } catch (e) { diag = { error: String(e && e.message || e) }; }
    return {
      kind: 'tnp-debug-state', version: SCRIPT_VERSION, at: new Date().toISOString(),
      url: (typeof location !== 'undefined' ? location.href : null),
      gameState: {
        street: gameState.street, holeCards: gameState.holeCards, boardCards: gameState.boardCards,
        activeOpponents: gameState.activeOpponents, pot: gameState.pot, toCall: gameState.toCall,
        toCallUnknown: gameState.toCallUnknown, potStale: gameState.potStale,
        heroStack: gameState.heroStack, effStack: gameState.effStack, position: gameState.position,
        raiseLevel: gameState.raiseLevel, equity: gameState.equity, equityMethod: gameState.equityMethod,
        mcSamples: gameState.mcSamples, readIssues: gameState.readIssues, occupiedSeats: gameState.occupiedSeats
      },
      tableIdentity: ident,
      parserReport: parser,
      provenance: provenanceReport(),
      stateConfidence: provenanceSummary(),
      domHealth: JSON.parse(JSON.stringify(domHealth)),
      pipelineStats: { ...pipelineStats },
      storage: { backend: storage.backendName(), budget: storageBudgetReport(refreshStorageBytes()), degraded: Array.from(storageState.degraded) },
      v6: diag,
      logBuffer: (logCapture.buffer || []).slice(-40),
      heal: { ...healTelemetry, features: Object.keys(healStore.features || {}) }
    };
  };
  const exportDebugState = () => {
    try {
      const blob = new Blob([JSON.stringify(buildDebugState(), null, 1)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `tnp-debug-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.json`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 4000);
      tnpToast('ok', 'Debug snapshot saved locally. It never leaves this device unless you send it yourself.');
    } catch (err) {
      window.alert(`Debug export failed: ${err && err.message ? err.message : err}`);
    }
  };

  const UPDATE_NOTICE_TEXT = '20.11.2026: compliance and architecture release. The script no longer installs any WebSocket or fetch hook: it is a read-only overlay that reads the rendered DOM of the actively viewed poker page only, pauses on hidden, unfocused or un-interacted windows (visibilitychange, focus, blur, trusted-interaction gate), and never issues network requests, external notifications or game actions. Every parser (hole cards, board, pot, call amount, stacks, opponents, position) now reads the visible DOM first and only. Table identity is a composite of stakes, seat count, speed and art: same-stakes tables with different seat counts are no longer aliased - an unresolved identity is reported instead. The prohibited Decision Evidence listing is gone everywhere, not moved: a compact state-integrity and calibration readout (freshness, agreement, sample support, provisional-vs-final simulation) replaces it in Diagnostics. The equity engine keeps the fixed 1,000,000-trial Monte Carlo in pooled Web Workers with cached, seeded, cancellable jobs and exact turn/river enumeration as a cross-check; opponent combo ranges are now built from DOM-observed actions and local profiles instead of intercepted transport frames. Both hole cards render from their own verified DOM elements; visual outs are compact chips with an honest no-asset fallback when genuine card artwork is unavailable. Hand records, opponent observations, replays and drills persist in IndexedDB with settings kept in localStorage. 19.11.2026 carried the same mandatory Monte Carlo, outs, opponent trends, decision debrief, replay + counterfactual EV, drills, session and bankroll tracking - all preserved.';
  const uiWatch = { primed: false, id: '', degr: 0, poolCheckedAt: 0, poolWarned: false };
  const uiRefreshTick = () => {

    if (settings.lastNoticedVersion !== SCRIPT_VERSION && document.getElementById('tnp-dossier')) {
      tnpToast('ok', `Poker Hold'em updated to ${SCRIPT_VERSION} · ${UPDATE_NOTICE_TEXT}`);
      settings.lastNoticedVersion = SCRIPT_VERSION;
      saveSettings();
    }

    const nowMs = Date.now();
    if (nowMs - uiWatch.poolCheckedAt >= ORIGIN_POOL_CHECK_MS) {
      uiWatch.poolCheckedAt = nowMs;
      try {
        const pool = originPoolBytes();
        refreshStorageBytes();
        const ours = Object.values(storageState.bytes).reduce((a, b) => a + b, 0);
        if (pool > ORIGIN_POOL_SOFT_LIMIT && ours > 150 * 1024) {
          const actions = emergencyShrink();
          if (!uiWatch.poolWarned) {
            uiWatch.poolWarned = true;
            tnpToast('warn', `Storage pool on torn.com is nearly full (${(pool / 1048576).toFixed(1)} MB). This HUD shrank its own data (${actions.join(', ') || 'nothing to trim'}) to stay out of the way.`);
          }
        } else if (pool <= ORIGIN_POOL_SOFT_LIMIT) {
          uiWatch.poolWarned = false;
        }
      } catch {  }
    }
    if (activeTab === 'session') {
      renderSessionChart();
    }
    if (activeTab === 'bankroll') {
      renderBankrollChart();
    }
    if (activeTab === 'settings') renderStorageMeters();

    const id = `${tableIdentityState.mode}|${tableIdentityState.name}`;
    const degr = storageState.degraded.size;
    if (uiWatch.primed) {
      if (id !== uiWatch.id) {
        if (tableIdentityState.mode === 'confirmed') {
          tnpToast('ok', `Table locked: ${tableIdentityState.name} · ${tableIdentityState.source}.`);
        } else if (uiWatch.id.startsWith('confirmed|')) {
          tnpToast('warn', 'Table identity dropped: stakes stopped matching. Re-deriving.');
        }
      }
      if (degr !== uiWatch.degr) {
        if (degr > 0) {
          tnpToast('warn', `Storage: ${degr} segment${degr > 1 ? 's' : ''} memory-only; tracking continues. Clear old HUD data in Setup if it persists.`);
        } else if (uiWatch.degr > 0) {
          tnpToast('ok', 'Storage writes recovered.');
        }
      }
    }
    uiWatch.id = id;
    uiWatch.degr = degr;
    uiWatch.primed = true;
  };

  let decisionHandStartedAt = 0;
  const resetForNewHand = () => {
    decisionHandStartedAt = Date.now();
    mcJobId++;
    try { archiveReplayHand(); } catch { }
    userFoldedThisHand = false;
    prevHeroTurn = false;
    gameState.userFolded = false;
    gameState.evalResult = null;
    gameState.equity = null;
    gameState.equityCI = null;
    gameState.equityProvisional = false;
    gameState.equityTrialsComplete = false;
    gameState.equityCached = false;
    gameState.exactEquity = null;
    gameState.exactSamples = 0;
    gameState.handTypeDist = null;
    gameState.mcSamples = 0;
    gameState.isCalculating = false;
    gameState.lastStateHash = '';
    gameState.lastCardHash = '';
    gameState.pot = 0;
    gameState.toCall = 0;
    gameState.toCallUnknown = false;
    gameState.readIssues = null;
    gameState.tableAdjust = null;
    gameState.preflopOpp = null;
    gameState.flopCtx = null;
    gameState.boardThreat = null;
    gameState.equityOuts = null;
    gameState.equityOutsKey = '';
    mySeat = null;
    clearCardHighlights();
  };

  let _lastComputeErrorAt = 0;
  let computeInFlight = false;
  let computeQueued = false;
  const computeState = async () => {
    if (computeInFlight) {
      computeQueued = true;
      return;
    }
    computeInFlight = true;
    const t0 = Date.now();
    try {
      await computeStateInner();
    } catch (err) {
      const now = Date.now();
      if (now - _lastComputeErrorAt > 60000) {
        _lastComputeErrorAt = now;
        twarn('[TNP] computeState error (HUD continues, will retry):', err);
      }
    } finally {
      lastComputeMs = Date.now() - t0;
      computeInFlight = false;
      if (computeQueued && runtimeActive) {
        computeQueued = false;
        setTimeout(() => computeState(), 0);
      } else {
        computeQueued = false;
      }
    }
  };

  const computeStateInner = async () => {

    if (isMinimized) {
      if (!isTableObservationAllowed()) return;
      try {
        const seatsMin = getAllSeats();
        processHandActions(parseActionLog(), seatsMin);
        syncSessionStack();
        try { observeTableIdentity(); } catch {  }
      } catch {  }
      return;
    }

    if (!isTableObservationAllowed()) {
      haltObservation();
      applyPauseState();
      setHudStatus('paused');
      return;
    }
    applyPauseState();


    const rawHole = parseHoleCards();
    provSet('holeCards', rawHole.length ? rawHole.join(' ') : null,
      rawHole.length === 2 ? 'card divs: role=img + aria-label / suit-rank class' : 'none found',
      rawHole.length === 2 ? 'known' : 'unavailable');
    const board = parseBoardCards();
    provSet('boardCards', board.length ? board.join(' ') : null,
      board.length ? 'community cards container: role=img + aria-label' : 'no board cards visible',
      board.length ? 'known' : 'unavailable');

    const hole = (rawHole.length === 2 && rawHole.some(c => board.includes(c))) ? [] : rawHole;

    const activeOpps = countActiveOpponents();
    provSet('activeOpponents', activeOpps,
      typeof activeOpps === 'number' && activeOpps > 0 ? 'seat scan: player-X wrappers, folded/sitting-out filters' : 'no active opponents seen',
      activeOpps > 0 ? 'known' : 'unavailable');
    const me = findOwnSeat();
    lastHeroSeatOk = !!me;
    const seats = getAllSeats();
    const actionLog = parseActionLog();
    provSet('actionLog', actionLog.length,
      logCapture.container ? `log feed (${logCapture.source || 'container matched'})` : 'log container not found yet',
      actionLog.length ? 'known' : 'unavailable');
    const actionBtnsForHealth = getActiveActionButtons();
    const pokerSurface = !!document.querySelector(
      '[class*="holdem"], [class*="pokerTable"], [class*="pokerGame"], ' +
      '[data-game="holdem"], [data-table="poker"], [class*="communityCards"], ' +
      '[class*="playerMeGateway___"], [class*="actionLog"], [data-zone="board"]'
    );
    const actionEvidence = actionLog.some(msg => POKER_MSG_RE.test(msg));
    const handExpected = pokerSurface && (
      hole.length === 2 || board.length > 0 || actionEvidence ||
      actionBtnsForHealth.hasFold || actionBtnsForHealth.hasCheck ||
      actionBtnsForHealth.hasCall || actionBtnsForHealth.hasRaise
    );
    const seatExpected = pokerSurface && (hole.length === 2 || board.length > 0 || actionEvidence || !!me || activeOpps > 0);
    reportDom('seats', seats.length > 0, seatExpected);
    reportDom('log', actionLog.length > 0, handExpected);

    processHandActions(actionLog, seats);

    try {
      let awardIdx = -1;
      for (let i = actionLog.length - 1; i >= 0; i--) {
        if (WINNER_LINE_RE.test(actionLog[i])) { awardIdx = i; break; }
      }
      if (awardIdx >= 0 && hole.length === 2) {
        const awardSig = handSignature(actionLog, awardIdx);
        if (awardSig && awardSig !== lastAwardSignature && !handTracker.processedMsgs.has(awardSig)) {
          let postAwardActions = 0;
          for (let i = awardIdx + 1; i < actionLog.length && postAwardActions < 2; i++) {
            const ev = parseActionMessage(actionLog[i]);
            if (ev && ev.action !== 'show' && ev.action !== 'muck' && ev.action !== 'win') postAwardActions++;
          }
          if (postAwardActions < 2) {
            lastAwardSignature = awardSig;
            sessionAwardSeenAt = Date.now();
            if (!recordedSessionHandKeys.has(hole.join(','))) {
              recordFallbackSessionHand(hole.join(','), actionLog, seats, null, true);
            }
          }
        }
      }
    } catch {  }

    try { commitSessionLedger(); } catch {  }

    syncSessionStack();
    renderSeatBadges();

    let street = 'Preflop';
    if (board.length === 3) street = 'Flop';
    if (board.length === 4) street = 'Turn';
    if (board.length === 5) street = 'River';

    if (hole.length !== 2) {
      mcJobId++;
      prevHeroTurn = false;
      gameState.lastCardHash = '';
      gameState.lastStateHash = '';
      gameState.holeCards = [];
      gameState.boardCards = board;
      gameState.activeOpponents = activeOpps;
      gameState.street = street;
      gameState.userFolded = false;
      gameState.evalResult = null;
      gameState.equity = null;
      gameState.equityCI = null;
      gameState.equityProvisional = false;
      gameState.handTypeDist = null;
      gameState.mcSamples = 0;
      gameState.isCalculating = false;
      gameState.boardTexture = analyzeBoardTexture(board);
      setHudStatus(pokerSurface ? 'ready' : 'paused');
      updateUI();
      return;
    }

    const holeKey = hole.join(',');

    if (holeKey !== lastHoleKey) lastGoodPot = 0;
    const previousHoleKey = lastHoleKey;
    const previousEvidence = previousHoleKey && handEvidence.key === previousHoleKey
      ? { ...handEvidence, messages: [...handEvidence.messages] }
      : null;
    captureHandEvidence(holeKey, actionLog, me);

    if (holeKey !== lastHoleKey) {

      try { commitSessionLedger(); } catch {  }

      if (previousHoleKey && !recordedSessionHandKeys.has(previousHoleKey)) {
        setTimeout(() => {
          if (recordedSessionHandKeys.has(previousHoleKey)) return;
          try {
            const liveMsgs = parseActionLog();
            let liveWinIdx = -1;
            for (let i = liveMsgs.length - 1; i >= 0; i--) {
              if (WINNER_LINE_RE.test(liveMsgs[i])) { liveWinIdx = i; break; }
            }
            const evMsgs = previousEvidence?.messages ?? [];
            let evWinIdx = -1;
            for (let i = evMsgs.length - 1; i >= 0; i--) {
              if (WINNER_LINE_RE.test(evMsgs[i])) { evWinIdx = i; break; }
            }
            const liveSig = liveWinIdx >= 0 ? handSignature(liveMsgs, liveWinIdx) : '';
            const evSig = evWinIdx >= 0 ? handSignature(evMsgs, evWinIdx) : '';
            if (liveSig && liveSig !== evSig) return;
          } catch {  }
          if (!recordedSessionHandKeys.has(previousHoleKey)) {
            recordFallbackSessionHand(previousHoleKey, actionLog, seats, previousEvidence, true);
          }
        }, 1200);
      }
      lastHoleKey = holeKey;
      resetForNewHand();

      syncSessionStack();
    }

    let userFolded = userFoldedThisHand;
    if (!userFolded && me) userFolded = hasHeroFolded(me);

    const pos = detectPosition();
    provSet('position', lastPositionKnown ? pos : `${pos} (unverified)`,
      lastPositionExact ? 'dealer button element or blind posts' : 'seat-order estimate',
      lastPositionExact ? 'known' : 'inferred');
    const raiseData = detectRaiseContext();
    const rLevel = raiseData.level;
    const potRead = readPot();
    provSet('pot', potRead > 0 ? potRead : (gameState.pot > 0 ? gameState.pot : null),
      potRead > 0 ? `pot read: ${lastPotSource}` : (lastPotSource === 'ambiguous' ? 'two pot reads disagree' : 'no pot element matched'),
      potRead > 0 ? 'known' : (lastPotSource === 'ambiguous' ? 'stale' : 'unavailable'));
    const potAmbiguous = potRead === 0 && lastPotSource === 'ambiguous';
    if (potRead > 0) {
      lastGoodPot = potRead;
      gameState.pot = potRead;
      gameState.potStale = false;
    } else if (lastGoodPot > 0 && !userFolded) {

      gameState.pot = lastGoodPot;
      gameState.potStale = true;
    } else {
      gameState.pot = 0;
      gameState.potStale = false;
    }
    const toCallRead = readToCall();
    provSet('toCall', toCallRead === null ? null : toCallRead,
      toCallRead === null ? 'call button text did not parse' : (toCallRead > 0 ? 'call button text' : 'no bet to call (check available or unopened)'),
      toCallRead === null ? 'unavailable' : 'known');
    gameState.toCallUnknown = toCallRead === null;
    gameState.toCall = toCallRead ?? 0;
    if (handExpected) reportDom('pot', gameState.pot > 0, board.length > 0 || actionEvidence || actionBtnsForHealth.hasCall || actionBtnsForHealth.hasRaise);

    try { observeTableIdentity(); } catch {  }
    provSet('table', tableIdentityState.mode === 'confirmed' ? tableIdentityState.name : null,
      tableIdentityState.mode === 'confirmed' ? tableIdentityState.source : 'stakes/seat heuristics only',
      tableIdentityState.mode === 'confirmed' ? 'known' : 'inferred',
      tableIdentityState.mode === 'confirmed' ? `${tableIdentityState.seats} seats · ws id ${tableIdentityState.wsTableId ?? 'n/a'}` : '');
    gameState.boardTexture = analyzeBoardTexture(board);
    gameState.boardThreat = (hole.length === 2 && board.length >= 3) ? boardThreatExtras(hole, board) : null;

    gameState.boardRiskRead = boardRisk(hole, board);
    gameState.oppAggressive = (board.length >= 3) && (() => {
      try {
        const hand = currentHandEvents(actionLog);
        const heroName = getHeroIdentity()?.name;
        const streetKey = street.toLowerCase();
        for (const [key, acts] of Object.entries(hand.byName)) {
          if (heroName && samePlayer(key, heroName)) continue;
          for (const a of acts) {
            if (a && a.street === streetKey && (a.action === 'bet' || a.action === 'raise')) return true;
          }
        }
      } catch {  }
      return false;
    })();
    const occupiedSeats = seats.filter(s => !isSeatEmpty(s)).length;
    gameState.occupiedSeats = occupiedSeats;

    if (occupiedSeats >= 2) {
      for (const seat of seats) {
        const idx = seatPositionIndex(seat);
        if (Number.isInteger(idx) && idx + 1 > (session.capacityHint | 0)) {
          session.capacityHint = idx + 1;
        }
      }
    }
    gameState.position = pos;
    gameState.positionLabel = positionLabel(pos, lastPositionExact);
    setText(document.getElementById('tnp-position-read'), gameState.positionLabel);
    setText(document.getElementById('tnp-compact-position'), lastPositionKnown ? pos : 'n/a');
    gameState.raiseLevel = rLevel;
    gameState.bbAmount = raiseData.bbAmount;
    gameState.raiseReliable = raiseData.reliable !== false;

    const rText = !gameState.raiseReliable ? 'Raise state unread'
      : (rLevel === 0 ? 'Unraised' : (rLevel === 1 ? 'Raised' : (rLevel === 2 ? '3-Bet' : '4-Bet+')));
    const posText = !lastPositionKnown ? 'Pos unread' : (pos === 'MP' && !lastPositionExact ? 'MP (est.)' : pos);
    const threatNotes = (gameState.boardThreat && gameState.boardThreat.notes && gameState.boardThreat.notes.length)
      ? ` | ${gameState.boardThreat.notes.join(' · ')}` : '';
    setText(document.getElementById('tnp-context'), `${posText} | ${rText}${threatNotes}`);

    const potOddsEl = document.getElementById('tnp-potodds');
    if (potOddsEl) {
      if (gameState.toCallUnknown) {
        setText(potOddsEl, 'Facing a bet · call size unreadable');
      } else if (gameState.toCall > 0 && gameState.pot > 0) {
        const reqEq = (gameState.toCall / (gameState.pot + gameState.toCall) * 100).toFixed(1);
        setText(potOddsEl, `Call $${gameState.toCall.toLocaleString()} into $${gameState.pot.toLocaleString()} · ${reqEq}%${gameState.potStale ? ' · pot read stale' : ''}`);
      } else {
        setText(potOddsEl, 'No bet to call');
      }
    }

    gameState.heroStack = readHeroStack(me);
    provSet('heroStack', gameState.heroStack > 0 ? gameState.heroStack : null,
      gameState.heroStack > 0 ? 'own-seat stack element or sr-only summary' : 'no plausible stack in own seat',
      gameState.heroStack > 0 ? 'known' : 'unavailable');
    const effStackRead = computeEffectiveStack(gameState.heroStack);
    provSet('effectiveStack', effStackRead.eff > 0 ? effStackRead.eff : null,
      effStackRead.source, effStackRead.eff > 0 ? 'known' : 'unavailable');
    gameState.effStack = effStackRead.eff;
    gameState.effStackSource = effStackRead.source;

    gameState.readIssues = null;
    const xCheck = crossCheckReads({
      pot: gameState.pot, toCall: gameState.toCallUnknown ? 0 : gameState.toCall,
      bb: raiseData.bbAmount || tableStakesRead.bb, board, hole, potAmbiguous
    });
    if (handExpected && xCheck.hard.length) {
      if (xCheck.hard.includes('call exceeds the pot')) {
        gameState.toCall = 0;
        gameState.toCallUnknown = true;
        gameState.potStale = true;
      }
      gameState.readIssues = xCheck.hard;
      setHudStatus('parser-issue', 'Unable to read poker data. Waiting for valid information (' + xCheck.hard.join('; ') + ').');
    } else {

      if (!gameState.toCallUnknown && gameState.toCall > 0 && gameState.heroStack > 0 && gameState.toCall > gameState.heroStack) {
        gameState.toCall = gameState.heroStack;
      }
      if (handExpected && xCheck.soft.length) gameState.potStale = true;

      if (hudStatus === 'parser-issue' && !domHealthBroken()) setHudStatus(gameState.holeCards.length === 2 ? 'live' : 'ready');
    }
    const mdfEl = document.getElementById('tnp-mdf');
    if (mdfEl) {
      const mdf = mdfVsBet(gameState.pot, gameState.toCall);
      setText(mdfEl, mdf !== null ? `${Math.round(mdf * 100)}% · vs 0-eq bluffs` : 'n/a');
    }
    const sprEl = document.getElementById('tnp-spr');
    if (sprEl) {
      const spr = street === 'Preflop' ? null : sprVsPot(gameState.effStack || gameState.heroStack, gameState.pot);
      setText(sprEl, spr !== null ? spr.toFixed(1) : 'n/a');
      sprEl.title = gameState.effStack > 0
        ? `Effective stack $${gameState.effStack.toLocaleString()} (${gameState.effStackSource}) ÷ pot $${Math.round(gameState.pot).toLocaleString()}. Under 3 committed, above 7 room to play.`
        : 'Effective stack unread; SPR needs the stacks in the hand.';
    }

    const outs = calculateOuts(hole, board);
    gameState.outs = outs;
    const outsEl = document.getElementById('tnp-outs');
    if (outsEl) {
      if (outs === null) {
        setText(outsEl, '-');
        outsEl.title = '';
      } else {

        const approx = ruleOfFourTwo(outs, street);
        setText(outsEl, approx !== null ? `${outs} outs · 4/2 ≈ ${approx}%` : `${outs} weighted outs`);
        const detail = analyzeOutsDetail(hole, board);
        const drawsHere = classifyDraws(hole, board);
        outsEl.title = (detail && detail.length
          ? `Discounted outs: ${detail.map(p => `${p.label} ${p.weight}`).join(' · ')}. Tainted board-pair and shared-flush cards are weighted down; `
          : 'Discounted outs; ')
          + (drawsHere.labels.length ? `Draws: ${drawsHere.labels.join(', ')}. ` : '')
          + 'the 4/2 figure is the rule-of-4/2 approximation, not the equity estimate';
      }
    }
        renderOutsChips(hole, board);
        if (board.length === 3 || board.length === 4) {
          const eqOutsKey = hole.join(',') + '|' + board.join(',');
          if (gameState.equityOutsKey !== eqOutsKey) {
            gameState.equityOutsKey = eqOutsKey;
            gameState.equityOuts = null;
            void outsWorkerRequest(hole, board).then((res) => {
              if (res && gameState.equityOutsKey === eqOutsKey) {
                gameState.equityOuts = res;
                try { renderOutsChips(hole, board); } catch { }
              }
            });
          }
        }

    let oppRanges = null;
    let rangeSig = '';
    gameState.tableAdjust = null;
    gameState.preflopOpp = null;
    gameState.flopCtx = null;
    if (settings.profileAdjusted && me) {
      const liveEvents = currentHandEvents(actionLog);
      const activeOppPlayers = [];
      const activeOppResolved = [];
      for (const seat of seats) {
        if (isOwnPlayerSeat(seat, me)) continue;
        if (!isOpponentActive(seat)) continue;
        const player = getPlayerName(seat);
        activeOppPlayers.push(player);
        if (player) activeOppResolved.push({ player, p: profiles[player.id] ?? null });
      }
      const live = buildLiveOppRanges(liveEvents, activeOppPlayers, opponentSeatPositions(), rLevel,
        !!(gameState.boardRiskRead && (gameState.boardRiskRead.suitThreat || gameState.boardRiskRead.straightThreat)));
      oppRanges = live.thresholds;
      gameState.liveRangeDisplay = live.display;
      rangeSig = live.display.map(d => `${d.pos ?? '?'}${Math.round(d.frac * 20)}`).join('.');
      gameState.tableAdjust = getTableAdjust();
      if (street === 'Preflop') {
        const heroName = getHeroIdentity()?.name ?? '';
        gameState.preflopOpp = buildPreflopOppSummary(actionLog, activeOppResolved, heroName, rLevel);
      } else {
        gameState.preflopOpp = null;
      }
      if (street === 'Flop' && activeOpps === 1) {
        const heroName = getHeroIdentity()?.name ?? '';
        const heroActs = heroName ? (liveEvents.byName[playerKey(heroName)] ?? []) : [];
        const heroRaisedPf = heroActs.some(a => a && a.street === 'preflop' && (a.action === 'raise' || a.action === 'bet'));
        const opp = headsUpOpponentProfile();
        if (heroRaisedPf && opp && (opp.foldToCbetOpp ?? 0) > 0) {
          gameState.flopCtx = {
            name: opp.name,
            cbetFold: Math.round((opp.foldToCbetCount ?? 0) / opp.foldToCbetOpp * 100),
            cbetFoldOpp: opp.foldToCbetOpp ?? 0
          };
        } else {
          gameState.flopCtx = null;
        }
      } else {
        gameState.flopCtx = null;
      }
    } else {
      gameState.liveRangeDisplay = null;
    }

    const heroTurn = isHeroTurn();
    provSet('heroTurn', heroTurn,
      heroTurnFromStatus() === true ? 'status line "Your turn..."' : (heroTurn ? 'action buttons visible' : 'status line / buttons'),
      heroTurn === null ? 'inferred' : 'known');
    const cardHash = `${holeKey}|${board.join(',')}|${activeOpps}|${userFolded}|${rangeSig}`;
    const fullHash = `${cardHash}|${gameState.toCall}|${gameState.pot}|${heroTurn}|${gameState.toCallUnknown}|${gameState.potStale}|${(gameState.readIssues ?? []).length}|${gameState.preflopOpp ? gameState.preflopOpp.name + gameState.preflopOpp.hands : ''}`;

    if (heroTurn && !prevHeroTurn && settings.turnFlash) {
      uiElement?.classList.remove('tnp-flash');
      void uiElement?.offsetWidth;
      uiElement?.classList.add('tnp-flash');
    }
    prevHeroTurn = heroTurn;

    if (fullHash === gameState.lastStateHash) return;
    if (cardHash === gameState.lastCardHash) {
      gameState.lastStateHash = fullHash;
      updateUI();
      return;
    }

    gameState.lastCardHash = cardHash;
    gameState.lastStateHash = fullHash;
    gameState.holeCards = hole;
    gameState.boardCards = board;
    gameState.activeOpponents = activeOpps;
    gameState.street = street;
    gameState.userFolded = userFolded;

    if (userFolded) {
      mcJobId++;
      prevHeroTurn = false;
      gameState.evalResult = null;
      gameState.equity = null;
      gameState.equityCI = null;
      gameState.equityProvisional = false;
      gameState.winSplit = null;
      gameState.isCalculating = false;
      setHudStatus('folded');
      clearCardHighlights();
      updateUI();
      return;
    }

    gameState.evalResult = evaluateHand(hole.concat(board));
    lastHeroEvalType = gameState.evalResult.type;

    if (settings.cardHighlight) {
      highlightContributingCards(hole, board, gameState.evalResult);
    }

    if (activeOpps > 0) {

      if (board.length === 0 && activeOpps === 1) {
        const cls = handClassKey(hole[0], hole[1]);
        const eqTable = PREFLOP_EQUITY_169[cls];
        if (typeof eqTable === 'number' && !oppRanges) {
          gameState.equity = eqTable;
          gameState.equityCI = { lower: Math.max(0, eqTable - 0.001), upper: Math.min(1, eqTable + 0.001) };
          gameState.equityMethod = 'preflop-table';
          gameState.equityProvisional = true;
          gameState.mcSamples = 0;
          gameState.mcWorkers = 0;
        }
      }
      gameState.isCalculating = true;
      setHudStatus('computing');
      updateUI();

      const currentJob = ++mcJobId;

      const onProgress = (snap) => {
        if (currentJob !== mcJobId || !snap || !(snap.samples >= 1)) return;
        gameState.equity = snap.equity;
        gameState.equityCI = snap.ci;
        gameState.handTypeDist = snap.typeDist || null;
        gameState.mcSamples = snap.samples || 0;
        gameState.winSplit = snap.winCount != null
          ? { win: snap.winCount, tie: snap.tieCount, loss: snap.lossCount }
          : null;
        gameState.mcWorkers = snap.workers || 0;
        gameState.equityMethod = 'monte-carlo';
        gameState.equityProvisional = true;
        updateUI();
      };

      let mcResult = null;
      const eqKey = equityCacheKey(hole, board, activeOpps, rangeSig);
      const cachedFinal = equityFinalCache.get(eqKey);
      if (cachedFinal) {
        mcResult = Object.assign({}, cachedFinal, { cached: true });
      } else {
        let combos = null;
        try {
          combos = TNP6.buildOppTablesDom(hole, board, { opponents: activeOpps, raiseLevel: rLevel, street });
        } catch (e) { combos = null; }
        mcResult = await runMandatedEquity(hole, board, activeOpps, currentJob, {
          onProgress, combos, ranges: combos ? null : oppRanges
        });
        if (mcResult && currentJob === mcJobId) equityCacheStore(eqKey, mcResult);
      }

      if (currentJob === mcJobId && mcResult !== null) {
        gameState.equity = mcResult.equity;
        gameState.equityCI = mcResult.ci;
        gameState.handTypeDist = mcResult.typeDist;
        gameState.mcSamples = mcResult.samples || 0;
        gameState.winSplit = mcResult.winCount != null
          ? { win: mcResult.winCount, tie: mcResult.tieCount, loss: mcResult.lossCount }
          : null;
        gameState.mcWorkers = mcResult.workers || 0;
        gameState.mcElapsedMs = mcResult.elapsedMs || 0;
        gameState.equityMethod = mcResult.method || 'monte-carlo';
        gameState.equityProvisional = false;
        gameState.equityTrialsComplete = mcResult.trialsComplete === true;
        gameState.equityMandatedTrials = mcResult.mandatedTrials || MC_MANDATE.totalTrials;
        gameState.equityCached = mcResult.cached === true;
        provSet('equity', mcResult.equity,
          mcResult.method + (mcResult.trialsComplete === true
            ? ' · 1,000,000 trials'
            : ` · ${(mcResult.samples || 0).toLocaleString()} of ${(mcResult.mandatedTrials || 1000000).toLocaleString()} trials (resource-limited)`),
          mcResult.trialsComplete === true ? 'known' : 'inferred');
        gameState.isCalculating = false;
        setHudStatus('live');
        updateUI();
        if (activeOpps === 1 && board.length >= 4 && !mcResult.rangeModel && currentJob === mcJobId) {
          try {
            const exact = await runExactEquity(hole, board, currentJob, null);
            if (exact && currentJob === mcJobId && exact.samples > 0) {
              gameState.exactEquity = exact.equity;
              gameState.exactSamples = exact.samples;
              updateUI();
            }
          } catch (e) { }
        }
      } else if (currentJob === mcJobId && mcResult === null) {
        gameState.isCalculating = false;
        setHudStatus('live');
        updateUI();
      }
    } else {

      gameState.equity = 1.0;
      gameState.equityCI = { lower: 1, upper: 1 };
      gameState.equityMethod = 'exact';
      gameState.equityProvisional = false;
      gameState.handTypeDist = null;
      gameState.winSplit = { win: 1, tie: 0, loss: 0 };
      gameState.mcSamples = 0;
      gameState.mcWorkers = 0;
      gameState.isCalculating = false;
      setHudStatus('live');
      updateUI();
    }

    try {
      replayRecord({
        hole, board, street,
        pot: gameState.pot, toCall: gameState.toCall, effStack: gameState.effStack || gameState.heroStack || 0,
        positionLabel: gameState.positionLabel || gameState.position || '?',
        activeOpponents: activeOpps,
        equity: gameState.equity, equityMethod: gameState.equityMethod,
        equityTrialsComplete: gameState.equityTrialsComplete,
        required: (gameState.toCall > 0 && gameState.pot > 0) ? gameState.toCall / (gameState.pot + gameState.toCall) : null,
        raiseLevel: gameState.raiseLevel || 0,
        heroTurn: isHeroTurn(),
        actions: actionLog.slice(-80),
        heroWon: (handEvidence && handEvidence.key === holeKey) ? handEvidence.heroWon : undefined,
        heroShowed: (handEvidence && handEvidence.key === holeKey) ? handEvidence.heroShowed : undefined
      });
    } catch { }
  };

  const decisionLog = [];
  const decisionStats = { good: 0, marginal: 0, expensive: 0 };
  const pct100 = (v) => `${Math.round((v ?? 0) * 100)}%`;
  const recordDecision = (action) => {
    try {
      const gs = gameState;
      const hasEq = typeof gs.equity === 'number' && gs.equity !== null;
      const required = (gs.toCall > 0 && gs.pot > 0) ? gs.toCall / (gs.pot + gs.toCall) : 0;
      const spr = gs.effStack > 0 && gs.pot > 0 ? gs.effStack / gs.pot : null;
      const fs = gs.activeOpponents > 0 ? 1 / (gs.activeOpponents + 1) : 0.5;
      const callEvNow = (hasEq && gs.toCall > 0) ? gs.equity * (gs.pot + gs.toCall) - gs.toCall : null;
      const entry = {
        ts: Date.now(), street: gs.street, action,
        pot: gs.pot, toCall: gs.toCall, equity: gs.equity, required,
        position: gs.positionLabel || gs.position || '?', opps: gs.activeOpponents, spr,
        effStack: gs.effStack || 0, callEv: callEvNow, profile: strategyProfile().label,
        equityMethod: gs.equityMethod || null,
        equityTrialsComplete: gs.equityTrialsComplete === true,
        mcSamples: gs.mcSamples || 0,
        potSource: provenance.pot?.source || '',
        toCallSource: provenance.toCall?.source || '',
        stateConfidence: provenanceSummary().confidence
      };
      let verdict = 'marginal';
      const reasons = [];
      if (action === 'fold') {
        if (entry.toCall > 0 && hasEq && gs.equity > required + 0.10) {
          verdict = 'expensive';
          reasons.push(`folded ${pct100(gs.equity)} equity when the call needed only ${pct100(required)} (pot odds)`);
        } else if (hasEq && entry.toCall > 0 && gs.equity < required - 0.03) {
          verdict = 'good';
          reasons.push(`below the ${pct100(required)} call price with ${pct100(gs.equity)} equity`);
        } else {
          verdict = 'good';
          reasons.push(entry.toCall > 0 ? 'discipline: the price was not there' : 'no price paid');
        }
      } else if (action === 'call') {
        if (!hasEq) { verdict = 'marginal'; reasons.push('equity still calculating at click time'); }
        else if (gs.equity >= required + 0.03) { verdict = 'good'; reasons.push(`${pct100(gs.equity)} equity beats the ${pct100(required)} price`); }
        else if (gs.equity >= required - 0.03) { verdict = 'marginal'; reasons.push(`close to break-even (${pct100(gs.equity)} vs ${pct100(required)})`); }
        else { verdict = 'expensive'; reasons.push(`paid ${pct100(required)} for ${pct100(gs.equity)} equity`); }
      } else if (action === 'check') {
        verdict = 'good';
        reasons.push('free card: no price paid');
      } else {
        if (hasEq && gs.equity > fs * 1.35) { verdict = 'good'; reasons.push(`value: ${pct100(gs.equity)} equity vs ${pct100(fs)} fair share`); }
        else if (hasEq && gs.equity > fs) { verdict = 'marginal'; reasons.push(`thin: ${pct100(gs.equity)} equity vs ${pct100(fs)} fair share`); }
        else { verdict = 'expensive'; reasons.push(`aggression with only ${hasEq ? pct100(gs.equity) : '?'} equity vs ${pct100(fs)} fair share`); }
      }
      reasons.push(`${entry.position} · ${entry.opps} opp${entry.opps === 1 ? '' : 's'}${spr !== null ? ` · SPR ${spr.toFixed(1)}` : ''} · $${Math.round(entry.pot).toLocaleString()} pot${entry.effStack > 0 ? ` · eff $${Math.round(entry.effStack).toLocaleString()}` : ''}${callEvNow !== null ? ` · call EV ${callEvNow >= 0 ? '+' : '-'}$${Math.abs(Math.round(callEvNow)).toLocaleString()}` : ''}${entry.profile !== 'Balanced' ? ` · ${entry.profile} profile` : ''}`);
      decisionLog.push({ ...entry, verdict, reasons });
      if (decisionLog.length > 12) decisionLog.shift();
      decisionStats[verdict]++;
      renderDecisionDebrief();
    } catch { }
  };
  const replaySnapshotKey = (snap) => `${snap.street}|${snap.board.join(',')}|${Math.round(snap.pot)}|${Math.round(snap.toCall)}`;
  const replayRecord = (ctx) => {
    try {
      const { hole, board } = ctx;
      if (!hole || hole.length !== 2) return;
      const holeKey = hole.join(',');
      if (!replayCurrent || replayCurrent.holeKey !== holeKey) {
        archiveReplayHand();
        replayCurrent = { holeKey, hole: hole.slice(), startedAt: Date.now(), snapshots: [], actions: [], heroWon: null, heroShowed: false, table: '' };
        try { replayCurrent.table = currentTableName(); } catch { }
      }
      const snap = {
        ts: Date.now(), street: ctx.street || 'Preflop', board: (board || []).slice(),
        pot: ctx.pot || 0, toCall: ctx.toCall || 0, effStack: ctx.effStack || 0,
        positionLabel: ctx.positionLabel || '?', activeOpponents: ctx.activeOpponents ?? 0,
        equity: (typeof ctx.equity === 'number') ? ctx.equity : null,
        equityMethod: ctx.equityMethod || null, equityTrialsComplete: ctx.equityTrialsComplete === true,
        required: ctx.required ?? null, advice: ctx.advice || '', adviceWhy: ctx.adviceWhy || '',
        raiseLevel: ctx.raiseLevel || 0, heroTurn: ctx.heroTurn === true
      };
      const last = replayCurrent.snapshots[replayCurrent.snapshots.length - 1];
      if (last && replaySnapshotKey(last) === replaySnapshotKey(snap)) {
        replayCurrent.snapshots[replayCurrent.snapshots.length - 1] = snap;
      } else {
        replayCurrent.snapshots.push(snap);
      }
      if (replayCurrent.snapshots.length > 40) replayCurrent.snapshots.shift();
      if (Array.isArray(ctx.actions) && ctx.actions.length) {
        replayCurrent.actions = ctx.actions.slice(-80);
      }
      if (ctx.heroWon !== undefined && ctx.heroWon !== null) replayCurrent.heroWon = ctx.heroWon;
      if (ctx.heroShowed !== undefined && ctx.heroShowed !== null) replayCurrent.heroShowed = ctx.heroShowed;
    } catch { }
  };
  const replayAttachAdvice = (advice) => {
    try {
      if (!replayCurrent || !replayCurrent.snapshots.length || !advice) return;
      const snap = replayCurrent.snapshots[replayCurrent.snapshots.length - 1];
      snap.advice = advice.text || advice.intent || '';
      snap.adviceWhy = advice.why || '';
      snap.adviceIntent = advice.intent || '';
      snap.requiredEquity = advice.requiredEquity ?? snap.required ?? null;
      snap.adviceEdge = advice.edge ?? null;
    } catch { }
  };
  const persistReplayLog = () => {
    try {
      void TNP6.putKv('tnp_replay_v1', JSON.stringify(replayLog.slice(-REPLAY_LOG_CAP)));
    } catch { }
  };
  const loadReplayLog = async () => {
    try {
      const raw = await TNP6.getKv('tnp_replay_v1');
      if (!raw) return;
      const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
      if (Array.isArray(parsed)) replayLog = parsed.slice(-REPLAY_LOG_CAP);
      replayCursor = Math.max(0, replayLog.length - 1);
      replayStreetCursor = 0;
    } catch { }
  };
  const archiveReplayHand = () => {
    try {
      if (!replayCurrent) return;
      if (replayCurrent.snapshots.length) {
        const lastSnap = replayCurrent.snapshots[replayCurrent.snapshots.length - 1];
        const known = replayCurrent.heroWon !== null && replayCurrent.heroWon !== undefined;
        replayLog.push({
          id: `${replayCurrent.holeKey}|${replayCurrent.startedAt}`,
          ts: replayCurrent.startedAt, endedAt: Date.now(),
          table: replayCurrent.table || '',
          hole: replayCurrent.hole,
          board: lastSnap.board || [],
          snapshots: replayCurrent.snapshots,
          actions: replayCurrent.actions,
          heroWon: replayCurrent.heroWon,
          heroShowed: replayCurrent.heroShowed,
          outcome: known ? (replayCurrent.heroWon ? 'won' : 'lost') : 'unknown'
        });
        if (replayLog.length > REPLAY_LOG_CAP) replayLog.shift();
        replayCursor = Math.max(0, replayLog.length - 1);
        replayStreetCursor = 0;
        persistReplayLog();
      }
      replayCurrent = null;
    } catch { }
  };
  const counterfactualEv = (snap) => {
    if (!snap) return null;
    const pot = snap.pot || 0, toCall = snap.toCall || 0;
    const eq = (typeof snap.equity === 'number') ? snap.equity : null;
    const stack = snap.effStack || 0;
    const out = {
      fold: 0, call: null, raise: null, basis: eq !== null
        ? `estimated from equity ${(eq * 100).toFixed(1)}% recorded at this point (${snap.equityMethod || 'estimate'}${snap.equityTrialsComplete ? '' : ', provisional'})`
        : 'no equity recorded at this point'
    };
    if (eq === null) return out;
    if (toCall > 0 && pot > 0) out.call = callEv(eq, pot, toCall);
    if (pot > 0) {
      const invest = stack > 0 ? Math.min(stack, Math.round(pot * 0.75)) : Math.round(pot * 0.75);
      if (invest > 0) {
        out.raise = shoveEv(eq, pot, invest, 0.40);
        out.raiseAssumed = '3/4-pot bet, 40% assumed fold equity';
      }
    }
    return out;
  };
  const renderReplayPanel = () => {
    const whichEl = document.getElementById('tnp-replay-which');
    const cardsEl = document.getElementById('tnp-replay-cards');
    const streetsEl = document.getElementById('tnp-replay-streets');
    const stateEl = document.getElementById('tnp-replay-state');
    const adviceEl = document.getElementById('tnp-replay-advice');
    const cfEl = document.getElementById('tnp-replay-cf');
    const actionsEl = document.getElementById('tnp-replay-actions');
    if (!whichEl) return;
    if (!replayLog.length) {
      setText(whichEl, replayCurrent ? 'current hand recording…' : 'no recorded hands yet');
      setHTML(cardsEl, ''); setHTML(streetsEl, ''); setText(stateEl, '-'); setText(adviceEl, '-');
      setHTML(cfEl, ''); setHTML(actionsEl, '');
      return;
    }
    replayCursor = Math.max(0, Math.min(replayLog.length - 1, replayCursor));
    const hand = replayLog[replayCursor];
    const snaps = hand.snapshots || [];
    replayStreetCursor = Math.max(0, Math.min(Math.max(0, snaps.length - 1), replayStreetCursor));
    const snap = snaps[replayStreetCursor] || null;
    setText(whichEl, `hand ${replayCursor + 1}/${replayLog.length} · ${new Date(hand.ts).toLocaleTimeString()}`);
    setHTML(cardsEl,
      (hand.hole || []).map(c => siteCardHtml(c, '', 'your hole card')).join('')
      + '<span class="tnp-outs-more"> </span>'
      + (snap ? (snap.board || []).map(c => siteCardHtml(c, '', 'board card at this point')).join('') : (hand.board || []).map(c => siteCardHtml(c, '', 'final board card')).join('')));
    setHTML(streetsEl, snaps.map((s, i) =>
      `<button type="button" class="tnp-timeline-step${i === replayStreetCursor ? ' tnp-timeline-now' : ''}" data-replay-step="${i}">${escapeHtml(s.street.slice(0, 4))}</button>`).join(''));
    if (snap) {
      setText(stateEl, `${snap.street} · pot $${Math.round(snap.pot).toLocaleString()}${snap.toCall > 0 ? ` · to call $${Math.round(snap.toCall).toLocaleString()}` : ''} · ${snap.positionLabel} · ${snap.activeOpponents} opp${snap.activeOpponents === 1 ? '' : 's'}${snap.effStack ? ` · eff $${Math.round(snap.effStack).toLocaleString()}` : ''}${snap.equity !== null ? ` · equity ${(snap.equity * 100).toFixed(0)}%` : ''}`);
      setText(adviceEl, snap.advice ? `${snap.advice}${snap.adviceWhy ? ` — ${snap.adviceWhy}` : ''}` : 'no recommendation recorded at this point');
      const cf = counterfactualEv(snap);
      setHTML(cfEl, cf ? `
        <div class="tnp-replay-cf-row"><span>fold</span><span>$0 (baseline)</span></div>
        ${cf.call !== null ? `<div class="tnp-replay-cf-row"><span>call</span><span>${cf.call >= 0 ? '+' : '-'}$${Math.abs(Math.round(cf.call)).toLocaleString()}</span></div>` : ''}
        ${cf.raise !== null ? `<div class="tnp-replay-cf-row"><span>raise</span><span>${cf.raise >= 0 ? '+' : '-'}$${Math.abs(Math.round(cf.raise)).toLocaleString()} (${escapeHtml(cf.raiseAssumed || '')})</span></div>` : ''}
        <div class="tnp-freshness">Estimated EV · ${escapeHtml(cf.basis)}. Estimates, not the actual outcome.</div>` : '');
    } else {
      setText(stateEl, '-'); setText(adviceEl, '-'); setHTML(cfEl, '');
    }
    const actions = hand.actions || [];
    setHTML(actionsEl, actions.length
      ? `<div class="tnp-freshness">Actions this hand:</div>` + actions.slice(-12).map(a => `<div class="tnp-replay-action">${escapeHtml(String(a).slice(0, 90))}</div>`).join('')
      : '');
  };
  const replayStepTo = (i) => {
    replayStreetCursor = i;
    renderReplayPanel();
  };
  const replayMoveHand = (delta) => {
    if (!replayLog.length) return;
    replayCursor = Math.max(0, Math.min(replayLog.length - 1, replayCursor + delta));
    replayStreetCursor = 0;
    renderReplayPanel();
  };

  const DRILL_STREETS = ['Preflop', 'Flop', 'Turn', 'River'];
  const generateDrill = (rnd = Math.random) => {
    const randInt = (n) => Math.max(0, Math.min(n - 1, Math.floor(rnd() * n)));
    const deck = [];
    for (const r of RANKS) for (const s of SUITS) deck.push(r + s);
    for (let i = deck.length - 1; i > 0; i--) {
      const j = randInt(i + 1);
      const t = deck[i]; deck[i] = deck[j]; deck[j] = t;
    }
    const street = DRILL_STREETS[randInt(rnd() < 0.4 ? 1 : 4)];
    const boardCount = { Preflop: 0, Flop: 3, Turn: 4, River: 5 }[street];
    const hole = deck.slice(0, 2);
    const board = deck.slice(2, 2 + boardCount);
    const opponents = rnd() < 0.6 ? 1 : 1 + randInt(3);
    const positions = ['UTG', 'MP', 'CO', 'BTN', 'SB', 'BB'];
    const position = positions[randInt(positions.length)];
    const tables = TABLE_CATALOG.filter(t => t.bb && t.sb);
    const table = tables[randInt(tables.length)];
    const bb = table.bb / 100;
    let effStack = bb * (25 + randInt(176));
    let pot = bb + bb / 2;
    let toCall = 0;
    let raiseLevel = 0;
    if (street === 'Preflop') {
      const scenario = randInt(4);
      if (scenario === 0) { toCall = bb; pot = bb * 1.5; raiseLevel = 0; }
      else if (scenario === 1) { toCall = Math.round(bb * 2.5); pot = Math.round(bb * 3.5); raiseLevel = 1; }
      else if (scenario === 2) { toCall = Math.round(bb * 4.5); pot = Math.round(bb * 6.5); raiseLevel = 2; }
      else { toCall = Math.round(bb * 9); pot = Math.round(bb * 13); raiseLevel = 3; }
    } else {
      pot = Math.round(bb * (3 + randInt(10)) * (1 + opponents) / 2);
      const facing = randInt(3);
      if (facing === 0) { toCall = 0; raiseLevel = 0; }
      else if (facing === 1) { toCall = Math.round(pot * (0.4 + rnd() * 0.4)); raiseLevel = 1; }
      else { toCall = Math.round(pot * (0.8 + rnd() * 0.7)); raiseLevel = 2; }
      pot += toCall;
    }
    effStack = Math.max(effStack, Math.round(toCall * 3), Math.round(bb * 40));
    const oppTypes = Object.keys(PLAYER_TYPES).filter(t => t !== 'UNKNOWN');
    const oppType = oppTypes[randInt(oppTypes.length)];
    return {
      id: 'drill-' + Date.now().toString(36) + '-' + Math.floor(rnd() * 1e6).toString(36),
      synthetic: true, street, hole, board, opponents, position,
      tableName: table.name, bb, effStack, pot, toCall, raiseLevel,
      oppType, ts: Date.now()
    };
  };
  const drillValidate = (drill) => {
    if (!drill || drill.synthetic !== true) return { valid: false, reason: 'not a synthetic drill' };
    const cards = drill.hole.concat(drill.board || []);
    if (drill.hole.length !== 2) return { valid: false, reason: 'hole cards must be exactly two' };
    const seen = new Set();
    for (const c of cards) {
      if (seen.has(c)) return { valid: false, reason: `duplicate card ${c}` };
      seen.add(c);
      if (!CARD_IDX[c] && CARD_IDX[c] !== 0) return { valid: false, reason: `invalid card ${c}` };
    }
    const n = { Preflop: 0, Flop: 3, Turn: 4, River: 5 }[drill.street];
    if ((drill.board || []).length !== n) return { valid: false, reason: `board size mismatch for ${drill.street}` };
    if (!(drill.opponents >= 1 && drill.opponents <= 4)) return { valid: false, reason: 'opponents out of range' };
    if (!(drill.bb > 0)) return { valid: false, reason: 'bb not positive' };
    if (!(drill.effStack > 0)) return { valid: false, reason: 'stack not positive' };
    if (drill.pot < drill.bb * 1.5 - 0.01) return { valid: false, reason: 'pot below blinds' };
    if (drill.toCall < 0) return { valid: false, reason: 'negative call' };
    if (drill.toCall > 0 && drill.toCall >= drill.effStack) return { valid: false, reason: 'call exceeds stack' };
    if (!['UTG', 'MP', 'CO', 'BTN', 'SB', 'BB'].includes(drill.position)) return { valid: false, reason: 'bad position' };
    return { valid: true };
  };
  const drillDecision = (drill, equity, actionBtns = null) => {
    if (!drill || drill.synthetic !== true) return null;
    if (drill.street === 'Preflop') {
      const intent = getPreflopIntent(drill.hole, drill.position, drill.raiseLevel, drill.opponents, drill.toCall, {
        seats: drill.opponents + 1, noPreFlop: false, toCallUnknown: false
      });
      const cls = handClassKey(drill.hole[0], drill.hole[1]);
      const eq = (typeof equity === 'number') ? equity : PREFLOP_EQUITY_169[cls];
      return {
        action: intent, text: intent === 'raise' ? 'Raise' : intent === 'call' ? 'Call' : intent === 'check' ? 'Check' : 'Fold',
        why: `Preflop chart intent from ${drill.position} facing raise level ${drill.raiseLevel} vs ${drill.opponents} opponent(s)`,
        equity: typeof eq === 'number' ? eq : null,
        requiredEquity: drill.toCall > 0 ? drill.toCall / (drill.pot + drill.toCall) : 0
      };
    }
    const btns = actionBtns || {
      hasFold: drill.toCall > 0, foldText: 'Fold',
      hasCheck: drill.toCall === 0, checkText: 'Check',
      hasCall: drill.toCall > 0, callText: `Call $${Math.round(drill.toCall).toLocaleString()}`,
      hasRaise: true, raiseText: drill.toCall > 0 ? 'Raise' : 'Bet'
    };
    const outs = calculateOuts(drill.hole, drill.board);
    const rec = getRecommendation(equity, drill.opponents, drill.toCall, drill.pot, btns, {
      street: drill.street, position: drill.position, raiseLevel: drill.raiseLevel,
      outs, hole: drill.hole, board: drill.board,
      boardTexture: analyzeBoardTexture(drill.board),
      effStack: drill.effStack, seats: drill.opponents + 1,
      toCallUnknown: false, ciWidth: 0.01
    });
    return {
      action: rec.intent, text: rec.text, why: rec.why,
      equity: (typeof equity === 'number') ? equity : null,
      requiredEquity: rec.requiredEquity
    };
  };
  const persistDrillScore = () => {
    try {
      void TNP6.putKv('tnp_drill_stats_v1', JSON.stringify(drillState.score));
    } catch { }
  };
  const loadDrillScore = async () => {
    try {
      const raw = await TNP6.getKv('tnp_drill_stats_v1');
      if (!raw) return;
      const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
      if (parsed && Number.isFinite(parsed.seen)) drillState.score = parsed;
    } catch { }
  };
  const drillEquity = async (drill) => {
    const mySeq = ++drillSeq;
    const isCancelled = () => drillSeq !== mySeq;
    const useExact = drill.opponents === 1 && drill.board.length >= 3 && drill.board.length <= 5;
    if (useExact) {
      try {
        const exact = await runExactEquity(drill.hole, drill.board, -1, null, { isCancelled });
        if (exact && exact.samples > 0 && !isCancelled()) {
          return { equity: exact.equity, method: 'exact enumeration', trials: exact.samples, complete: true };
        }
      } catch { }
    }
    const res = await runMandatedEquity(drill.hole, drill.board, drill.opponents, -2, { isCancelled });
    if (!res) return null;
    return {
      equity: res.equity, method: res.method || 'monte-carlo',
      trials: res.samples || 0, complete: res.trialsComplete === true
    };
  };
  const renderDrillPanel = () => {
    const scenarioEl = document.getElementById('tnp-drill-scenario');
    const cardsEl = document.getElementById('tnp-drill-cards');
    const verdictEl = document.getElementById('tnp-drill-verdict');
    const scoreEl = document.getElementById('tnp-drill-score');
    if (!scenarioEl) return;
    const d = drillState.active;
    if (!d) {
      setText(scenarioEl, 'Press "New scenario" to generate a synthetic practice hand.');
      setHTML(cardsEl, ''); setHTML(verdictEl, '');
    } else {
      const oppT = PLAYER_TYPES[d.oppType] || { label: '?' };
      setText(scenarioEl, `${d.street} · ${d.position} · ${d.opponents} opp (${oppT.label}) · $${Math.round(d.pot).toLocaleString()} pot${d.toCall > 0 ? ` · to call $${Math.round(d.toCall).toLocaleString()}` : ' · no bet to you'} · eff $${Math.round(d.effStack).toLocaleString()} · ${d.tableName} stakes`);
      setHTML(cardsEl,
        d.hole.map(c => siteCardHtml(c, '', 'your hole card')).join('')
        + (d.board || []).map(c => siteCardHtml(c, '', 'board card')).join(''));
      const a = drillState.answered;
      if (!a) {
        setHTML(verdictEl, `<span class="tnp-freshness">What is your play?</span>`);
      } else {
        const matched = a.userAction === a.engine.action;
        setHTML(verdictEl, `
          <div class="tnp-decision-row">
            <span class="tnp-decision-meta">you: ${escapeHtml(a.userAction)} · engine: ${escapeHtml(a.engine.text || a.engine.action)}</span>
            <span class="tnp-verdict ${matched ? 'tnp-verdict-good' : 'tnp-verdict-expensive'}">${matched ? 'MATCH' : 'DIFFERENT'}</span>
            <span class="tnp-decision-why">${escapeHtml(a.engine.why || '')}${a.engine.equity !== null && a.engine.equity !== undefined ? ` · equity ${(a.engine.equity * 100).toFixed(1)}%` : ''}${a.engine.requiredEquity !== null && a.engine.requiredEquity !== undefined ? ` vs ${(a.engine.requiredEquity * 100).toFixed(1)}% required` : ''}${a.trials ? ` · ${a.method} (${a.trials.toLocaleString()} trials${a.complete ? '' : ', partial'})` : ''}</span>
          </div>`);
      }
    }
    const s = drillState.score;
    setText(scoreEl, s.seen > 0 ? `Drill score: ${s.matched}/${s.seen} matched the engine` : 'No drills answered yet.');
  };
  const drillNew = () => {
    const drill = generateDrill();
    const check = drillValidate(drill);
    if (!check.valid) return null;
    drillState.active = drill;
    drillState.answered = null;
    drillSeq++;
    renderDrillPanel();
    return drill;
  };
  const drillAnswer = async (userAction) => {
    const d = drillState.active;
    if (!d || drillState.answered) return null;
    drillState.score.seen++;
    let engine = null;
    let trials = 0, method = '', complete = false;
    try {
      const eq = await drillEquity(d);
      if (eq) { trials = eq.trials; method = eq.method; complete = eq.complete; }
      engine = drillDecision(d, eq ? eq.equity : null);
    } catch {
      engine = drillDecision(d, null);
    }
    if (!engine) engine = { action: 'wait', text: '-', why: 'engine unavailable', equity: null, requiredEquity: null };
    if (engine.action === userAction) drillState.score.matched++;
    drillState.answered = { userAction, engine, trials, method, complete };
    persistDrillScore();
    renderDrillPanel();
    return drillState.answered;
  };

  const DIAG_OK = 'ok', DIAG_WARN = 'warn', DIAG_FAIL = 'fail', DIAG_IDLE = 'idle';
  const buildDiagnosticsReport = () => {
    const now = Date.now();
    const rows = [];
    const row = (component, status, detail) => rows.push({ component, status, detail: String(detail ?? '') });
    let parser = [];
    try { parser = buildParserReport(); } catch { parser = []; }
    const parserHits = parser.reduce((a, p) => a + (p.hits || 0), 0);
    const parserMisses = parser.reduce((a, p) => a + (p.misses || 0), 0);
    row('DOM parser', parserHits > 0 ? DIAG_OK : (runtimeActive ? DIAG_WARN : DIAG_IDLE),
      parserHits > 0 ? `${parserHits} selector hits / ${parserMisses} misses this session` : 'no selector hits yet');
    const holeOk = gameState.holeCards && gameState.holeCards.length === 2;
    row('Hole-card recognition', holeOk ? DIAG_OK : (runtimeActive ? DIAG_WARN : DIAG_IDLE),
      holeOk ? gameState.holeCards.join(' ') : 'two hero hole cards not currently visible');
    const boardExpected = gameState.street && gameState.street !== 'Preflop';
    const boardOk = !boardExpected || (gameState.boardCards && gameState.boardCards.length >= 3);
    row('Board recognition', boardOk ? DIAG_OK : DIAG_WARN,
      gameState.boardCards && gameState.boardCards.length ? gameState.boardCards.join(' ') : (boardExpected ? 'postflop street without board cards' : 'no board cards (preflop or waiting)'));
    row('Player identification', lastHeroSeatOk === null ? DIAG_IDLE : (lastHeroSeatOk ? DIAG_OK : DIAG_WARN),
      lastHeroSeatOk === null ? 'not evaluated yet' : (lastHeroSeatOk ? 'own seat identified' : 'own seat not found'));
    const ident = tableIdentityDebug();
    row('Table identification', ident.mode === 'confirmed' ? DIAG_OK : ident.mode === 'none' ? DIAG_IDLE : DIAG_WARN,
      ident.mode === 'confirmed' ? `${ident.name} (${ident.sourceLabel || ident.source || 'confirmed'})` : (ident.mode === 'none' ? 'no table identity yet' : `${ident.name || '?'} unconfirmed`));
    row('Position detection', lastPositionKnown ? (lastPositionExact ? DIAG_OK : DIAG_WARN) : DIAG_WARN,
      lastPositionKnown ? `${gameState.positionLabel || gameState.position}${lastPositionExact ? '' : ' (estimated)'}` : 'position not determined');
    const potState = provClassify(provenance.pot, now);
    row('Pot parsing', potState === 'fresh' ? DIAG_OK : (potState === 'unavailable' ? DIAG_WARN : DIAG_WARN),
      provenance.pot ? `$${Math.round(Number(provenance.pot.value) || 0).toLocaleString()} via ${provenance.pot.source}` : 'no pot read');
    const toCallState = provClassify(provenance.toCall, now);
    row('Call amount parsing', gameState.toCallUnknown ? DIAG_WARN : (toCallState === 'fresh' ? DIAG_OK : DIAG_WARN),
      gameState.toCallUnknown ? 'call size unreadable this street' : (provenance.toCall ? `$${Math.round(Number(provenance.toCall.value) || 0).toLocaleString()} via ${provenance.toCall.source}` : 'no call read'));
    const handsSeen = pipelineStats.awardWindows + session.handsPlayed;
    row('Session synchronization', handsSeen > 0 ? DIAG_OK : DIAG_WARN,
      `${session.handsPlayed} hands played · ${pipelineStats.awardWindows} award windows · ${pipelineStats.actionsParsed} actions parsed`);
    const profileCount = Object.keys(profiles).length;
    row('Opponent tracking', profileCount > 0 ? DIAG_OK : (handsSeen > 0 ? DIAG_WARN : DIAG_IDLE),
      profileCount > 0 ? `${profileCount} profile(s) stored` : 'no opponent profiles built yet');
    const bbOk = (tableStakesRead && tableStakesRead.bb > 0) || (ident && ident.table && ident.table.bb) || session.bb > 0;
    row('BB/cash conversion', bbOk ? DIAG_OK : DIAG_WARN,
      bbOk ? `stakes read; session BB $${(session.bb || (ident && ident.table ? ident.table.bb / 100 : 0)).toLocaleString()}` : 'stakes not read yet');
    row('Equity calculation', gameState.isCalculating ? DIAG_WARN : (gameState.equity !== null && gameState.equity !== undefined ? (gameState.equityTrialsComplete || gameState.equityMethod === 'exact' || gameState.equityMethod === 'preflop-table' ? DIAG_OK : DIAG_WARN) : DIAG_WARN),
      gameState.equity !== null && gameState.equity !== undefined
        ? `${gameState.equityMethod || 'unknown'} · ${(gameState.mcSamples || 0).toLocaleString()} trials${gameState.equityTrialsComplete ? ' (complete)' : ' (partial)'}${gameState.exactEquity !== null && gameState.exactEquity !== undefined ? ` · exact ${(gameState.exactEquity * 100).toFixed(2)}%` : ''}`
        : 'no equity this state');
    row('Recommendation generation', lastRecAt > 0 ? (now - lastRecAt < 60000 ? DIAG_OK : DIAG_WARN) : DIAG_IDLE,
      lastRecAt > 0 ? `last "${lastRecIntent}" ${Math.round((now - lastRecAt) / 1000)}s ago` : 'no recommendation generated yet');
    row('MutationObserver connectivity', runtimeObserver ? (observerLastMutationAt > 0 ? (now - observerLastMutationAt < 120000 ? DIAG_OK : DIAG_WARN) : DIAG_OK) : (runtimeActive ? DIAG_FAIL : DIAG_IDLE),
      runtimeObserver ? (observerLastMutationAt > 0 ? `alive · last mutation ${Math.round((now - observerLastMutationAt) / 1000)}s ago` : 'connected, no mutations yet') : 'not connected');
    const backend = storage.backendName();
    const degraded = storageState.degraded && storageState.degraded.size ? Array.from(storageState.degraded) : [];
    row('Storage availability', degraded.length ? DIAG_WARN : DIAG_OK,
      `${backend} · IndexedDB ${idbPrimary ? 'primary' : 'unavailable'}${degraded.length ? ` · degraded: ${degraded.join(', ')}` : ''}`);
    row('Calculation execution time', lastComputeMs > 0 ? (lastComputeMs < 500 ? DIAG_OK : DIAG_WARN) : DIAG_IDLE,
      lastComputeMs > 0 ? `last compute pass ${Math.round(lastComputeMs)}ms` : 'no compute pass yet');
    const issues = gameState.readIssues || [];
    row('Card sanity', issues.length ? DIAG_WARN : DIAG_OK,
      issues.length ? issues.join('; ').slice(0, 160) : 'no duplicate, missing or invalid cards detected');
    row('Long-task monitor', perfWatch.installed ? (perfWatch.longTasks > 0 ? DIAG_WARN : DIAG_OK) : DIAG_IDLE,
      perfWatch.installed ? `${perfWatch.longTasks} long task(s) · worst ${Math.round(perfWatch.worstLongMs)}ms` : 'PerformanceObserver longtask not supported here');
    return rows;
  };
  const tagDecisionOutcomes = (heroWon, sinceTs) => {
    try {
      if (heroWon !== true && heroWon !== false) return;
      for (const d of decisionLog) {
        if (d.outcome !== undefined) continue;
        if (sinceTs && d.ts < sinceTs) { d.outcome = 'unknown'; continue; }
        d.outcome = heroWon ? 'won' : 'lost';
      }
    } catch { }
  };

  const decisionCalibration = () => {
    const resolved = decisionLog.filter((d) => d.outcome === 'won' || d.outcome === 'lost');
    if (resolved.length < 5) {
      return { n: resolved.length, hitRate: null, note: `insufficient resolved decisions (${resolved.length}/5) for a calibration read` };
    }
    let agreed = 0;
    for (const d of resolved) {
      const favored = (d.callEv !== null && d.callEv > 0) || (typeof d.equity === 'number' && d.equity > d.required);
      const won = d.outcome === 'won';
      if ((favored && won) || (!favored && !won)) agreed++;
    }
    const hitRate = agreed / resolved.length;
    const note = Math.abs(hitRate - 0.5) < 0.12
      ? 'prediction and outcome agree at chance level: results are not yet informative about decision quality'
      : (hitRate > 0.5
        ? 'positive-edge decisions won more often than not over this tiny sample'
        : 'positive-edge decisions lost more often than not over this tiny sample (normal in small samples)');
    return { n: resolved.length, hitRate, note };
  };

  const integrityRead = () => {
    const summary = provenanceSummary();
    const readsAgree = gameState.readIssues ? gameState.readIssues.length === 0 : null;
    const oppSamples = [];
    try {
      const me = findOwnSeat();
      for (const seat of getAllSeats()) {
        if (me && (seat === me || seat.contains(me) || me.contains(seat))) continue;
        if (!isOpponentActive(seat)) continue;
        const player = getPlayerName(seat);
        const p = (player && player.id) ? (profiles[player.id] ?? null) : null;
        oppSamples.push(p ? (p.handsObserved || 0) : 0);
      }
    } catch { }
    const oppWithSample = oppSamples.filter((n) => n >= 10).length;
    const finalNow = gameState.equityTrialsComplete === true
      || gameState.equityMethod === 'exact' || gameState.equityMethod === 'preflop-table';
    const simState = gameState.isCalculating ? 'provisional'
      : (gameState.equity !== null && gameState.equity !== undefined && !finalNow ? 'provisional'
        : (finalNow ? 'final' : 'idle'));
    return {
      confidence: summary.confidence, fresh: summary.fresh, stale: summary.stale,
      inferred: summary.inferred, unavailable: summary.unavailable,
      readsAgree, oppCount: oppSamples.length, oppWithSample,
      oppMedian: oppSamples.length ? oppSamples.slice().sort((a, b) => a - b)[Math.floor(oppSamples.length / 2)] : 0,
      simState, calibration: decisionCalibration()
    };
  };

  const renderIntegrityStrip = () => {
    const host = document.getElementById('tnp-diag-integrity');
    if (!host) return;
    const r = integrityRead();
    const conf = Math.round(r.confidence * 100);
    const confCls = conf >= 70 ? 'tnp-pill-ok' : (conf >= 45 ? 'tnp-pill-dim' : 'tnp-pill-warn');
    const sim = r.simState === 'final' ? 'final (1,000,000 trials complete)'
      : r.simState === 'provisional' ? 'provisional - simulation still running' : 'idle';
    const cal = r.calibration;
    const calText = cal.hitRate !== null
      ? `${Math.round(cal.hitRate * 100)}% agreement over ${cal.n} resolved decisions`
      : 'insufficient resolved decisions yet';
    setHTML(host,
      '<div class="tnp-integrity"><span class="tnp-pill ' + confCls + '">state ' + conf + '% fresh</span>'
        + '<span class="tnp-integrity-item">reads '+ (r.readsAgree === null ? 'n/a' : (r.readsAgree ? 'agree' : 'disagree')) +'</span>'
        + '<span class="tnp-integrity-item">opp samples '+ r.oppWithSample + '/' + r.oppCount + '>=10 hands</span>'
        + '<span class="tnp-integrity-item">simulation: ' + sim + '</span>'
        + '<span class="tnp-integrity-item">calibration: ' + calText + '</span>'
        + '</div>'
        + '<div class="tnp-integrity-note">' + escapeHtml(cal.note) + ' · A statistically correct decision is not the same as a favourable result.</div>');
  };

  const renderDiagnosticsPanel = () => {
    const rowsEl = document.getElementById('tnp-diag-rows');
    if (!rowsEl) return;
    const rows = buildDiagnosticsReport();
    const color = { ok: 'var(--tnp-success)', warn: 'var(--tnp-amber)', fail: 'var(--tnp-danger)', idle: 'var(--tnp-muted)' };
    const label = { ok: 'OK', warn: 'WARN', fail: 'FAIL', idle: 'IDLE' };
    setHTML(rowsEl, rows.map(r => `
      <div class="tnp-diag-row">
        <span class="tnp-diag-status" style="color:${color[r.status]};">${label[r.status]}</span>
        <span class="tnp-diag-component">${escapeHtml(r.component)}</span>
        <span class="tnp-diag-detail">${escapeHtml(r.detail)}</span>
      </div>`).join(''));
    renderIntegrityStrip();
  };

  const renderDecisionDebrief = () => {
    const logEl = document.getElementById('tnp-decision-log');
    if (logEl) {
      if (!decisionLog.length) {
        setHTML(logEl, `<div class="tnp-exploit-hint">Your next fold, call, bet or raise gets graded here against pot odds, equity, position and SPR.</div>`);
      } else {
        const chip = (v) => `<span class="tnp-verdict tnp-verdict-${v}">${v === 'good' ? 'GOOD' : v === 'marginal' ? 'MARGINAL' : 'EXPENSIVE'}</span>`;
        setHTML(logEl, decisionLog.slice().reverse().map((d) => `
          <div class="tnp-decision-row">
            <span class="tnp-decision-meta">${escapeHtml(d.street)} · ${escapeHtml(d.action)}${d.toCall > 0 ? ` $${d.toCall.toLocaleString()}` : ''}${d.effStack ? ` · eff $${Math.round(d.effStack).toLocaleString()}` : ''}${d.profile && d.profile !== 'Balanced' ? ` · ${escapeHtml(d.profile)}` : ''}</span>
            ${chip(d.verdict)}
            <span class="tnp-decision-why">${escapeHtml(d.reasons.join(' · '))}</span>
          </div>`).join(''));
      }
    }
    const scoreEl = document.getElementById('tnp-decision-score');
    if (scoreEl) {
      const total = decisionStats.good + decisionStats.marginal + decisionStats.expensive;
      setText(scoreEl, total > 0
        ? `Decision quality: ${decisionStats.good} good · ${decisionStats.marginal} marginal · ${decisionStats.expensive} expensive (${Math.round(100 * decisionStats.good / total)}% clean)`
        : 'Decision quality: no graded decisions yet this session.');
    }
    const lastEl = document.getElementById('tnp-last-decision');
    if (lastEl) {
      const d = decisionLog[decisionLog.length - 1];
      if (d) {
        lastEl.className = `tnp-last-decision tnp-verdict-${d.verdict}`;
        setText(lastEl, `Last decision: ${d.action} (${d.verdict}) — ${d.reasons[0]}`);
      } else {
        lastEl.className = 'tnp-last-decision';
        setText(lastEl, '');
      }
    }
  };

  const renderNow = () => {
    if (settings.hudEnabled === false) { applyHudEnabled(); return; }
    renderStatusChip();
    if (activeTab === 'analysis' || activeTab === 'opponents') { renderUI(); }
    else if (activeTab === 'you') { renderActionBanner(); renderMirrorPanel(); }
    else if (activeTab === 'session') { renderActionBanner(); renderSessionPanel(); renderDecisionDebrief(); }
    else if (activeTab === 'bankroll') { renderActionBanner(); renderBankrollPanel(); }
    else if (activeTab === 'replay') { renderActionBanner(); renderReplayPanel(); }
    else if (activeTab === 'drill') { renderActionBanner(); renderDrillPanel(); }
    else if (activeTab === 'diagnostics') { renderActionBanner(); renderDiagnosticsPanel(); }
    else if (activeTab === 'settings') { renderActionBanner(); renderDataLifecycleCards(); }
    else renderActionBanner();
    try { uiRefreshTick(); } catch {  }
  };

  let renderQueued = false;
  const updateUI = () => {
    if (renderQueued) return;
    renderQueued = true;
    const schedule = typeof requestAnimationFrame === 'function'
      ? requestAnimationFrame
      : (fn) => setTimeout(fn, 16);
    schedule(() => {
      renderQueued = false;
      renderNow();
    });
  };

  let observerTimeout = null;
  let initialComputeTimer = null;
  let routeInterval = null;
  let computeInterval = null;
  let sessionTimerInterval = null;
  let runtimeObserver = null;
  let resizeHandler = null;
  let documentClickHandler = null;
  let lobbyClickHandler = null;
  let initStarted = false;
  let runtimeActive = false;
  let uiCleanupFns = [];

  const isOwnMutation = (m) => {
    const t = m.target;
    if (!t) return false;
    if (uiElement && (t === uiElement || uiElement.contains(t))) return true;
    if (t.nodeType === 1) {
      if (t.id && String(t.id).indexOf('tnp-') === 0) return true;
      if (t.closest && t.closest('#tnp-dossier, .tnp-seat-badge')) return true;
      if (m.type === 'attributes' && m.attributeName === 'class'
        && (highlightedCards.has(t) || (t.classList && t.classList.contains('tnp-card-highlight')))) return true;
    }
    if (m.type === 'childList') {
      const nodes = [...m.addedNodes, ...m.removedNodes];
      if (nodes.length && nodes.every(n => n.nodeType === 1 && (
        (n.id && String(n.id).indexOf('tnp-') === 0) ||
        (n.classList && n.classList.contains('tnp-seat-badge'))
      ))) return true;
    }
    return false;
  };

  const HOLD_ROOT_SEL = '[class*="holdemWrapper"], [class*="tContainer___"], [class*="tableWrap___"], [class*="playerMeGateway___"]';
  const holdemScopeRoot = () => {
    try { return document.querySelector(HOLD_ROOT_SEL) || document.body; } catch { return document.body; }
  };
  let observerLastRun = 0;
  const initObserver = () => {
    const config = { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'aria-label', 'data-state'] };
    let observedRoot = null;
    runtimeObserver = new MutationObserver((mutations) => {
      let relevant = false;
      for (const m of mutations) {
        if (m.target && m.target.isConnected === false) continue;
        if (!isOwnMutation(m)) { relevant = true; break; }
      }
      if (!relevant) return;
      observerLastMutationAt = Date.now();
      if (!runtimeActive) return;
      if (observedRoot && !document.contains(observedRoot)) {
        try { runtimeObserver.disconnect(); } catch { }
        observedRoot = holdemScopeRoot();
        try { runtimeObserver.observe(observedRoot, config); } catch { }
      }
      clearTimeout(observerTimeout);
      observerTimeout = setTimeout(() => {
        if (!runtimeActive) return;
        const now = Date.now();
        if (now - observerLastRun < 200) return;
        observerLastRun = now;
        buildUI();
        const schedule = typeof requestAnimationFrame === 'function'
          ? requestAnimationFrame
          : (fn) => setTimeout(fn, 16);
        schedule(() => { if (runtimeActive) computeState(); });
      }, 300);
    });
    observedRoot = holdemScopeRoot();
    runtimeObserver.observe(observedRoot, config);
  };

  const isHoldemSurface = () => {
    for (let i = 0; i < SELECTORS.pokerRoot.length; i++) {
      if (document.querySelector(SELECTORS.pokerRoot[i])) {
        recordSelectorHit('pokerRoot', i);
        return true;
      }
    }
    recordSelectorMiss('pokerRoot');
    return false;
  };

  const cleanupRuntime = (reason = 'route-change') => {
    if (!runtimeActive && !uiElement) return;
    runtimeActive = false;
    mcJobId++;
    drillSeq++;
    try { archiveReplayHand(); } catch { }
    try { terminateOutsWorker(); } catch { }
    _seatsScanCache = { at: 0, seats: null };
    _ownSeatCache = { at: 0, seat: null, has: false };
    _actionButtonsCache = { at: 0, buttons: null };
    _boardRootCache = { at: 0, root: null };
    try { cancelBoardRetry(); } catch { }
    boardRetrySig = '';
    try { cancelHoleRetry(); } catch { }
    holeRetrySig = '';
    _storageMetersRenderedAt = 0;
    _originPoolCache = { at: 0, bytes: 0 };
    clearTimeout(observerTimeout);
    observerTimeout = null;
    clearTimeout(initialComputeTimer);
    initialComputeTimer = null;
    clearInterval(computeInterval);
    computeInterval = null;
    clearInterval(sessionTimerInterval);
    sessionTimerInterval = null;
    if (runtimeObserver) {
      runtimeObserver.disconnect();
      runtimeObserver = null;
    }
    stopLogCapture(reason === 'route-change');
    if (resizeHandler) {
      window.removeEventListener('resize', resizeHandler);
      resizeHandler = null;
    }
    if (documentClickHandler) {
      document.removeEventListener('click', documentClickHandler);
      documentClickHandler = null;
    }
    if (lobbyClickHandler) {
      document.removeEventListener('click', lobbyClickHandler, true);
      lobbyClickHandler = null;
    }
    uninstallActivityGuards();
    flushAllSaves('cleanup');
    for (const cleanup of uiCleanupFns.splice(0)) {
      try { cleanup(); } catch {  }
    }
    clearCardHighlights();
    document.querySelectorAll('.tnp-seat-badge').forEach(el => el.remove());
    if (uiElement?.parentNode) uiElement.remove();
    document.getElementById('tnp-style')?.remove();
    uiElement = null;
    minimizedBodyEl = null;
    minimizedBodyPlaceholder = null;
    minimizedStyleBackup = null;
    isMinimized = false;

    gameState.lastStateHash = '';
    gameState.lastCardHash = '';
    lastHoleKey = '';
    if (reason !== 'route-change') tinfo(`[TNP] Runtime cleaned up: ${reason}`);
  };

  const startRuntime = () => {
    if (runtimeActive || !document.body || !isHoldemSurface()) return false;
    runtimeActive = true;

    injectCSS();
    buildUI();
    applyHudEnabled();
    updateMobileMode();
    initObserver();
    installActivityGuards();
    startLogCapture();
    resizeHandler = () => {
      updateMobileMode();
      if (settings.panelPos && typeof settings.panelPos.x === 'number' && uiElement) {
        const w = window.innerWidth || 1024, h = window.innerHeight || 768;
        const panelW = uiElement.offsetWidth || 348;
        const x = Math.max(-(panelW - 90), Math.min(w - 90, settings.panelPos.x));
        const y = Math.max(0, Math.min(h - 40, settings.panelPos.y));
        settings.panelPos = { x, y };
        dragPos = { x, y };
        uiElement.style.right = 'auto';
        uiElement.style.bottom = 'auto';
        uiElement.style.left = `${x}px`;
        uiElement.style.top = `${y}px`;
      }
    };
    window.addEventListener('resize', resizeHandler, { passive: true });
    initialComputeTimer = setTimeout(() => {
      initialComputeTimer = null;
      if (runtimeActive) computeState();
    }, 300);

    computeInterval = setInterval(() => {
      if (runtimeActive && isTableObservationAllowed()) computeState();
    }, 1500);
    sessionTimerInterval = setInterval(() => {
      if (!runtimeActive) return;
      if (activeTab === 'session') { renderSessionPanel(); renderDataLifecycleCards(); }

      try { uiRefreshTick(); } catch {  }
    }, 1000);
    documentClickHandler = (e) => {
      const btn = e.target?.closest?.('button, [role="button"]');
      if (!btn) return;
      const txt = (btn.textContent ?? '').trim();
      if (isPreActionButton(txt)) return;
      if (/(?:^|\s)(?:queueable|queued)___/i.test(getClassString(btn))) return;
      const actionBtns = getActiveActionButtons();
      const sameBtn = (el) => !!el && (el === btn || el.contains(btn) || btn.contains(el));
      if (/^\s*fold\b/i.test(txt) && sameBtn(actionBtns.fold)) {
        userFoldedThisHand = true;
        gameState.userFolded = true;
        recordDecision('fold');
        updateUI();
        return;
      }
      if (sameBtn(actionBtns.check)) recordDecision('check');
      else if (sameBtn(actionBtns.call)) recordDecision('call');
      else if (sameBtn(actionBtns.raise) || (actionBtns.hasRaise && /raise|bet|all-?in/i.test(txt))) recordDecision(/^all[- ]?in/i.test(txt) ? 'all-in' : 'raise');
    };
    document.addEventListener('click', documentClickHandler);

    lobbyClickHandler = (e) => onLobbyClick(e);
    document.addEventListener('click', lobbyClickHandler, true);
    return true;
  };

  const reconcileRoute = () => {
    const holdem = isHoldemSurface();
    if (holdem && !runtimeActive) {
      startRuntime();
    } else if (!holdem && runtimeActive) {
      cleanupRuntime('route-change');
    }
  };

const TNP6 = (() => {
  'use strict';
  const V6_DEFAULTS = {
    targetHalfWidth: 0.005, minSamples: 20000, maxSamples: 600000,
    deadlineMs: 12000, sliceMs: 12
  };

  const DB = { name: 'tnp6_poker', version: 2, db: null, ok: false, lastError: '' };
  const openDb = () => new Promise((resolve) => {
    if (DB.db) return resolve(DB.db);
    if (typeof indexedDB === 'undefined') { DB.lastError = 'indexeddb unavailable'; return resolve(null); }
    let req;
    try { req = indexedDB.open(DB.name, DB.version); } catch (e) { DB.lastError = String(e && e.message || e); return resolve(null); }
    req.onupgradeneeded = (e) => {
      const db = e.target.result;
      if (!db.objectStoreNames.contains('hands')) db.createObjectStore('hands', { keyPath: 'id' });
      if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv', { keyPath: 'k' });
      if (!db.objectStoreNames.contains('stats')) db.createObjectStore('stats', { keyPath: 'id' });
    };
    req.onsuccess = (e) => { DB.db = e.target.result; DB.ok = true; resolve(DB.db); };
    req.onerror = () => { DB.lastError = 'open failed'; resolve(null); };
    setTimeout(() => { if (!DB.db) resolve(null); }, 4000);
  });
  const idbOp = (store, mode, fn) => new Promise((resolve) => {
    if (!DB.db) return resolve(null);
    let tx;
    try { tx = DB.db.transaction(store, mode); } catch (e) { return resolve(null); }
    let out = null;
    let settled = false;
    const finish = (ok) => {
      if (settled) return;
      settled = true;
      resolve({ ok, out });
    };
    tx.oncomplete = () => finish(true);
    tx.onerror = () => finish(false);
    tx.onabort = () => finish(false);
    setTimeout(() => finish(false), 5000).unref?.();
    Promise.resolve()
      .then(() => fn(tx.objectStore(store)))
      .then((r) => { out = r; })
      .catch(() => { });
  });
  const idbGetRow = (store, key) => idbOp(store, 'readonly', (st) => new Promise((res) => {
    try {
      const r = st.get(key);
      r.onsuccess = () => res(r.result ?? null);
      r.onerror = () => res(null);
    } catch (e) { res(null); }
  }));
  const MIGRATION_KEY = 'tnp6_migration_v1';
  const MIGRATION_V2_KEY = 'tnp6_migration_v2';
  let migrationDone = false;
          const putKv = async (k, v) => {
    const db = await openDb(); if (!db) return false;
    const r = await idbOp('kv', 'readwrite', (st) => { st.put({ k, v }); });
    return !!(r && r.ok);
  };
  const getKv = async (k) => {
    const db = await openDb(); if (!db) return null;
    const r = await idbGetRow('kv', k);
    const row = r ? r.out : null;
    return (row && typeof row === 'object' && 'v' in row) ? row.v : null;
  };
  const deleteKv = async (k) => {
    const db = await openDb(); if (!db) return false;
    const r = await idbOp('kv', 'readwrite', (st) => { st.delete(k); });
    return !!(r && r.ok);
  };
  const migrateLegacy = async () => {
    if (migrationDone) return; migrationDone = true;
    const db = await openDb(); if (!db) return;
    const flagRow = await idbGetRow('kv', MIGRATION_KEY);
    const flag = flagRow ? flagRow.out : null;
    if (flag && flag.v === DB.version) return;
    await idbOp('kv', 'readwrite', (st) => {
      for (const k of ['legacy_profiles', 'legacy_hero', 'legacy_session', 'legacy_lifetime', 'legacy_bankroll']) {
        try { st.delete(k); } catch (e) { }
      }
      st.put({ k: MIGRATION_KEY, v: DB.version });
    });
  };
  const migrateLocalStorageToIdb = async () => {
    const db = await openDb(); if (!db) return { migrated: 0, skipped: true };
    const flagRow = await idbGetRow('kv', MIGRATION_V2_KEY);
    const flag = flagRow ? flagRow.out : null;
    if (flag && flag.v && flag.v.done) return { migrated: 0, skipped: true, alreadyDone: true };
    if (typeof localStorage === 'undefined') return { migrated: 0, skipped: true };
    const categories = ['profiles', 'notes', 'hero', 'lifetime', 'bankroll', 'session'];
    const pending = [];
    for (const cat of categories) {
      const key = STORAGE_KEYS[cat];
      if (!key) continue;
      let raw = null;
      try { raw = localStorage.getItem(key); } catch (e) { raw = null; }
      if (raw === null || raw === '') continue;
      const existing = await idbGetRow('kv', 'tnp_' + key);
      if (!(existing && existing.out)) pending.push({ k: 'tnp_' + key, v: raw, key });
    }
    let migrated = 0;
    if (pending.length) {
      const r = await idbOp('kv', 'readwrite', (st) => {
        for (const row of pending) st.put({ k: row.k, v: row.v });
        st.put({ k: MIGRATION_V2_KEY, v: { done: true, at: Date.now(), migrated: pending.length } });
      });
      if (r && r.ok) {
        migrated = pending.length;
        for (const row of pending) {
          try { localStorage.removeItem(row.key); } catch (e) { }
        }
      } else {
        return { migrated: 0, error: 'transaction failed' };
      }
    } else {
      await idbOp('kv', 'readwrite', (st) => {
        st.put({ k: MIGRATION_V2_KEY, v: { done: true, at: Date.now(), migrated: 0 } });
      });
    }
    return { migrated };
  };
  const persistHand = async (hand) => {
    const db = await openDb(); if (!db) return false;
    const r = await idbOp('hands', 'readwrite', (st) => {
      st.put(hand);
      try {
        const q = st.getAll();
        q.onsuccess = () => {
          const records = (q.result || []).sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));
          for (let i = 0; i < records.length - 400; i++) {
            try { st.delete(records[i].id); } catch (e) { }
          }
        };
      } catch (e) { }
    });
    return !!(r && r.ok);
  };


  const CLASSES = [];
  (() => {
    for (let i = 0; i < RANKS.length; i++) for (let j = i; j < RANKS.length; j++) {
      const hi = RANKS[j], lo = RANKS[i];
      CLASSES.push(hi === lo ? hi + lo : hi + lo + 's');
      if (hi !== lo) CLASSES.push(hi + lo + 'o');
    }
  })();
  const CLASS_COMBOS = (() => {
    const m = {};
    for (const cls of CLASSES) {
      const combos = [];
      const r1 = cls[0], r2 = cls[1], suited = cls[2] === 's', off = cls[2] === 'o';
      for (const s1 of SUITS) for (const s2 of SUITS) {
        if (r1 === r2) { if (s1 < s2) combos.push(r1 + s1 + r2 + s2); }
        else if (suited && s1 === s2) combos.push(r1 + s1 + r2 + s2);
        else if (off && s1 !== s2) combos.push(r1 + s1 + r2 + s2);
      }
      m[cls] = combos;
    }
    return m;
  })();


  const rangeWeightsDom = (playerId, opts) => {
    const o = opts || {};
    const w = new Float64Array(CLASSES.length);
    const p = (playerId && typeof profiles !== 'undefined') ? (profiles[playerId] ?? null) : null;
    const hands = p ? (p.handsObserved || 0) : 0;
    let vpip = 0.50, pfr = 0.20;
    if (p && hands >= 10) {
      const mm = (typeof getProfileMetrics === 'function') ? getProfileMetrics(p) : null;
      if (mm && Number.isFinite(mm.vpip)) vpip = Math.max(0.05, Math.min(1.0, mm.vpip / 100));
      if (mm && Number.isFinite(mm.pfr)) pfr = Math.max(0.02, Math.min(0.60, mm.pfr / 100));
    }
    const raiseLevel = o.raiseLevel || 0;
    const street = o.street || 'preflop';
    const scores = CLASSES.map((cls) => preflopScore(cls[0] + '♠', cls[1] + (cls[1] === cls[0] ? '♠' : (cls[2] === 's' ? '♠' : '♥'))));
    const order = CLASSES.map((c, i) => i).sort((a, b) => scores[b] - scores[a]);
    const fracFor = () => {
      if (street === 'preflop') {
        if (raiseLevel >= 2) return Math.max(0.02, Math.min(0.12, (pfr * 0.30) || 0.04));
        if (raiseLevel === 1) return Math.max(0.02, Math.min(0.45, pfr || 0.13));
        return Math.max(0.05, Math.min(1.0, vpip || 0.50));
      }
      return Math.max(0.05, Math.min(0.80, (o.postflopNarrow != null ? o.postflopNarrow : (vpip || 0.50) * 0.7)));
    };
    const frac = fracFor();
    let cum = 0;
    const total = CLASSES.reduce((s, c, i) => s + CLASS_COMBOS[c].length, 0);
    for (const i of order) {
      const share = CLASS_COMBOS[CLASSES[i]].length / total;
      if (cum < frac) w[i] = 1; else w[i] = 0;
      cum += share;
    }
    return w;
  };

  const buildOppTablesDom = (hole, board, ctx) => {
    const o = ctx || {};
    const nOpp = Math.max(1, o.opponents | 0);
    const blocked = new Set(hole.concat(board));
    const tables = [];
    const oppPlayers = [];
    try {
      const me = (typeof findOwnSeat === 'function') ? findOwnSeat() : null;
      const seats = (typeof getAllSeats === 'function') ? getAllSeats() : [];
      for (const seat of seats) {
        if (!seat) continue;
        if (me && (seat === me || seat.contains(me) || me.contains(seat))) continue;
        if (!(typeof isOpponentActive === 'function' && isOpponentActive(seat))) continue;
        const player = (typeof getPlayerName === 'function') ? getPlayerName(seat) : null;
        if (player && player.id) oppPlayers.push(player);
      }
    } catch (e) { }
    for (const player of oppPlayers.slice(0, nOpp)) {
      const w = rangeWeightsDom(player.id, { raiseLevel: o.raiseLevel || 0, street: (o.street || 'Preflop').toLowerCase() });
      tables.push(buildComboTable(w, blocked));
    }
    while (tables.length < nOpp) {
      const w = new Float64Array(CLASSES.length).fill(1);
      tables.push(buildComboTable(w, blocked));
    }
    return tables.slice(0, nOpp);
  };

  const buildComboTable = (weights, blockedSet) => {
    const combos = [], cums = [];
    let acc = 0;
    for (let i = 0; i < CLASSES.length; i++) {
      const wgt = weights[i];
      if (wgt <= 0) continue;
      for (const c of CLASS_COMBOS[CLASSES[i]]) {
        if (blockedSet.has(c.slice(0, 2)) || blockedSet.has(c.slice(2, 4))) continue;
        acc += wgt; cums.push(acc); combos.push(c);
      }
    }
    return { combos, cums, total: acc };
  };
  const sampleCombo = (table, rnd) => {
    if (!table.combos.length || table.total <= 0) return null;
    const r = rnd() * table.total;
    let lo = 0, hi = table.cums.length - 1;
    while (lo < hi) { const mid = (lo + hi) >> 1; if (table.cums[mid] < r) lo = mid + 1; else hi = mid; }
    return table.combos[lo];
  };

  const rngV6 = (() => {
    let s = (Date.now() ^ 0x6d2b79f5) >>> 0 || 1;
    const fn = () => { let x = s; x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; s = x; return x / 4294967296; };
    fn.seed = (v) => { s = (v >>> 0) || 1; };
    return fn;
  })();
  const mcEquityCombo = (hole, board, oppTables, jobId, opts) => new Promise((resolve) => {
    const o = Object.assign({}, V6_DEFAULTS, opts || {});
    if (Number.isFinite(o.seed)) rngV6.seed(o.seed);
    const onProgress = typeof o.onProgress === 'function' ? o.onProgress : null;
    const holeIdx = hole.map((c) => CARD_IDX[c]);
    const boardIdx = board.map((c) => CARD_IDX[c]);
    const dead = new Set(holeIdx.concat(boardIdx));
    const baseDeck = [];
    for (let c = 0; c < 52; c++) if (!dead.has(c)) baseDeck.push(c);
    const boardNeeded = Math.max(0, 5 - board.length);
    const my7 = new Uint8Array(7), opp7 = new Uint8Array(7);
    my7[0] = holeIdx[0]; my7[1] = holeIdx[1];
    for (let b = 0; b < boardIdx.length; b++) my7[2 + b] = boardIdx[b];
    const cancelled = () => (typeof mcJobId !== 'undefined' ? mcJobId !== jobId : false);
    let runs = 0, sum = 0, sumSq = 0, wins = 0, ties = 0, losses = 0;
    const typeCounts = new Array(10).fill(0);
    const t0 = Date.now();
    let lastProg = 0;
    const deck = new Uint8Array(52);
    const blocked = new Set(hole.concat(board));
    const chunk = () => {
      if (cancelled()) { resolve(null); return; }
      const sliceStart = Date.now();
      let iters = Math.min(4000, o.maxSamples - runs);
      for (let i = 0; i < iters; i++) {
        let liveCount = 0;
        for (let d = 0; d < baseDeck.length; d++) deck[liveCount++] = baseDeck[d];
        const took = new Set();
        let ok = true;
        const oppHole = [];
        for (let oi = 0; oi < oppTables.length; oi++) {
          let got = null;
          for (let attempt = 0; attempt < 40; attempt++) {
            const combo = sampleCombo(oppTables[oi], rngV6);
            if (!combo) { got = null; break; }
            if (took.has(combo[0] + combo[1]) || took.has(combo[2] + combo[3])) continue;
            got = combo; break;
          }
          if (!got) { ok = false; break; }
          took.add(got[0] + got[1]); took.add(got[2] + got[3]);
          oppHole.push([CARD_IDX[got[0] + got[1]], CARD_IDX[got[2] + got[3]]]);
        }
        if (!ok) { continue; }
        for (let oi = 0; oi < oppHole.length; oi++) for (let ci = 0; ci < 2; ci++) {
          const cv = oppHole[oi][ci];
          for (let p = 0; p < liveCount; p++) { if (deck[p] === cv) { liveCount--; deck[p] = deck[liveCount]; break; } }
        }
        for (let b = 0; b < boardNeeded; b++) {
          const idx = (rngV6() * liveCount) | 0;
          my7[2 + board.length + b] = deck[idx];
          liveCount--; deck[idx] = deck[liveCount];
        }
        const myScore = evalFastIdx(my7, 7);
        typeCounts[myScore >> 20]++;
        for (let b = 0; b < 5; b++) opp7[2 + b] = my7[2 + b];
        let won = true, tied = 1;
        for (let oi = 0; oi < oppHole.length; oi++) {
          opp7[0] = oppHole[oi][0]; opp7[1] = oppHole[oi][1];
          const s = evalFastIdx(opp7, 7);
          if (s > myScore) { won = false; break; }
          if (s === myScore) tied++;
        }
        if (won) { const share = tied === 1 ? 1 : 1 / tied; sum += share; sumSq += share * share; }
        if (!won) losses++; else if (tied > 1) ties++; else wins++;
      }
      runs += iters;
      const now = Date.now();
      const eq = runs > 0 ? sum / runs : 0;
      const ci = varianceCI(sum, sumSq, runs);
      const half = (ci.upper - ci.lower) / 2;
      const snap = {
        equity: eq, ci, samples: runs,
        typeDist: typeCounts.map((c) => c / Math.max(1, runs)),
        winCount: wins, tieCount: ties, lossCount: losses
      };
      if (onProgress && runs - lastProg >= 5000 && runs >= 5000 && runs < o.maxSamples) { lastProg = runs; onProgress(snap); }
      if ((runs >= o.minSamples && half <= o.targetHalfWidth) || runs >= o.maxSamples || now - t0 >= o.deadlineMs || now - sliceStart > 500) {
        resolve(Object.assign(snap, { method: 'monte-carlo-combo', workers: 0, elapsedMs: now - t0, targetReached: half <= o.targetHalfWidth }));
        return;
      }
      setTimeout(chunk, 0);
    };
    setTimeout(chunk, 0);
  });



  const runExactHU = (hole, board, jobId) => {
    const holeIdx = hole.map((c) => CARD_IDX[c]);
    const boardIdx = board.map((c) => CARD_IDX[c]);
    const dead = new Set(holeIdx.concat(boardIdx));
    const deck = [];
    for (let c = 0; c < 52; c++) if (!dead.has(c)) deck.push(c);
    const my7 = new Uint8Array(7), opp7 = new Uint8Array(7);
    my7[0] = holeIdx[0]; my7[1] = holeIdx[1];
    for (let b = 0; b < boardIdx.length; b++) my7[2 + b] = boardIdx[b];
    let runs = 0, sum = 0, sumSq = 0, wins = 0, ties = 0, losses = 0;
    const typeCounts = new Array(10).fill(0);
    const riverCount = board.length === 4 ? deck.length : 0;
    for (let i = 0; i < deck.length; i++) {
      for (let j = i + 1; j < deck.length; j++) {
        let settle = false;
        for (let rb = 0; rb <= riverCount && !settle; rb++) {
          if (riverCount && rb === riverCount) break;
          const riverCard = riverCount ? deck[rb] : -1;
          if (riverCard === deck[i] || riverCard === deck[j]) continue;
          if (riverCount) my7[6] = riverCard;
          const myScore = evalFastIdx(my7, 7);
          typeCounts[myScore >> 20]++;
          opp7[0] = deck[i]; opp7[1] = deck[j];
          for (let b = 0; b < 5; b++) opp7[2 + b] = my7[2 + b];
          const os = evalFastIdx(opp7, 7);
          runs++;
          if (myScore > os) { sum += 1; sumSq += 1; wins++; }
          else if (myScore === os) { sum += 0.5; sumSq += 0.25; ties++; }
          else losses++;
          if (runs >= 400000) settle = true;
        }
      }
      if (runs >= 400000) break;
    }
    return {
      equity: runs > 0 ? sum / runs : 0, ci: varianceCI(sum, sumSq, runs),
      typeDist: typeCounts.map((c) => c / Math.max(1, runs)),
      samples: runs, winCount: wins, tieCount: ties, lossCount: losses,
      method: board.length === 5 ? 'exact-river' : 'exact-turn', workers: 0,
      elapsedMs: 0, targetReached: true
    };
  };



  const BET_SIZES = [0.33, 0.5, 0.75, 1.0];
  const legalBetRange = (ctx) => {
    const { toCall, effStack, actionBtns } = ctx;
    const out = { min: null, max: null, canRaise: false, source: 'none' };
    const betFloor = (ctx.betFloor > 0) ? ctx.betFloor : 0;
    if (betFloor > 0) {
      out.min = betFloor; out.source = 'bet input (DOM)';
    } else if (toCall > 0) {
      out.min = 2 * toCall; out.source = 'derived-full-raise';
    } else if (hero && typeof hero.betAmount === 'number' && hero.betAmount > 0) {
      out.min = 2 * hero.betAmount; out.source = 'derived-open';
    } else if (hero && typeof hero.pot === 'number' && hero.pot > 0) {
      out.min = 2 * hero.pot; out.source = 'derived-committed';
    }
    const afford = (typeof ctx.money === 'number' && ctx.money >= 0) ? ctx.money : effStack;
    const cap = (out.max !== null && Number.isFinite(out.max)) ? Math.min(out.max, afford) : afford;
    out.max = cap;
    const hasAggrBtn = !!(actionBtns && (actionBtns.hasRaise || actionBtns.hasBet));
    if (out.min !== null) {
      out.canRaise = hasAggrBtn;
      if (out.canRaise && out.min > cap) {
        out.canRaise = false;
        out.allInOnly = true;
      }
    } else if (hasAggrBtn) {
      out.canRaise = true;
    }
    return out;
  };
  const clampRaiseTo = (target, legal) => {
    if (legal.min === null) return { size: target, legal: false, note: 'unverified: no server minimum in frame' };
    if (target >= legal.min) return { size: Math.min(target, legal.max), legal: true, note: '' };
    if (legal.allInOnly || legal.min > legal.max) {
      return { size: legal.max, legal: true, allIn: true, note: 'below minimum: all-in is the only legal raise' };
    }
    return { size: legal.min, legal: true, note: `lifted to the $${legal.min.toLocaleString()} minimum` };
  };
  const evDecide = (ctx) => {
    const { equity: eq, pot, toCall, effStack, opponents, street, position, actionBtns } = ctx;
    if (typeof eq !== 'number' || !(pot > 0) || !(effStack > 0)) return null;
    const out = { actions: [], assumptions: [], best: null, eqRaw: eq };
    const feStat = ctx.oppFoldStat;
    const foldEqFor = (fracOfPot) => {
      if (feStat && feStat.n >= 8) {
        const base = feStat.rate;
        const scale = 0.7 + 0.6 * fracOfPot;
        return Math.max(0.05, Math.min(0.9, base * scale));
      }
      out.assumptions.push('fold probability: population estimate ~45% (HU single bet); no reliable stat');
      return Math.max(0.05, Math.min(0.85, 0.45 * (0.7 + 0.6 * fracOfPot) * (opponents === 1 ? 1 : Math.pow(0.55, opponents - 1))));
    };
    out.actions.push({ action: 'fold', ev: 0, note: 'give up the pot; already-committed money is sunk' });
    if (!(toCall > 0)) {
      out.actions.push({ action: 'check', ev: eq * pot, note: 'see the next card; assumes no free-card loss', assumption: 'no bet behind (checked through)' });
    }
    if (toCall > 0) {
      const potOdds = toCall / (pot + toCall);
      const callEv = eq * (pot + toCall) - toCall;
      out.actions.push({
        action: 'call', ev: callEv, requiredEquity: potOdds,
        note: `needs ${(potOdds * 100).toFixed(1)}% vs ${(eq * 100).toFixed(1)}% raw equity`,
        assumption: 'one-street model: no future betting after the call'
      });
    }
    const legal = legalBetRange(ctx);
    const canAggr = legal.canRaise;
    if (legal.source === 'derived-full-raise' || legal.source === 'derived-open' || legal.source === 'derived-committed') {
      out.assumptions.push('raise floor derived from the last full bet (server minimum not in frame)');
    } else if (legal.source === 'none' && canAggr) {
      out.assumptions.push('no verified minimum in frame: raise sizes are estimates, not legal floors');
    }
    if (legal.allInOnly) {
      out.assumptions.push('stack cannot cover the minimum raise: all-in replaces every sized raise');
    }
    if (canAggr) {
      for (const frac of BET_SIZES) {
        const investRaw = Math.round(pot * frac);
        const clamped = clampRaiseTo(investRaw, legal);
        if (clamped.size <= 0) continue;
        const invest = Math.min(effStack, Math.max(clamped.size, 1));
        const allIn = invest >= effStack || !!clamped.allIn;
        const fe = foldEqFor(frac);
        const evWhenFold = fe * (pot + (toCall > 0 ? toCall : 0));
        const winPot = pot + (toCall > 0 ? toCall : 0) + 2 * invest;
        const eqCalled = ctx.eqCalled != null ? ctx.eqCalled : Math.max(0, eq - 0.08);
        if (ctx.eqCalled == null) out.assumptions.push('equity-when-called: raw equity -8pp (no continue-range simulation available)');
        const evCalled = eqCalled * winPot - invest;
        const ev = evWhenFold + (1 - fe) * evCalled;
        out.actions.push({
          action: allIn ? 'all-in' : (toCall > 0 ? 'raise' : 'bet'),
          size: invest, ev, fe, eqCalled,
          note: `${allIn ? 'all-in' : (toCall > 0 ? 'raise to' : 'bet')} $${invest.toLocaleString()} (${Math.round(frac * 100)}% pot)${clamped.note ? ' · ' + clamped.note : ''}`,
          assumption: `folds ${Math.round(fe * 100)}% (estimate)`
        });
        if (allIn) break;
      }
    }
    out.actions.sort((a, b) => b.ev - a.ev);
    out.best = out.actions[0] || null;
    const second = out.actions[1];
    out.margin = second ? out.best.ev - second.ev : null;
    if (ctx.equityCI && out.best) {
      const width = (ctx.equityCI.upper - ctx.equityCI.lower) / 2;
      out.ciStable = out.margin === null ? null : out.margin > width * (pot + 2 * effStack) * 0.5;
    }
    return out;
  };


  const diagnostics = () => ({
    storage: DB.ok ? 'indexeddb open' : ('indexeddb issue: ' + (DB.lastError || 'unavailable')),
    domPipeline: 'visible DOM only',
    netHooks: 'none'
  });

  const BOOT = { pollMs: 250, maxAttempts: 240, attempts: 0, done: false, failed: false };
  const boot = (initFn) => {
    if (BOOT.done) return;
    const isHoldemRoute = () => {
      try {
        if (typeof location === 'undefined') return false;
        const p = new URLSearchParams(location.search || '');
        return (p.get('sid') || '').toLowerCase() === 'holdem';
      } catch (e) { return false; }
    };
    const tick = () => {
      if (BOOT.done) return;
      BOOT.attempts++;
      const ready = (isHoldemRoute() || (typeof isHoldemSurface === 'function' && isHoldemSurface()))
        && document.body && (typeof isHoldemSurface === 'function' && isHoldemSurface() || document.querySelector('#react-root, [class*="holdem"]'));
      if (ready || BOOT.attempts >= BOOT.maxAttempts) {
        BOOT.done = true;
        BOOT.failed = !ready;
        if (BOOT.failed) twarn('[TNP] v6 boot: poker surface not detected after ' + (BOOT.attempts * BOOT.pollMs / 1000) + 's; initialising anyway (HUD will show paused until the table appears).');
        if (document.body) initFn();
        else {
          const w = setInterval(() => { if (document.body) { clearInterval(w); initFn(); } }, 50);
          setTimeout(() => clearInterval(w), 10000);
        }
        return;
      }
      setTimeout(tick, BOOT.pollMs);
    };
    tick();
  };



  const testApi = () => ({
    V6_DEFAULTS, CLASSES, CLASS_COMBOS,
    rangeWeightsDom, buildComboTable, sampleCombo, rngV6, mcEquityCombo,
    evDecide, legalBetRange, clampRaiseTo, buildOppTablesDom, runExactHU,
    diagnostics, boot,
    putKv, getKv, deleteKv, storageReady, clearIdbData,
    migrateLocalStorageToIdb, persistHand, persistHandRecord
  });

  const persistHandRecord = async (record) => {
    if (!record || !record.id) return false;
    try { return await persistHand(record); } catch (e) { return false; }
  };

  const storageReady = async () => {
    const db = await openDb();
    return !!db;
  };

  const clearIdbData = async () => {
    const db = await openDb(); if (!db) return false;
    let ok = true;
    try {
      const r = await idbOp('kv', 'readwrite', (st) => { st.clear(); });
      if (!r || !r.ok) ok = false;
    } catch (e) { ok = false; }
    try {
      const r2 = await idbOp('hands', 'readwrite', (st) => { st.clear(); });
      if (!r2 || !r2.ok) ok = false;
    } catch (e) { ok = false; }
    return ok;
  };


  return {
    buildOppTablesDom, evDecide, legalBetRange, clampRaiseTo,
    diagnostics, boot, testApi,
    migrateLegacy, migrateLocalStorageToIdb, persistHand, persistHandRecord,
    putKv, getKv, deleteKv, clearIdbData, storageReady
  };
})();

  const init = () => {
    if (initStarted) return;
    initStarted = true;
    injectCSS();
    installPerfWatch();

    window.addEventListener('popstate', reconcileRoute);
    window.addEventListener('hashchange', reconcileRoute);

    void loadReplayLog();
    void loadDrillScore();

    window.addEventListener('storage', (e) => {
      if (e.key !== PROFILES_KEY || !e.newValue) return;
      if (e.newValue === lastProfilesJsonWritten) return;
      try {
        const incoming = JSON.parse(e.newValue);
        const { merged, changed } = mergeIncomingProfiles(profiles, incoming);
        if (changed > 0) {
          profiles = merged;
          tinfo(`[TNP] merged ${changed} profile row${changed === 1 ? '' : 's'} from another tab`);
          if (runtimeActive && (activeTab === 'opponents' || activeTab === 'you')) renderUI();
        }
      } catch {  }
    });
    routeInterval = setInterval(reconcileRoute, 750);
    reconcileRoute();

    void (async () => {
      try {
        await storage.loadPdaOverlay();
        await TNP6.migrateLegacy();
        idbPrimary = await TNP6.storageReady() === true;
        if (idbPrimary) {
          try {
            const mig = await TNP6.migrateLocalStorageToIdb();
            if (mig && mig.migrated > 0) {
              tinfo(`[TNP] Storage: migrated ${mig.migrated} localStorage segment(s) into IndexedDB; localStorage now keeps settings only.`);
            }
          } catch (migErr) {
            twarn('[TNP] localStorage→IndexedDB migration skipped:', migErr?.message || migErr);
          }
          const fromIdb = async (key, apply) => {
            try {
              const raw = await TNP6.getKv('tnp_' + key);
              if (raw === null || raw === undefined) return;
              const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
              apply(parsed);
            } catch { }
          };
          await fromIdb(STORAGE_KEYS.profiles, (v) => { const r = loadProfilesFrom(v); if (Object.keys(r).length) profiles = r; });
          await fromIdb(STORAGE_KEYS.notes, (v) => { const r = normalizeNotes(v); if (Object.keys(r).length) playerNotes = r; });
          await fromIdb(STORAGE_KEYS.hero, (v) => { const r = normalizeHeroStats(v); if (r.hands > 0) heroStats = r; });
          await fromIdb(STORAGE_KEYS.lifetime, (v) => { lifetime = normalizeLifetime(v); });
          await fromIdb(STORAGE_KEYS.bankroll, (v) => { bankroll = normalizeBankrollState(v); });
          await fromIdb(STORAGE_KEYS.session, (v) => { if (restoreSavedSession(v)) bootSessionRestored = true; });
        }

                                try {
          if (!Object.keys(profiles).length) {
            const raw = await TNP6.getKv('mirror_' + PROFILES_KEY);
            if (raw) {
              const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
              const restored = loadProfilesFrom(parsed);
              if (Object.keys(restored).length) {
                profiles = restored;
                tinfo(`[TNP] Mirror: restored ${Object.keys(restored).length} opponent profile(s) from IndexedDB (localStorage copy was empty).`);
                saveProfiles();
              }
            }
          }
          if (!heroStats || !heroStats.hands) {
            const raw = await TNP6.getKv('mirror_' + HERO_STATS_KEY);
            if (raw) {
              const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
              const restored = normalizeHeroStats(parsed);
              if (restored.hands > 0) {
                heroStats = restored;
                tinfo(`[TNP] Mirror: restored your self profile (${restored.hands} hands) from IndexedDB (localStorage copy was empty).`);
                saveHeroStats();
              }
            }
          }
          if (!Object.keys(playerNotes).length) {
            const raw = await TNP6.getKv('mirror_' + NOTES_KEY);
            if (raw) {
              const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
              const restored = normalizeNotes(parsed);
              if (Object.keys(restored).length) {
                playerNotes = restored;
                tinfo(`[TNP] Mirror: restored ${Object.keys(restored).length} note(s) from IndexedDB (localStorage copy was empty).`);
                saveNotes();
              }
            }
          }
        } catch (mirrorErr) {
          twarn('[TNP] Mirror restore skipped:', mirrorErr?.message || mirrorErr);
        }

        if (!bootSessionRestored) resetProfileSessionCounters();

        pruneProfiles();

        sweepQuarantine();
        if (sweptProfileRows > 0) {
          tinfo(`[TNP] Profiles: removed ${sweptProfileRows} invalid or phantom row(s) on load.`);
          saveProfiles();
        }
        renderDataLifecycleCards();
        if (runtimeActive) { applyDisplayMode(); applyVisualSettings(); renderUI(); }
      } catch (err) {
        twarn('[TNP] Storage hydration issue (continuing in memory):', err?.message || err);
      }
    })();

    tlog(`[TNP] v${SCRIPT_VERSION} loaded (PDA=${isMobile()}, storage=${storage.backendName()})`);
  };

  if (typeof window !== 'undefined' && window.__TNP_TEST__) {
    window.__TNP_TEST__.expose({
      SCRIPT_VERSION,

      RANKS, SUITS, RANK_VALS, parseCardFromText, extractCardString,
      evaluateHand, evalFastIdx, CARD_STR, CARD_IDX,
      preflopScore, preflopTopFraction, getPreflopIntent, OPEN_THRESHOLDS,
      analyzeOutsCards, nextCardImprovement, riverImprovementOdds,
      afOf, afLabelOf, MIN_AF_ACTIONS, computeEffectiveStack, textForIntent,
      sessionVariance, bankrollRiskRead, getRangeThreshold,
      scenarioSeed, MC_MANDATE, mcTargetsNow, runMonteCarlo, runEquityJob, runMandatedEquity, MC_WORKER_SRC,
      equityCacheKey, equityFinalCache, provenanceReport, provenanceSummary, provSet, sessionAwardSeenAtRead: () => sessionAwardSeenAt,
      readTableArtSlug, tableFromArtSlug, tableKeyOf, TABLE_BY_KEY,
      potOddsRequired: (toCall, pot) => (toCall > 0 && pot > 0) ? toCall / (pot + toCall) : 0,

      analyzeBoardTexture, boardDanger, boardRisk, boardThreatExtras, calculateOuts, analyzeOutsDetail,
      classifyDraws, outsSummary, equityImprovingOuts, OUTS_WORKER_SRC, outsWorkerRequest, terminateOutsWorker,
      replayRecord, replayAttachAdvice, archiveReplayHand, counterfactualEv, replayMoveHand, replayStepTo, persistReplayLog,
      generateDrill, drillValidate, drillDecision, drillNew, drillAnswer, drillEquity,
      buildDiagnosticsReport, renderDiagnosticsPanel, renderReplayPanel, renderDrillPanel,
      integrityRead, decisionCalibration, tagDecisionOutcomes,
      perfWatchRead: () => ({ ...perfWatch }),
      activityRead: () => ({ ...activity }),
      activitySet: (patch) => { Object.assign(activity, patch || {}); },
      replayState: () => ({ log: replayLog, current: replayCurrent, cursor: replayCursor, streetCursor: replayStreetCursor }),
      drillStateRead: () => ({ active: drillState.active, answered: drillState.answered, score: { ...drillState.score } }),
      freshSessionDirect: freshSession, sessionSavedStateDirect: sessionSavedState, restoreSavedSessionDirect: restoreSavedSession,
      resetForNewHandDirect: resetForNewHand, resetProfileSessionCountersDirect: resetProfileSessionCounters,
      recordDecisionDirect: recordDecision, sparklineSvgDirect: sparklineSvg, barSparkSvgDirect: barSparkSvg,
      positionFromDistanceDirect: positionFromDistance, evOptionsDirect: evOptions, crossCheckReadsDirect: crossCheckReads,
      parseHoleCardsDirect: parseHoleCards, parseBoardCardsDirect: parseBoardCards, isOwnMutationDirect: isOwnMutation,
      evaluateRelativeStrength, detectBlockers,

      parseActionMessage, playerKey, samePlayer, parseTornNumber,
      normalizeLogText, logLineIsAction, collectLogTexts, extractNodeTexts,
      currentHandEvents, riverFacesFromEvents, firstInStats,
      positionFromBlindPosts, raiseContextFromMessages, handSignature,
      heroLedgerFromMessages, classifyButtonAction, isPreActionButton,

      getRecommendation, getBetSizingAdvice, narrowRangeFraction,
      classifyPlayer, getProfileMetrics, getHeroMetrics,
      mdfVsBet, callEv, eqrFactor, geometricBetFraction, sprVsPot,
      bluffBreakEven, riverOverfoldRead, overfoldSizingText, ruleOfFourTwo,
      varianceCI, wilsonCI, netStackTransition, bankrollAdvice, tiltCheck,
      estimateHandScore, sampleConfidence, decayFactor, smoothedRate,
      profileTier, isPlausiblePlayerName, normalizeProfiles,
      afqRate, MIN_AFQ_POSTFLOP_ACTIONS, mergeMcPartials, runExactEquity,
      lastPreflopAggressor, buildPreflopOppSummary, TABLE_CATALOG, RANGE_CHARTS,
      PREFLOP_EQUITY_169,
      normalizeHeroStats, heroLedgerView, getSelfLeaks,
      STRATEGY_PROFILES, strategyProfile, heatRead, readSrSummary, buildDebugState,
      mergeIncomingProfiles, applyBackupData,

      identifyTable, parseLobbySpeed, parseLobbyAria, parseLobbyPlayersCell,
      lobbyHeaderScore,
      STORAGE_BUDGETS, NOTES_MAX_ROWS, storageBudgetReport,

            _testDom: {
        isChatMessageRow, insideChatMessageRow, insideLogFeed,
        scanAllSeats, getAllSeats, getPlayerName, findOwnSeat, isOwnPlayerSeat,
        countActiveOpponents, isOpponentActive, isSeatEmpty, isSeatSittingOut, isSeatInHand,
        getBoardCardElements, getBoardCardsRoot, parseBoardCards, parseHoleCards,
        getHoleCardElements, renderHoleCardsRow, renderBoardRow, domCardHtml,
        renderDecisionBlock, renderOpponentsPanel, renderUI, renderSessionPanel, renderMirrorPanel,
        renderOutsChips, renderReplayPanel, renderDrillPanel, renderDiagnosticsPanel,
        switchTabByName: switchTab,
        replayAttachAdviceDirect: replayAttachAdvice,
        get isMinimized() { return isMinimized; },
        get dragPos() { return dragPos; },
        get lastRecAt() { return lastRecAt; },
        get lastComputeMs() { return lastComputeMs; },
        get observerLastMutationAt() { return observerLastMutationAt; },
        get replayLogLen() { return replayLog.length; },
        updateMobileModeDirect: updateMobileMode,
        initObserverDirect: initObserver,
        get runtimeObserverAlive() { return !!runtimeObserver; },
        get runtimeActive() { return runtimeActive; },
        detectPosition, readPot, readToCall, getActiveActionButtons, computeState, syncSessionStack, isHeroTurn,
        buildParserReport, LOG_FEED_CONTAINER_SEL,
        buildUI, cleanupRuntime, renderSeatBadges, switchTab,
        processHandActions,
        get activeTab() { return activeTab; },
        get mcJobId() { return mcJobId; },
        set mcJobId(v) { mcJobId = v; },
        resetCaches: () => {
          _seatsScanCache = { at: 0, seats: null };
          _ownSeatCache = { at: 0, seat: null, has: false };
          _boardRootCache = { at: 0, root: null };
          cachedHeroIdentity = null;
          cachedPageHeroIdentity = null;
          _tableArtCache = { at: 0, slug: null };
        },
        get gameState() { return gameState; },
        get settings() { return settings; },
        set settings(v) { settings = v; },
        get profiles() { return profiles; },
        set profiles(v) { profiles = v; },
        get heroStats() { return heroStats; },
        set heroStats(v) { heroStats = v; },
        get session() { return session; },
        set session(v) { session = v; },
        get pipelineStats() { return pipelineStats; }
      },
      _testIdentity: {
        scanLobby, observeTableIdentity, onLobbyClick, resolveTableIdentity, tableIdentityDebug,
        findLobbyTables, dropTableIdentity,
        state: () => ({ ...tableIdentityState }),
        clear: () => {
          tableIdentityState.mode = 'none';
          tableIdentityState.name = '';
          tableIdentityState.seats = 0;
          tableIdentityState.source = '';
          tableIdentityState.wsTableId = null;
          pendingJoin = null;
          stakesMismatchCount = 0;
          lastGoodLobbyTable = null;
          session.capacityHint = 0;
          _tableArtCache = { at: 0, slug: null };
        }
      },
      v6: TNP6.testApi(),
      _testStorage: {
        safeSetItem, emergencyShrink, enforceCategoryBudget, queueSave, flushSave,
        pruneProfilesToBytes, trimNotesToBytes, sweepQuarantine, STORAGE_MIRROR_CATEGORIES,
        get profiles() { return profiles; },
        set profiles(v) { profiles = v; },
        get playerNotes() { return playerNotes; },
        set playerNotes(v) { playerNotes = v; },
        report: () => ({ degraded: Array.from(storageState.degraded), shrinks: storageState.shrinks, bytes: { ...storageState.bytes } })
      }
    });
  }
  TNP6.boot(init);
})();