// Troko — VENUE-MANAGER (VM) surface · shared base
// The surface a person uses to RUN a centre: see all batches/coaches/athletes,
// manage schedule + enrollment, and (gated) revenue + per-centre pricing.
//
// PALETTE: catalogue-WARM, not the grey operator console. Bone/paper surfaces,
// an INK command sidebar with LIME accents — the same person-centric product
// as the coach app, one notch more "command". Reuses coach/account atoms
// (Avatar, BatchGlyph, Ring, Icon, XIcon, Eyebrow, CourtBg).
//
// ROLE MODEL (shapes everything): Manager and Coach are independent grants
// that compose per-centre. A {manager}-only person sees centre-wide oversight
// + assignment, but NEVER a personal coaching workspace. The role×centre
// switcher reveals coaching tabs only where a coach grant exists.

// IST-locked time-of-day greeting. Troko runs on India time — a viewer on a device
// set to another timezone (or a surface that hardcoded one part of day) must NOT
// mis-greet. Called at render, so it is always defined by then regardless of load order.
function greetIST(name) {
  var h;
  try { h = parseInt(new Date().toLocaleString('en-GB', { timeZone: 'Asia/Kolkata', hour: '2-digit', hour12: false }), 10); }
  catch (e) { h = new Date().getHours(); }
  if (!(h >= 0 && h <= 23)) h = new Date().getHours();
  var part = h < 12 ? 'Good morning' : (h < 17 ? 'Good afternoon' : 'Good evening');
  return part + (name ? ', ' + name : '');
}

const { useState: useVMState } = React;

// ── The person + their grants (person_role_scope) ──
//   {coach@BBPS, manager@KNC} — manages KNC, coaches at BBPS (different centres)
// venue-login: VM_PERSON/GRANTS/CENTRE/COACHES/BATCHES are `let` so the live
// canonical data layer can replace these mocks via window.VMStore.set before the
// VM screens render — the screens read these globals at render time (zero edits).
// NEUTRAL DEFAULTS ONLY — never a real academy's name/numbers. The canonical loader
// (loadVMContext → VMStore.set) overwrites all of these from session + /roster before the
// screens matter; if that load ever fails, a generic placeholder is honest, a stranger's
// centre is not. (A hardcoded "KNC Basecamp" leaked into the topbar chip once — see fix 744d6a1.)
let VM_PERSON = { name: 'Manager', initials: 'M' };
let VM_GRANTS = [
  { centre: 'Your centre', area: '', roles: ['manager'], current: true },
];

// ── The managed centre, at a glance ──
let VM_CENTRE = { name: 'Your centre', area: '', courts: 0, coaches: 0, batches: 0, athletes: 0 };

// ── Centre-wide coaches (a VM sees ALL, not just one) ──
let VM_COACHES = [
  { id: 'vikram', name: 'Vikram Rao',  sport: 'cricket',   batches: 3, athletes: 32, tint: 'lime',   today: true },
  { id: 'sofia',  name: 'Sofia Reyes', sport: 'football',  batches: 2, athletes: 28, tint: 'orange', today: true },
  { id: 'anjali', name: 'Anjali Nair', sport: 'badminton', batches: 1, athletes: 14, tint: 'ink',    today: false },
  { id: 'imran',  name: 'Imran Qureshi', sport: 'cricket', batches: 0, athletes: 0,  tint: 'lime',   today: false, unassigned: true },
];

// ── Centre-wide batches (every batch, across coaches) ──
let VM_BATCHES = [
  { id: 'u10c',  name: 'U-10 Beginner',       sport: 'cricket',   coach: 'Vikram Rao',  days: 'Mon · Wed · Fri', time: '5:00 PM', court: 'Net 1',   fill: 12, cap: 14, today: true },
  { id: 'u14c',  name: 'U-14 Intermediate',   sport: 'cricket',   coach: 'Vikram Rao',  days: 'Tue · Thu · Sat', time: '6:30 PM', court: 'Net 2',   fill: 10, cap: 12, today: false },
  { id: 'camp',  name: 'Saturday Skills Camp',sport: 'cricket',   coach: 'Vikram Rao',  days: 'Saturday',        time: '8:00 AM', court: 'Ground',  fill: 8,  cap: 16, today: false },
  { id: 'u12f',  name: 'U-12 Football',       sport: 'football',  coach: 'Sofia Reyes', days: 'Mon · Wed · Fri', time: '5:00 PM', court: 'Turf',    fill: 16, cap: 18, today: true },
  { id: 'u16f',  name: 'U-16 Football',       sport: 'football',  coach: 'Sofia Reyes', days: 'Tue · Thu',       time: '6:30 PM', court: 'Turf',    fill: 12, cap: 18, today: false },
  { id: 'badm',  name: 'Badminton Beginners', sport: 'badminton', coach: 'Anjali Nair', days: 'Mon · Thu',       time: '4:00 PM', court: 'Court 3', fill: 14, cap: 14, today: true },
];

// ── Nav model — Operations (live) + Commercial (gated) ──
// Task-grouped nav (2026-08-31 restructure). The old 13-item "Operations" dump is
// split into Today / Coaching / Team & time / Set up so a first-run VM can find a
// job by its name. Routes (2nd field) are UNCHANGED — screens are untouched; only
// grouping, order and labels move. `agent:true` marks the group the calling-desk
// (agentMode) shows — it replaces the old hard-coded group==='CRM' filter.
// Recall switch for the RETIRED VM copy of Reconciliation. The canonical one is the
// Business Office at /office: reconciliation is tenant-wide finance work, most of the
// money arrives naming no centre at all, and persona routing sends the finance lead
// there — so a copy here was a screen she could never open. Checked before retiring:
// the finance grant is held by one person, she lands on /office, and nobody holds both
// finance and venue_manager.
//
// NOTHING IS DELETED. The screens still load and /venue/#/reconcile still mounts; only
// the nav entry is hidden, so a venue manager later given a finance grant can be put
// back on it without a deploy:
//
//     recall  →  /venue/?vmreconcile=1   (sticks, per browser)
//     release →  /venue/?vmreconcile=0
//
// Delete the files for real once the office surface has been used in anger for a while.
const VM_RECONCILE = (function () {
  try {
    var q = new URLSearchParams(window.location.search);
    var v = q.get('vmreconcile');
    if (v === '1') localStorage.setItem('troko_vm_reconcile', '1');
    if (v === '0') localStorage.removeItem('troko_vm_reconcile');
    return localStorage.getItem('troko_vm_reconcile') === '1';
  } catch (e) { return false; }
})();

