/* Robot Clash - layout self-test (dev only, loaded always but idle without ?uicheck). RC.uiCheck() measures the live DOM and reports layout faults as text: - containers that scroll (content taller than the box) - elements sticking out of #stage - overlapping pairs that must not touch (HUD over content, pad over cooldowns, ...) - tap targets below 34 px (tablet rule) - labels cut off with an ellipsis - heading font actually loaded The result goes into
 and document.title, so it can be read from a
   headless --dump-dom run without taking a screenshot (Michael's rule: never screenshots). */
(function (root) {
  'use strict';
  const RC = (root.RC = root.RC || {});
  // catch script errors as soon as this file loads (it runs before game.js), so a headless
  // --dump-dom run shows them instead of silently rendering a half-dead page
  const jsErrors = [];
  addEventListener('error', e => jsErrors.push(String(e.message || e.error) + ' @ ' + (e.filename || '').split('/').pop() + ':' + e.lineno));
  addEventListener('unhandledrejection', e => jsErrors.push('promise: ' + String(e.reason)));

  const MIN_TAP = 34;                 // px, smallest allowed button edge on touch
  const EPS = 1.5;                    // rounding slack

  const vis = el => {
    if (!el || !el.getBoundingClientRect) return false;
    const r = el.getBoundingClientRect();
    if (r.width < 1 || r.height < 1) return false;
    const st = getComputedStyle(el);
    return st.display !== 'none' && st.visibility !== 'hidden' && +st.opacity > 0.05;
  };
  const all = sel => Array.from(document.querySelectorAll(sel)).filter(vis);
  const one = sel => all(sel)[0] || null;
  const name = el => el.id ? '#' + el.id : '.' + (el.className || el.tagName).toString().trim().split(/\s+/)[0];
  const overlap = (a, b) => {
    const r = a.getBoundingClientRect(), q = b.getBoundingClientRect();
    const w = Math.min(r.right, q.right) - Math.max(r.left, q.left);
    const h = Math.min(r.bottom, q.bottom) - Math.max(r.top, q.top);
    return w > EPS && h > EPS ? Math.round(w) + 'x' + Math.round(h) : null;
  };

  // containers that are allowed to scroll only when genuinely full (long lists)
  const SCROLLERS = ['#cards', '.roomlist', '.plist', '#hangarView', '#paintView', '.card', '.board'];
  // pairs that must never cover each other: [a, b, why]
  const PAIRS = [
    ['#hud', '#rname', 'HUD over robot name'],
    ['#hud', '#shopTabs', 'HUD over shop tabs'],
    ['#hud', '.card', 'HUD over dialog'],
    ['#hud', '.lobbyfull', 'HUD over lobby'],
    ['#hud', '.opps', 'HUD over league grid'],
    ['#hud', '.fbox', 'HUD over the health box'],
    ['#winctl', '#hud', 'window buttons over HUD'],
    ['#winctl', '#fightHud', 'window buttons over fight HUD'],
    ['#fCds', '#pad > div:first-child', 'cooldown chips under the d-pad'],
    ['#fCds', '#pad .fire', 'cooldown chips under the fire buttons'],
    ['#fCds', '.fbox', 'cooldown chips over a fight box'],
    ['#pad', '#fightHud', 'touch pad over fight HUD'],
  ];

  RC.uiCheck = function () {
    const bad = [], note = [];
    const stage = document.getElementById('stage');
    if (!stage) return { ok: false, lines: ['no #stage'] };
    const sr = stage.getBoundingClientRect();

    // 1. scrolling containers
    for (const sel of SCROLLERS) {
      for (const el of all(sel)) {
        const over = el.scrollHeight - el.clientHeight;
        if (over > EPS) bad.push(`SCROLL ${name(el)} +${Math.round(over)}px (${el.scrollHeight}>${el.clientHeight})`);
        const overX = el.scrollWidth - el.clientWidth;
        if (overX > EPS) bad.push(`SCROLL-X ${name(el)} +${Math.round(overX)}px`);
      }
    }

    // 2. out of the stage
    for (const sel of ['#hud', '#shop', '#fightHud', '#pad', '.card', '.lobbyfull', '.title', '#fCds', '#detail', '.gbar', '.fitted']) {
      for (const el of all(sel)) {
        const r = el.getBoundingClientRect();
        const out = [
          r.left < sr.left - EPS ? 'left ' + Math.round(sr.left - r.left) : '',
          r.right > sr.right + EPS ? 'right ' + Math.round(r.right - sr.right) : '',
          r.top < sr.top - EPS ? 'top ' + Math.round(sr.top - r.top) : '',
          r.bottom > sr.bottom + EPS ? 'bottom ' + Math.round(r.bottom - sr.bottom) : '',
        ].filter(Boolean);
        if (out.length) bad.push(`OUTSIDE ${name(el)} ${out.join(', ')}`);
      }
    }

    // 3. forbidden overlaps
    for (const [sa, sb, why] of PAIRS) {
      const a = one(sa), b = one(sb);
      if (!a || !b) continue;
      const o = overlap(a, b);
      if (o) bad.push(`OVERLAP ${sa} / ${sb} ${o} - ${why}`);
    }

    // 4. tap targets (buttons that are visible right now)
    const scale = sr.width / (stage.offsetWidth || sr.width) || 1;   // Kit.fit scales the stage
    for (const b of all('button')) {
      const r = b.getBoundingClientRect();
      const w = r.width / scale, h = r.height / scale;
      if (h < MIN_TAP - EPS || w < 18) {
        const lbl = (b.textContent || b.id || '?').trim().slice(0, 14);
        bad.push(`SMALL button "${lbl}" ${Math.round(w)}x${Math.round(h)} (min ${MIN_TAP} high)`);
      }
    }

    // 5. clipped labels
    for (const el of all('.nm, .fn, .pn, .rn, .hmn, .hn, .who')) {
      if (el.scrollWidth - el.clientWidth > 2) bad.push(`CLIPPED "${(el.textContent || '').trim().slice(0, 18)}" in ${name(el)}`);
    }

    // 6. heading font - fonts.check() lies about missing families, so measure instead:
    //    render the same text in "Russo One" and in a family that cannot exist; equal width = fallback.
    const fontOk = (() => {
      const c = document.createElement('canvas').getContext('2d');
      const probe = f => { c.font = '40px ' + f; return c.measureText('ROBOT CLASH 123').width; };
      const miss = probe('"__no_such_font__", monospace');
      return Math.abs(probe('"Russo One", "__no_such_font__", monospace') - miss) > 0.5;
    })();
    if (fontOk === false) bad.push('FONT "Russo One" not loaded (headings fall back)');
    note.push(`stage ${Math.round(sr.width)}x${Math.round(sr.height)} scale ${scale.toFixed(2)} · mode ${document.body.dataset.mode || '?'} · font ${fontOk}`);

    for (const e of jsErrors) bad.unshift('JS ERROR ' + e);
    if (!document.body.dataset.mode) bad.push('NO SCREEN - setScreen() never ran (game did not start)');
    return { ok: bad.length === 0, lines: bad, note };
  };

  // ?uicheck - run after layout settled and print into the page (and the title, for --dump-dom)
  RC.uiCheckRun = function () {
    const show = () => {
      const r = RC.uiCheck();
      let pre = document.getElementById('uicheck');
      if (!pre) {
        pre = document.createElement('pre');
        pre.id = 'uicheck';
        pre.style.cssText = 'position:fixed;left:0;top:0;max-width:60vw;max-height:100vh;overflow:auto;margin:0;z-index:9999;' +
          'font:12px/1.4 monospace;white-space:pre-wrap;padding:6px 8px;background:rgba(0,0,0,.85);pointer-events:none';
        document.body.appendChild(pre);
      }
      pre.style.color = r.ok ? '#6dff9e' : '#ff5a4a';
      pre.textContent = (r.ok ? 'UI ok' : 'UI FAIL ' + r.lines.length) + '\n' + r.note.join('\n') +
        (r.lines.length ? '\n' + r.lines.join('\n') : '');
      document.title = (r.ok ? 'UI ok' : 'UI FAIL ' + r.lines.length) + ' | ' + (document.body.dataset.mode || '?');
    };
    const go = () => { show(); setTimeout(show, 600); setTimeout(show, 1600); };
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(go); else setTimeout(go, 300);
  };
})(typeof window !== 'undefined' ? window : globalThis);