const VM_NAV = [
  { group: 'Today', items: [
    ['M1', 'overview',   'Overview',          'grid'],
    ['S6', 'approvals',  'Approvals & tasks', 'calCheck'],
    // Comms lives in Today because it is the needs-me surface, not a setup screen.
    ['C6', 'messages',   'Comms',             'message'],
  ]},
  { group: 'Coaching', items: [
    ['M2', 'batches',    'Batches',           'users'],
    // Coach groups (M499): children who pay and have no coach; give them to coaches (vm-overview.jsx VMNoCoach).
    ['M2c','nocoach',    'No coach',          'users'],
    ['M3', 'coaches',    'Coaches',           'whistle'],
    ['M3b','coachpages', 'Coach pages',       'whistle'],   // M381 — review + publish coaches' public pages
    ['M3c','personal',   'Personal coaching', 'spark'],     // M378–M380 — where it is permitted (super admin flips)
    ['M4', 'schedule',   'Schedule',          'cal'],
    ['M4b','classes',    'Classes',           'calCheck'],
    ['M5', 'attendance', 'Attendance',        'calCheck'],
    // Manager/exception path (offline/import/bulk/reassignment); online buys auto-place.
    ['M6', 'enroll',     'Enroll / reassign', 'add'],
  ]},
  { group: 'Team & time', items: [
    ['M5a','myteam',     'My team',           'whistle'],
    ['M5b','coachshifts','Coach shifts',      'pin'],
    ['M5d','staffhours', 'Staff hours',       'calCheck'],
    ['M5e','cleaning',   'Cleaning log',      'shield'],
    // M376 — expected vs done: duty expectations, today's outcomes, the week's compliance strip, roster overrides.
    ['M5g','duties',     'Duties',            'calCheck'],
    // The gate team's patrol log — same journal rail, kind='security' (M315).
    ['M5f','secjournal', 'Security journal',  'shield'],
    ['M5c','myshift',    'My shift',          'pin'],
  ]},
  { group: 'Customers & leads', agent: true, items: [
    ['C0', 'customers',  'Customers',         'users'],
    ['CG', 'gaps',       'Data gaps',         'spark'],
    // Nitin 2026-11-27: VMs work leads on the ONE modern surface, the Sales Desk (/sales), scoped to
    // their centre. 'leaddesk' / 'leads' are redirected there by venue-mount.jsx (vmOpenSales).
    ['CD', 'leaddesk',   'Sales Desk',        'spark'],
    ['C2', 'trials',     'Trials',            'calCheck'],
    // What we offer (read-only): batches with seats left (members + live trials), prices, registration fee, events.
    ['C2b','offer',      'What we offer',     'grid'],
    ['C5', 'feedback',   'Feedback',          'message'],
    ['C3', 'incidents',  'Incidents',         'shield'],
    ['C7', 'parentnotify','Parent updates',   'message'],   // M382/M383 — what families are told; start/stop per centre
  ]},
  // Marketing Engine canvas ("Leads in", "Drives"), M512 — vm-marketing.jsx. Vite twin: Sales Desk → Marketing.
  { group: 'Marketing', items: [
    ['MK1','leadsources', 'Lead sources',     'trend'],
    ['MK2','drives',      'Drives',           'pin'],
    ['MK3','media',       'Media',            'gallery'],   // M515 vm-media.jsx
    ['MK4','adspend',     'Ad spend',         'card'],    // M514 spend vs trials done / bookings; not for agents
  ]},
  { group: 'Front desk', items: [
    ['F1', 'bookings',   'Bookings',          'cal'],
    ['F2', 'visitors',   'Visitors',          'users'],
    ['F3', 'gate',       'Gate',              'shield'],
    ['F3b','gatescan',   'Gate scan',         'add'],
    ['F3c','comp',       'Comp members',      'users'],
    ['F3d','gatesettings','Gate settings',    'shield'],
    ['F5', 'policies',   'Policies',          'document'],
    ['F4', 'access',     'Access rules',      'shield',   'soon'],
  ]},
  { group: 'Money', items: [
    ['S1', 'subscriptions','Subscriptions',   'card'],
    ['S2', 'transactions', 'Transactions',    'card'],
    // Finance's queue. Under Money because that is where whoever handles money
    // already looks — not a new place to remember.
    ['S2b','confirmpay',   'Confirm payments','shield'],
    // The gateway's own feed against our books. Finance-only, tenant-wide: much of
    // this money arrives naming no centre at all.
    ['S2c','reconcile',    'Reconciliation',  'trend'],
    ['S3', 'collect',      'Collect',         'add'],
    ['S4', 'coupons',      'Coupons',         'spark'],
    // The operator's headline report — surfaced from the old "Roadmap" group.
    ['P1', 'pnl',          'Revenue · MIS',   'trend'],
    ['P2', 'members',      'Members',         'card',     'soon'],
  ]},
  // The shop's screens live in the Vite console (/vm). Wide screens are bounced from /vm to here, so
  // without this entry a venue manager on a laptop could not reach Merch at all (Nitin 2026-11-18).
  // None of these is a page here: TrokoVMNav sends every 'shop*' key to /vm?desktop=1 (see vmOpenShop).
  // The last five are the central desk's (Nitin 2026-11-18 "add them to shop menu"); vmNavFor hides them
  // unless /api/v1/merch/me says this person is on the desk (window.__vmMerchDesk).
  { group: 'Shop', items: [
    ['SH1','shop',          'Shop orders & sales', 'card'],
    ['SH2','shop-receive',  'Receive stock',       'add'],
    ['SH3','shop-stock',    'Centre stock',        'grid'],
    ['SH4','shop-products', 'Products & stock',    'document'],
    ['SH5','shop-inbound',  'Inbound stock',       'add'],
    ['SH6','shop-dispatch', 'Send to centres',     'pin'],
    ['SH6b','shop-ship',    'Ship to homes',       'pin'],
    ['SH7','shop-exchanges','Exchanges',           'spark'],
    ['SH8','shop-centres',  'Pickup centres',      'pin'],
  ]},
  { group: 'Set up', items: [
    ['M7', 'facilities',   'Facilities',      'pin'],
    ['S5', 'authorplan',   'Plans & pricing', 'add'],
    ['M8', 'tournaments',  'Tournaments',     'cal'],
    ['M9', 'events',       'Events',          'cal'],
    ['C4', 'sop',          'SOP',             'document'],
  ]},
];

// What a calling agent's menu holds: the agent:true groups, minus the items the server refuses an
// agent (app/policy/agent_fence.py). "Parent updates" sat in that group and loaded forever for an
// agent (403 swallowed). One helper for the desktop sidebar, the mobile menu and the route guard.
const VM_AGENT_HIDE = { parentnotify: 1 };
// The shop desk's items (vm-base VM_NAV 'Shop'): shown only to the central desk.
const VM_SHOP_DESK = { 'shop-products': 1, 'shop-inbound': 1, 'shop-dispatch': 1, 'shop-ship': 1, 'shop-exchanges': 1, 'shop-centres': 1 };
function vmNavFor(agentMode) {
  if (!agentMode) {
    if (typeof window !== 'undefined' && window.__vmMerchDesk) return VM_NAV;
    return VM_NAV.map(function (g) {
      return g.group !== 'Shop' ? g : Object.assign({}, g, { items: g.items.filter(function (it) { return !VM_SHOP_DESK[it[1]]; }) });
    });
  }
  return VM_NAV.filter(function (g) { return g.agent; }).map(function (g) {
    return Object.assign({}, g, { items: (g.items || []).filter(function (it) { return !VM_AGENT_HIDE[it[1]]; }) });
  });
}
// True when the signed-in console is a calling agent's (set by VMApp from the session).
function vmIsAgent() { return typeof window !== 'undefined' && !!window.__vmAgentMode; }

// ── Menu counts (Sales Desk design: "Calls · 2 to finish", "Approvals · 1 waiting") ──
// ONE light read, GET /api/v1/crm/agenda/menu-counts (app/services/crm_menu_counts.py), kept 60 s across
// pages, re-read each minute while visible and when the tab regains focus. Zero / unknown -> no pill.
// Twin of troko-web/src/pages/sales/menuCounts.ts (vmNavPills) + useMenuCounts.ts. This console's
// entries that lead to the desk: 'leaddesk' ("Sales Desk", calls still to finish) and 'approvals'
// (the caller's own requests waiting). The calling team never sees this console (sent to /sales).
const VM_MENU_TTL_MS = 60000;
var _vmMenu = { at: 0, c: null, inflight: null };
function vmMenuPill(key, c) {
  if (!c) return null;
  var n = function (v) { return (typeof v === 'number' && isFinite(v) && v > 0) ? Math.floor(v) : 0; };
  if (key === 'leaddesk') { var a = n(c.calls_to_finish); return a ? a + ' to finish' : null; }
  if (key === 'approvals') { var b = n(c.approvals_waiting); return b ? b + ' waiting' : null; }
  return null;
}
function vmReadMenuCounts(force) {
  var now = Date.now();
  if (!force && _vmMenu.at && now - _vmMenu.at < VM_MENU_TTL_MS) return Promise.resolve(_vmMenu.c);
  if (_vmMenu.inflight) return _vmMenu.inflight;
  if (typeof vapiSafe !== 'function') return Promise.resolve(null);
  _vmMenu.inflight = vapiSafe('/api/v1/crm/agenda/menu-counts').then(function (r) {
    _vmMenu.inflight = null;
    if (r) { _vmMenu.at = Date.now(); _vmMenu.c = r; }
    return r || _vmMenu.c;
  }, function () { _vmMenu.inflight = null; return _vmMenu.c; });
  return _vmMenu.inflight;
}
function useVMMenuCounts(enabled) {
  const [c, setC] = React.useState(_vmMenu.c);
  React.useEffect(function () {
    if (!enabled) return undefined;
    var live = true;
    var load = function (force) { vmReadMenuCounts(force).then(function (r) { if (live) setC(r); }); };
    load(false);
    var t = setInterval(function () { if (!document.hidden) load(true); }, VM_MENU_TTL_MS);
    var onFocus = function () { if (!document.hidden) load(false); };
    window.addEventListener('focus', onFocus);
    document.addEventListener('visibilitychange', onFocus);
    return function () { live = false; clearInterval(t); window.removeEventListener('focus', onFocus); document.removeEventListener('visibilitychange', onFocus); };
  }, [enabled]);
  return c;
}
const VMMenuPill = ({ text, on, light }) => text ? (
  <span style={{ flexShrink: 0, fontSize: 10.5, fontWeight: 800, lineHeight: 1, padding: '3px 7px', borderRadius: 999,
    background: on ? 'rgba(31,42,0,0.16)' : 'var(--orange)', color: on ? 'var(--lime-ink)' : 'var(--ink)' }}>{text}</span>
) : null;
// The one retired entry, removed in a single place rather than by editing the literal —
// so recalling it is a flag, not a diff.
VM_NAV.forEach(function (g) {
  if (!VM_RECONCILE) g.items = g.items.filter(function (it) { return it[1] !== 'reconcile'; });
});

const VM_SHARED_ICONS = new Set(['whistle', 'calCheck', 'trend', 'card', 'edit', 'message']); // from XIcon

const VMIcon = ({ name, ...p }) => VM_SHARED_ICONS.has(name) ? <XIcon name={name} {...p} /> : <Icon name={name} {...p} />;

// ── Tag / pill ──
const VMTag = ({ children, bg = 'var(--bone-2)', fg = 'var(--text-2)', mono }) => (
  <span style={{ fontFamily: mono ? 'var(--font-mono)' : 'var(--font-ui)', fontSize: mono ? 10 : 11.5, fontWeight: 700, letterSpacing: mono ? '0.05em' : 0, padding: mono ? '3px 7px' : '4px 9px', borderRadius: 999, background: bg, color: fg, whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 5 }}>{children}</span>
);

// ── KPI card (warm) ──
const VMKpi = ({ label, value, sub, delta, deltaUp, accent = 'var(--ink)', gated, onClick }) => (
  <div onClick={onClick || undefined} style={{ flex: 1, background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 18, padding: 18, position: 'relative', opacity: gated ? 0.6 : 1, cursor: onClick ? 'pointer' : 'default' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ fontSize: 12, color: 'var(--text-3)', fontWeight: 600 }}>{label}</span>
      {delta && <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 700, color: deltaUp ? 'var(--success)' : 'var(--orange)', background: deltaUp ? 'var(--success-bg)' : 'var(--orange-tint)', padding: '2px 7px', borderRadius: 999 }}>{deltaUp ? '▲' : '▼'} {delta}</span>}
      {gated && <span style={{ marginLeft: 'auto' }}><VMTag mono bg="var(--bone-2)" fg="var(--text-4)">SOON</VMTag></span>}
    </div>
    <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 30, letterSpacing: '-0.02em', marginTop: 8, color: gated ? 'var(--text-4)' : accent }}>{value}</div>
    <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 5 }}>{sub}</div>
  </div>
);

// ── Section panel (warm) ──
const VMPanel = ({ title, right, children, pad = 18 }) => (
  <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 18, overflow: 'hidden' }}>
    {title && (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '15px 18px', borderBottom: '1px solid var(--line)' }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15.5 }}>{title}</span>
        <div style={{ flex: 1 }} />
        {right}
      </div>
    )}
    <div style={{ padding: pad }}>{children}</div>
  </div>
);

// Sport filter + sort bar — shared across list surfaces (Batches…). Since 28 Nov a thin wrapper over FilterBar
// (below): the sports are its ONE chip row, the count and Sort sit in its right slot, and Clear filters puts the
// sport back to "All sports" (sort is not a filter, so Clear leaves it). Same props as before.
// `sports` = array of bare slugs; `value`='all'|slug; sort = 'sport'|'name'|'fill'.
const SportFilterBar = ({ sports = [], value = 'all', onChange, sortBy, onSort, count, noun = 'item' }) => {
  if (!sports.length) return null;
  const right = (
    <React.Fragment>
      {typeof count === 'number' && <span style={{ fontSize: 11.5, color: 'var(--text-4)', fontWeight: 600 }}>{count} {noun}{count === 1 ? '' : 's'}</span>}
      {onSort && (
        <select value={sortBy} onChange={e => onSort(e.target.value)} title="Sort" style={{ padding: '6px 10px', borderRadius: 9, border: '1px solid var(--line-2)', background: 'var(--paper)', fontSize: 12, fontWeight: 600, fontFamily: 'var(--font-ui)', color: 'var(--text-2)', cursor: 'pointer' }}>
          <option value="sport">Sort: Sport</option>
          <option value="name">Sort: Name</option>
          <option value="fill">Sort: Fill</option>
        </select>
      )}
    </React.Fragment>
  );
  return (
    <FilterBar chips={[{ key: 'all', label: 'All sports' }].concat(sports.map(s => ({ key: s, label: window.trokoSportLabel(s) || s })))}
      chip={value} onChip={k => onChange && onChange(k)} chipReset="all" chipsLabel="Sport" right={right} />
  );
};

// ── FILTER BAR (Nitin 28 Nov: "search and filtration ... should be like drop downs and text boxes rather
// than multiple layers of chips, chips can exist but not multiple layers"). The ONE filter strip for
// reporting / list screens: [search box] [labelled dropdowns…] [Clear filters], then at most ONE chip row.
// Controlled (the screen owns every value, so hash state and agent fences stay put); the search box is
// debounced here. Vite twin: troko-web/src/components/FilterBar.tsx + filterRules.ts (same props, same rules).
//   selects: [{ key, label, value, options: [{value,label}], onChange, reset?, always? }]
//   chips:   [{ key, label, count? }], chip, onChip, chipReset (default = first chip)
const fbResetOf = (s) => (s.reset !== undefined ? s.reset : ((s.options && s.options[0] && s.options[0].value) || ''));
const fbShown = (s) => !!s.always || (s.options || []).length > 1 || s.value !== fbResetOf(s);
const fbWithAll = (allLabel, opts, allValue) => {
  const av = allValue === undefined ? '' : allValue;
  const seen = {}; seen[av] = 1;
  const out = [{ value: av, label: allLabel }];
  (opts || []).forEach(o => { if (!seen[o.value]) { seen[o.value] = 1; out.push(o); } });
  return out;
};
const fbDigits = (s) => String(s == null ? '' : s).replace(/\D+/g, '');
const fbFold = (s) => String(s == null ? '' : s).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '');
// Same rule as Vite rowMatches: every typed word somewhere in the fields, or 3+ digits inside the phone.
const fbRowMatches = (query, fields, phone) => {
  const q = fbFold(query).replace(/\s+/g, ' ').trim();
  if (!q) return true;
  const qd = fbDigits(q);
  if (phone && qd.length >= 3 && qd.length === q.replace(/[\s+-]/g, '').length && fbDigits(phone).indexOf(qd) >= 0) return true;
  const hay = fbFold((fields || []).filter(f => f !== null && f !== undefined && f !== '').join(' '));
  return q.split(' ').every(t => hay.indexOf(t) >= 0);
};
const FilterBar = ({ q, onQ, placeholder, debounceMs, selects, chips, chip, onChip, chipReset, chipsLabel, onClear, right, shown, total, noun, dark, style }) => {
  const sel = (selects || []).filter(Boolean);
  const [text, setText] = React.useState(q || '');
  const sent = React.useRef(q || '');
  const onQRef = React.useRef(onQ); onQRef.current = onQ;
  React.useEffect(() => { if ((q || '') !== sent.current) { sent.current = q || ''; setText(q || ''); } }, [q]);
  React.useEffect(() => {
    if (!onQRef.current || text === sent.current) return undefined;
    const t = setTimeout(() => { sent.current = text; onQRef.current && onQRef.current(text); }, debounceMs == null ? 250 : debounceMs);
    return () => clearTimeout(t);
  }, [text]);
  const cr = chipReset !== undefined ? chipReset : (chips && chips[0] ? chips[0].key : undefined);
  let n = text.trim() ? 1 : 0;
  sel.forEach(s => { if (s.value !== fbResetOf(s)) n += 1; });
  if (chip !== undefined && cr !== undefined && chip !== cr) n += 1;
  const clear = () => {
    sent.current = ''; setText('');
    if (onQ && (q || text)) onQ('');
    sel.forEach(s => { if (s.value !== fbResetOf(s)) s.onChange(fbResetOf(s)); });
    if (onChip && cr !== undefined && chip !== cr) onChip(cr);
    if (onClear) onClear();
  };
  const fg = dark ? 'var(--text-on-ink, #fff)' : 'var(--ink)';
  const box = { display: 'inline-flex', alignItems: 'center', gap: 6, minHeight: 38, boxSizing: 'border-box', borderRadius: 11,
    border: '1px solid ' + (dark ? 'rgba(255,255,255,0.16)' : 'var(--line)'), background: dark ? 'rgba(255,255,255,0.08)' : 'var(--paper)',
    color: fg, padding: '0 11px', fontSize: 12.5, fontFamily: 'var(--font-ui)' };
  const cap = { fontSize: 9.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: dark ? 'rgba(255,255,255,0.6)' : 'var(--text-4)', whiteSpace: 'nowrap', fontFamily: 'var(--font-mono)' };
  const chipCss = (on) => ({ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 999, cursor: 'pointer', fontSize: 12, fontWeight: 700,
    fontFamily: 'var(--font-ui)', border: '1px solid ' + (on ? 'var(--ink)' : 'var(--line)'), background: on ? 'var(--ink)' : 'var(--paper)', color: on ? 'var(--lime)' : 'var(--text-2)' });
  const line = (typeof shown === 'number' && typeof total === 'number' && shown !== total) ? ('Showing ' + shown + ' of ' + total + ' ' + (noun || 'rows')) : '';
  return (
    <div style={Object.assign({ display: 'grid', gap: 8, marginBottom: 14 }, style || {})}>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        {onQ && (
          <div style={Object.assign({}, box, { flex: '1 1 200px', minWidth: 0, maxWidth: 360 })}>
            <Icon name="search" size={15} color={dark ? 'rgba(255,255,255,0.6)' : 'var(--text-4)'} />
            <input type="search" value={text} onChange={e => setText(e.target.value)} placeholder={placeholder || 'Search…'} aria-label={placeholder || 'Search'}
              style={{ border: 0, outline: 'none', background: 'transparent', flex: 1, minWidth: 0, fontFamily: 'var(--font-ui)', fontSize: 12.5, color: fg }} />
          </div>
        )}
        {sel.filter(fbShown).map(s => (
          <label key={s.key} style={Object.assign({}, box, { cursor: 'pointer', maxWidth: '100%' })}>
            <span style={cap}>{s.label}</span>
            <select value={s.value} aria-label={s.label} onChange={e => s.onChange(e.target.value)}
              style={{ border: 0, outline: 'none', background: 'transparent', cursor: 'pointer', fontWeight: 700, fontSize: 12.5, fontFamily: 'var(--font-ui)', color: fg, maxWidth: 200 }}>
              {(s.options || []).map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </label>
        ))}
        {n > 0 && <button type="button" onClick={clear} style={Object.assign({}, box, { cursor: 'pointer', fontWeight: 700, background: 'transparent', color: dark ? fg : 'var(--text-2)' })}>Clear filters</button>}
        {right ? <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>{right}</div> : null}
      </div>
      {chips && chips.length > 1 && onChip && (
        <div role="group" aria-label={chipsLabel || 'Quick filter'} className="no-bar" style={{ display: 'flex', gap: 7, overflowX: 'auto', paddingBottom: 2 }}>
          {chips.map(c => (
            <button key={c.key || 'all'} type="button" aria-pressed={c.key === chip} onClick={() => onChip(c.key)} style={chipCss(c.key === chip)}>
              {c.label}{typeof c.count === 'number' && <span style={{ fontSize: 10.5, opacity: 0.7 }}>{c.count}</span>}
            </button>
          ))}
        </div>
      )}
      {line && <div role="status" style={{ fontSize: 12, color: dark ? 'rgba(255,255,255,0.7)' : 'var(--text-3)' }}>{line}</div>}
    </div>
  );
};

// ── Fill meter (batch occupancy) ──
const FillMeter = ({ fill, cap, w = 90 }) => {
  const pct = Math.round((fill / cap) * 100);
  const full = pct >= 100;
  const col = full ? 'var(--orange)' : pct >= 80 ? 'var(--lime-2)' : 'var(--success)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
      <div style={{ width: w, height: 7, borderRadius: 999, background: 'var(--bone-2)', overflow: 'hidden' }}>
        <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', borderRadius: 999, background: col }} />
      </div>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-2)', fontWeight: 600, minWidth: 42 }}>{fill}/{cap}</span>
    </div>
  );
};

// =====================================================================
//  THE 2-D ROLE × CENTRE SWITCHER  (X1 — the main net-new problem)
//  Two dimensions: pick a centre, then a role — but only GRANTED roles
//  are selectable. Manager-only at KNC → Coach is locked there. This is
//  where "never imply coaching from management" is made visible.
// =====================================================================
const RoleCentreSwitcher = ({ open, onClose }) => {
  if (!open) return null;
  const ROLE_META = {
    manager: { label: 'Manager', sub: 'Run the centre', icon: 'grid' },
    coach:   { label: 'Coach',   sub: 'Daily operating', icon: 'whistle' },
  };
  return (
    <>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 40 }} />
      <div style={{ position: 'absolute', top: 58, right: 16, width: 340, background: 'var(--paper)', borderRadius: 18, border: '1px solid var(--line)', boxShadow: 'var(--sh-float)', zIndex: 41, overflow: 'hidden' }}>
        <div style={{ padding: '14px 16px 10px' }}>
          <Eyebrow>SWITCH ROLE × CENTRE</Eyebrow>
          <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 6, lineHeight: 1.45 }}>You see management only where you’re a manager, coaching only where you’re a coach.</div>
        </div>

        {/* All my centres — the default for anyone with 2+ centres (Nitin 2026-11-28). Real now: it
            sets X-Active-Centre '__all__' (the roll-up across the caller's grants, never wider). */}
        {VM_GRANTS.filter(g => g.centre_id).length > 1 && (
        <div style={{ padding: '0 12px 8px' }}>
          <div onClick={() => { if (!window.__vmAllCentres && window.switchVMCentre) window.switchVMCentre('__all__'); }} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 11, borderRadius: 13, background: window.__vmAllCentres ? 'var(--ink)' : 'var(--bone)', border: '1px solid ' + (window.__vmAllCentres ? 'var(--ink)' : 'var(--line-2)'), cursor: window.__vmAllCentres ? 'default' : 'pointer' }}>
            <span style={{ width: 34, height: 34, borderRadius: 10, background: window.__vmAllCentres ? 'var(--lime)' : 'var(--bone-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="grid" size={17} color={window.__vmAllCentres ? 'var(--lime-ink)' : 'var(--text-3)'} /></span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: window.__vmAllCentres ? '#fff' : 'var(--text)' }}>All my centres</div>
              <div style={{ fontSize: 11, color: window.__vmAllCentres ? 'var(--text-on-ink-3)' : 'var(--text-3)' }}>Every centre you hold, in one view</div>
            </div>
            {window.__vmAllCentres && <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--lime)', letterSpacing: '0.04em' }}>ACTIVE</span>}
          </div>
        </div>
        )}

        {/* Per-centre grant rows */}
        <div style={{ padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {VM_GRANTS.map(g => (
            <div key={g.centre} style={{ borderRadius: 13, border: `1px solid ${g.current ? 'var(--ink)' : 'var(--line)'}`, overflow: 'hidden' }}>
              <div onClick={() => { if ((!g.current || window.__vmAllCentres) && g.centre_id && window.switchVMCentre) window.switchVMCentre(g.centre_id); }} style={{ padding: '10px 12px', background: g.current ? 'var(--ink)' : 'var(--paper)', display: 'flex', alignItems: 'center', gap: 8, cursor: g.current ? 'default' : 'pointer' }}>
                <Icon name="pin" size={14} color={g.current ? 'var(--lime)' : 'var(--text-3)'} />
                <span style={{ fontSize: 13.5, fontWeight: 700, color: g.current ? '#fff' : 'var(--text)' }}>{g.centre}</span>
                <span style={{ fontSize: 11, color: g.current ? 'var(--text-on-ink-3)' : 'var(--text-4)' }}>· {g.area}</span>
                {!g.current && <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 700, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>Switch <Icon name="chevR" size={13} color="var(--text-4)" /></span>}
                {g.current && <span style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 700, color: 'var(--lime)', letterSpacing: '0.04em' }}>ACTIVE</span>}
              </div>
              <div style={{ display: 'flex', gap: 8, padding: 10 }}>
                {['manager', 'coach'].map(role => {
                  const granted = g.roles.includes(role);
                  const active = g.current && role === 'manager';
                  const m = ROLE_META[role];
                  return (
                    <div key={role} style={{
                      flex: 1, padding: '10px 11px', borderRadius: 11,
                      background: active ? 'var(--lime)' : granted ? 'var(--paper)' : 'var(--bone)',
                      border: `1px solid ${active ? 'var(--lime)' : granted ? 'var(--line-2)' : 'var(--line)'}`,
                      cursor: granted ? 'pointer' : 'not-allowed', opacity: granted ? 1 : 0.55,
                      display: 'flex', alignItems: 'center', gap: 8,
                    }}>
                      <VMIcon name={m.icon} size={15} color={active ? 'var(--lime-ink)' : 'var(--text-2)'} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12.5, fontWeight: 700, color: active ? 'var(--lime-ink)' : 'var(--text)', display: 'flex', alignItems: 'center', gap: 5 }}>
                          {m.label}{!granted && <Icon name="shield" size={11} color="var(--text-4)" />}
                        </div>
                        <div style={{ fontSize: 9.5, color: active ? 'rgba(31,42,0,0.6)' : 'var(--text-4)' }}>{granted ? (active ? 'Active now' : m.sub) : 'Not granted here'}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

// =====================================================================
//  DESKTOP SHELL — ink command sidebar + warm content + switcher
// =====================================================================
const VMShell = ({ active = 'overview', children, h = 900 }) => {
  const [sw, setSw] = useVMState(false);
  const [acct, setAcct] = useVMState(false);   // account/sign-out menu
  // Menu counts on the entries that lead to the Sales Desk (not on the locked gate kiosk).
  const menuCounts = useVMMenuCounts(!(typeof window !== 'undefined' && window.__vmGateLocked));
  // Agent mode (tenant-wide calling team, M155): CRM-only nav + tenant-wide chrome.
  const agentMode = (typeof window !== 'undefined') && !!window.__vmAgentMode;
  // Resolve the ACTIVE centre's name LIVE from the id→name map the context caches, so the
  // topbar follows the centre switcher even when VM_CENTRE (a module-level cache) is stale
  // — e.g. an operator "viewing as VM" switches via a force-render, not a full reload, so
  // VM_CENTRE never gets recomputed and the header showed the wrong (default) venue.
  const _activeCid = (typeof window !== 'undefined' && window.VenueAuth && VenueAuth.centreIds && VenueAuth.centreIds()[0]) || null;
  // A RAW TENANT ID IS NOT A CENTRE NAME. When the name map has not resolved the
  // active centre this fell through to VM_CENTRE.name, which can itself be the
  // id — so the header read "loc_svc_basecamp" above a list of somebody else's
  // leads. An id on screen looks like data and it is not; say what we know.
  const _rawName = (typeof window !== 'undefined' && window.__vmCentreNames && _activeCid && window.__vmCentreNames[_activeCid]) || VM_CENTRE.name;
  const _looksLikeId = /^(loc|ten|venue)[_-]/.test(String(_rawName || ''));
  const _activeCentreName = (typeof window !== 'undefined' && window.__vmAllCentres && !window.__opCentreId) ? 'All my centres'
    : (_rawName && !_looksLikeId) ? _rawName : 'Your centre';
  // Does the console currently span more than one centre? The lead rows use this
  // to decide whether naming each row's centre is information or noise.
  try {
    window.__crmMultiCentre = !!(window.VenueAuth && VenueAuth.centreIds
      && (VenueAuth.centreIds() || []).length > 1 && !window.__opCentreId);
  } catch (e) { /* noop */ }
  // The cached area belongs to VM_CENTRE; only trust it when that cache matches the live
  // active centre (else we'd show one centre's area under another's name).
  const _centreMatches = (_activeCentreName === VM_CENTRE.name);
  // Mobile: drop the fixed 232px sidebar + topbar chrome and render the page body
  // full-width. A desktop screen (e.g. Enrollment/Coaches) routed into the mobile
  // shell (VMMobile) otherwise kept the sidebar → content clipped off-screen at 375px.
  // VMMobile supplies the bottom tab bar + sign-out; the page's own VMPageHead is the header.
  const isMobile = (typeof window !== 'undefined') && window.innerWidth < 768;
  // Locked mode (gate-keeper kiosk, GateKeeperApp sets __vmGateLocked): render the page
  // body full-width with NO sidebar/nav — same bare frame as mobile — so entrance staff
  // see only their one Gate screen. padding-top clears the kiosk header GateKeeperApp adds.
  const locked = (typeof window !== 'undefined') && !!window.__vmGateLocked;
  if (isMobile || locked) {
    return (
      <div className="troko-app" style={{ width: '100%', minHeight: '100vh', background: 'var(--bone)', padding: locked ? '64px 14px 84px' : '12px 12px 92px', boxSizing: 'border-box' }}>
        {children}
      </div>
    );
  }
  return (
    <div className="troko-app" style={{ width: '100%', minHeight: h, display: 'flex', background: 'var(--bone)', position: 'relative', borderRadius: 16, overflow: 'hidden', border: '1px solid var(--line)' }}>
      {/* Sidebar */}
      <div style={{ width: 232, flexShrink: 0, background: 'var(--ink)', color: 'var(--text-on-ink)', padding: '20px 14px', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>
        <CourtBg kind="cricket" opacity={0.05} color="var(--lime)" />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 9, padding: '0 6px 18px' }}>
          <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--lime)', color: 'var(--lime-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>t</span>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: '#fff', lineHeight: 1 }}>Troko</div>
            <div style={{ fontSize: 10, color: 'var(--lime)', fontWeight: 600, letterSpacing: '0.06em', marginTop: 2 }}>{agentMode ? 'CALLING DESK' : 'MANAGE'}</div>
          </div>
        </div>

        <div style={{ position: 'relative', flex: 1, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {vmNavFor(agentMode).map(({ group, items, gated, roadmap }) => (
            <div key={group}>
              <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--text-on-ink-3)', padding: '0 8px 7px', display: 'flex', alignItems: 'center', gap: 6 }}>
                {group.toUpperCase()}{(gated || roadmap) && <Icon name="clock" size={10} color="var(--text-on-ink-3)" />}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                {items.map(([code, key, label, ic, eta]) => {
                  const on = key === active;
                  return (
                    <div key={key} onClick={() => { if (window.TrokoVMNav) window.TrokoVMNav(key); }} style={{
                      display: 'flex', alignItems: 'center', gap: 10, padding: '9px 10px', borderRadius: 10,
                      background: on ? 'var(--lime)' : 'transparent', cursor: 'pointer',
                      color: on ? 'var(--lime-ink)' : roadmap ? 'var(--text-on-ink-3)' : 'var(--text-on-ink-2)',
                    }}>
                      <VMIcon name={ic} size={17} color={on ? 'var(--lime-ink)' : roadmap ? 'var(--text-on-ink-3)' : 'var(--text-on-ink-2)'} />
                      <span style={{ flex: 1, fontSize: 13.5, fontWeight: on ? 700 : 500 }}>{label}</span>
                      <VMMenuPill text={vmMenuPill(key, menuCounts)} on={on} />
                      {(roadmap || eta) && <span style={{ fontSize: 8.5, fontWeight: 700, letterSpacing: '0.05em', padding: '2px 6px', borderRadius: 999, background: on ? 'rgba(31,42,0,0.18)' : 'rgba(212,255,63,0.12)', color: on ? 'var(--lime-ink)' : 'var(--lime)', textTransform: 'uppercase' }}>{eta}</span>}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        {/* tenant-scope footer */}
        <div style={{ position: 'relative', marginTop: 12, padding: 11, borderRadius: 11, background: 'rgba(255,255,255,0.05)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <Icon name="shield" size={14} color="var(--lime)" />
          <span style={{ fontSize: 10.5, color: 'var(--text-on-ink-2)', lineHeight: 1.45 }}>{agentMode ? 'Tenant-wide · every centre in your org. Never cross-tenant.' : 'Scoped to centres you manage. Never cross-tenant.'}</span>
        </div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        {/* Topbar with role×centre switcher */}
        <div style={{ height: 58, flexShrink: 0, background: 'var(--paper)', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', padding: '0 20px', gap: 14, position: 'relative', zIndex: 30 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <BatchGlyph sport="cricket" size={30} />
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, lineHeight: 1 }}>{agentMode ? 'Lead Desk' : _activeCentreName}</div>
              <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 2 }}>{agentMode ? 'Tenant-wide · calling team' : (_centreMatches ? VM_CENTRE.area : '')}</div>
            </div>
          </div>
          <div style={{ flex: 1 }} />
          {/* Lead search, every granted centre (Nitin 2026-11-28); opens the hit on the Sales Desk. */}
          {typeof VMLeadSearch !== 'undefined' ? <VMLeadSearch /> : null}
          {agentMode ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '7px 12px', borderRadius: 999, background: 'var(--bone)', border: '1px solid var(--line-2)' }}>
              <VMTag bg="var(--ink)" fg="var(--lime)">Agent</VMTag>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)' }}>All centres</span>
            </div>
          ) : (
            <button onClick={() => setSw(v => !v)} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '7px 12px', borderRadius: 999, background: 'var(--bone)', border: '1px solid var(--line-2)', cursor: 'pointer' }}>
              <VMTag bg="var(--ink)" fg="var(--lime)">Manager</VMTag>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)' }}>{_activeCentreName}</span>
              <Icon name="chevD" size={14} color="var(--text-3)" />
            </button>
          )}
          {typeof VMNotifBell !== 'undefined' ? <VMNotifBell /> : null}
          {/* Account menu — avatar opens name + Sign out (standard top-right pattern) */}
          <div style={{ position: 'relative' }}>
            <button onClick={() => setAcct(v => !v)} title={VM_PERSON.name} style={{ width: 34, height: 34, borderRadius: 999, background: 'var(--ink)', color: 'var(--lime)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, border: acct ? '2px solid var(--lime)' : '2px solid transparent', cursor: 'pointer', padding: 0 }}>{VM_PERSON.initials}</button>
            {acct && (
              <>
                <div onClick={() => setAcct(false)} style={{ position: 'fixed', inset: 0, zIndex: 44 }} />
                <div style={{ position: 'absolute', top: 44, right: 0, width: 232, background: 'var(--paper)', borderRadius: 14, border: '1px solid var(--line)', boxShadow: 'var(--sh-float)', zIndex: 45, overflow: 'hidden' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 14px' }}>
                    <div style={{ width: 38, height: 38, borderRadius: 999, background: 'var(--ink)', color: 'var(--lime)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, flexShrink: 0 }}>{VM_PERSON.initials}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{VM_PERSON.name}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--text-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{agentMode ? 'Agent · all centres' : ('Manager · ' + (_activeCentreName || ''))}</div>
                    </div>
                  </div>
                  <div style={{ borderTop: '1px solid var(--line)' }}>
                    {(typeof window !== 'undefined' && window.__personaHasMulti) ? (
                    <button onClick={() => { setAcct(false); try { window.dispatchEvent(new Event('troko:persona-open')); } catch (e) {} }} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', background: 'transparent', border: 0, borderBottom: '1px solid var(--line)', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--text)', textAlign: 'left' }}
                      onMouseEnter={e => e.currentTarget.style.background = 'var(--bone)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <Icon name="swap" size={16} color="var(--text-2)" /> Switch role
                    </button>
                    ) : null}
                    <button onClick={() => { setAcct(false); if (window.__vmSignOut) window.__vmSignOut(); }} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', background: 'transparent', border: 0, cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--text)', textAlign: 'left' }}
                      onMouseEnter={e => e.currentTarget.style.background = 'var(--bone)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <Icon name="arrowR" size={16} color="var(--text-2)" /> Sign out
                    </button>
                  </div>
                </div>
              </>
            )}
          </div>
          {!agentMode && <RoleCentreSwitcher open={sw} onClose={() => setSw(false)} />}
        </div>

        {/* Page body */}
        <div style={{ flex: 1, padding: 22, overflow: 'hidden' }}>{children}</div>
      </div>
    </div>
  );
};

// ── Page header used inside content ──
const VMPageHead = ({ title, sub, right }) => (
  <div style={{ display: 'flex', alignItems: 'flex-end', flexWrap: 'wrap', gap: 10, marginBottom: 16 }}>
    <div>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 23, letterSpacing: '-0.02em' }}>{title}</div>
      {sub && <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 3 }}>{sub}</div>}
    </div>
    <div style={{ flex: 1 }} />
    {right}
  </div>
);

// venue-login live store — the canonical data layer calls VMStore.set({...}) to
// replace the mocks with real data (roster→coaches, batches, centre counts,
// person→grants) before the VM screens render. Omitted keys keep their mock so a
// screen never blanks — never legacy.
window.VMStore = {
  set(d) {
    d = d || {};
    if (d.person)  VM_PERSON  = d.person;
    if (d.grants)  VM_GRANTS  = d.grants;
    if (d.centre)  VM_CENTRE  = d.centre;
    if (d.coaches) VM_COACHES = d.coaches;
    if (d.batches) VM_BATCHES = d.batches;
    Object.assign(window, { VM_PERSON, VM_GRANTS, VM_CENTRE, VM_COACHES, VM_BATCHES });
  },
};

// Shared 5-star rating (was only defined in vm-feedback.jsx, which isn't loaded →
// VMCustomers/vm-mobile rendered <Stars> against an undefined global and crashed
// the whole route whenever a customer row rendered — the "This screen hit a snag"
// that only fired with data, never on the empty state. Define + export it here so
// every loaded consumer resolves it. (G2 root cause.)
const Stars = ({ n, size = 12 }) => (
  <span style={{ display: 'inline-flex', gap: 1 }}>
    {[1, 2, 3, 4, 5].map(i => <Icon key={i} name="star" size={size} color={i <= (n || 0) ? 'var(--lime-2)' : 'var(--line-2)'} />)}
  </span>
);

// ── Roll numbers (M498 · Nitin 24 Nov: "roll numbers everywhere, simple and easy to remember") ──
// A child's CENTRE-SPORT-NUMBER (VK-F-17) as a small monospace chip beside their name. The
// Vite twin is troko-web/src/pages/vm/RollChip.tsx — change both together.
const vmRollNorm = (s) => String(s || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
// Does a typed filter hit this roll number? "vkf17", "VK F 17", "vk-f-17" all find VK-F-17.
// The query must carry a letter AND a digit, so a name being typed ("Su") never lights up a centre.
const vmRollMatch = (q, roll) => {
  const n = vmRollNorm(q);
  return !!(n && /[A-Z]/.test(n) && /[0-9]/.test(n) && roll && vmRollNorm(roll).indexOf(n) === 0);
};
const VMRollChip = ({ no, title, style }) => (no ? (
  <span className="vm-roll" title={title || 'Roll number'} style={Object.assign({ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 500, lineHeight: '14px', color: 'var(--text-2)', background: 'var(--bone-2)', borderRadius: 5, padding: '1px 5px', marginLeft: 6, whiteSpace: 'nowrap', display: 'inline-block', verticalAlign: 'middle', letterSpacing: 0 }, style || {})}>{no}</span>
) : null);
// Every number a child holds (one per centre + sport) — the profile header.
const VMRollChips = ({ nos, style }) => {
  const list = (nos || []).filter((r) => r && (r.roll_no || typeof r === 'string'));
  if (!list.length) return null;
  return (
    <span style={Object.assign({ display: 'inline-flex', flexWrap: 'wrap', gap: 4, alignItems: 'center' }, style || {})}>
      {list.map((r, i) => {
        const no = typeof r === 'string' ? r : r.roll_no;
        const t = typeof r === 'string' ? 'Roll number' : ['Roll number', r.sport, r.centre].filter(Boolean).join(' · ');
        return <VMRollChip key={no + i} no={no} title={t} style={{ marginLeft: 0 }} />;
      })}
    </span>
  );
};

Object.assign(window, {
  VM_PERSON, VM_GRANTS, VM_CENTRE, VM_COACHES, VM_BATCHES, VM_NAV,
  VMIcon, VMTag, VMKpi, VMPanel, FillMeter, RoleCentreSwitcher, VMShell, VMPageHead, Stars, SportFilterBar,
  FilterBar, fbWithAll, fbRowMatches,
  VMRollChip, VMRollChips, vmRollMatch, vmRollNorm,
});
