/* eslint-disable */
// Ork datasheet reference drawer. Data lives in window.HORDE_DATASHEETS.Orks
// (functional stats only). Spawn-table unit strings carry counts / "+ Leader" /
// "(Full)" loadout flavor, so we normalize them down to the canonical datasheet.

(function () {
  // Explicit aliases for spellings/abbreviations the spawn table uses that differ
  // from the datasheet key (keys are de-slugged Wahapedia anchors).
  const ALIASES = {
    'meganobs': 'Meganobz',
    'beast snagga boys': 'Beast Snagga Boyz',
    'squighog boys': 'Squighog Boyz',
    'stormboys': 'Stormboyz',
    'ghaz': 'Ghazghkull Thraka',
    'killrig': 'Kill Rig',
    "big'ed bossbunka": 'Big ed Bossbunka',
    'biged bossbunka': 'Big ed Bossbunka',
  };

  function norm(s) { return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ''); }

  // Strip loadout/count noise: "10 Boyz", "5 Lootas + Leader", "Gretchin (11)",
  // "Trukk (Full)", "Ghaz + 3 Meganobz", "Burna Boyz x5", "20 Boyz + Double Leader".
  function canonicalName(raw) {
    let s = String(raw || '').trim();
    s = s.replace(/\([^)]*\)/g, ' ');        // drop "(11)", "(Full)"
    s = s.split('+')[0];                       // drop "+ Leader", "+ Makari", "+ N <unit>"
    s = s.replace(/\bx\s*\d+\b/gi, ' ');       // drop "x5"
    s = s.replace(/^\s*\d+\s+/, ' ');          // drop leading count "10 "
    s = s.replace(/\bfull\b/gi, ' ');
    s = s.replace(/\s+/g, ' ').trim();
    return s;
  }

  // Returns { name, sheet } or null if we have no datasheet for it.
  window.resolveOrkDatasheet = function (rawName) {
    const book = (window.HORDE_DATASHEETS && window.HORDE_DATASHEETS.Orks) || {};
    if (!rawName) return null;
    const cleaned = canonicalName(rawName);
    const alias = ALIASES[cleaned.toLowerCase()];
    const target = alias || cleaned;
    // Build a normalized index once.
    if (!book.__index) {
      Object.defineProperty(book, '__index', { value: {}, enumerable: false });
      for (const key of Object.keys(book)) book.__index[norm(key)] = key;
    }
    const idx = book.__index;
    let key = idx[norm(target)];
    // Singular/plural "boys"/"boyz" fallback
    if (!key) key = idx[norm(target.replace(/boys$/i, 'boyz'))];
    if (!key) return null;
    return { name: key, sheet: book[key] };
  };

  // ---------- UI ----------
  const e = React.createElement;

  function WeaponTable({ title, rows }) {
    if (!rows || rows.length === 0) return null;
    const isMelee = title === 'MELEE';
    return e('div', { className: 'tile', style: { padding: 0, marginTop: 'var(--pad-2)' } },
      e('table', { className: 'ds-weapons', style: { width: '100%', borderCollapse: 'collapse', fontSize: 12 } },
        e('thead', null,
          e('tr', { style: { color: 'var(--c-horde)', textAlign: 'left' } },
            e('th', { style: thW }, isMelee ? 'MELEE WEAPONS' : 'RANGED WEAPONS'),
            e('th', { style: thN }, 'RNG'),
            e('th', { style: thN }, 'A'),
            e('th', { style: thN }, isMelee ? 'WS' : 'BS'),
            e('th', { style: thN }, 'S'),
            e('th', { style: thN }, 'AP'),
            e('th', { style: thN }, 'D'),
          )
        ),
        e('tbody', null, rows.map((w, i) =>
          e(React.Fragment, { key: i },
            e('tr', { style: { borderTop: '1px solid var(--line-soft)' } },
              e('td', { style: tdName }, w.name),
              e('td', { style: tdNum }, w.range),
              e('td', { style: tdNum }, w.a),
              e('td', { style: tdNum }, w.skill),
              e('td', { style: tdNum }, w.s),
              e('td', { style: tdNum }, w.ap),
              e('td', { style: tdNum }, w.d),
            ),
            w.keywords && w.keywords.length
              ? e('tr', null, e('td', { colSpan: 7, style: { padding: '0 8px 6px', color: 'var(--ink-3)', fontSize: 10 } },
                  '[' + w.keywords.join(', ') + ']'))
              : null
          )
        ))
      )
    );
  }

  const thW = { padding: '6px 8px', fontSize: 10 };
  const thN = { padding: '6px 4px', fontSize: 10, textAlign: 'center', width: 38 };
  const tdName = { padding: '6px 8px', fontWeight: 600 };
  const tdNum = { padding: '6px 4px', textAlign: 'center', fontFamily: 'var(--mono, monospace)' };

  function StatPip({ label, value }) {
    if (value == null || value === '') return null;
    return e('div', { className: 'ds-stat', style: { textAlign: 'center', minWidth: 44 } },
      e('div', { className: 'eyebrow', style: { fontSize: 9 } }, label),
      e('div', { className: 'display', style: { fontSize: 18, color: 'var(--ink)' } }, value)
    );
  }

  // unit = the resolved { name, sheet }; rawLabel = original spawn string.
  function DatasheetDrawer({ unit, rawLabel, onClose }) {
    const Drawer = window.Drawer;
    if (!unit) {
      return e(Drawer, { open: true, onClose, title: rawLabel || 'Datasheet', accent: 'horde' },
        e('div', { className: 'tile' },
          e('div', { className: 'muted', style: { fontSize: 13 } },
            'No datasheet on file for "', rawLabel, '" yet. Only Ork horde units are supported right now.')
        )
      );
    }
    const s = unit.sheet || {};
    const st = s.stats || {};
    return e(Drawer, { open: true, onClose, title: unit.name, accent: 'horde' },
      // stat line
      e('div', { className: 'tile' },
        e('div', { className: 'row', style: { gap: 6, justifyContent: 'space-between', flexWrap: 'wrap' } },
          e(StatPip, { label: 'M', value: st.M }),
          e(StatPip, { label: 'T', value: st.T }),
          e(StatPip, { label: 'SV', value: st.Sv }),
          e(StatPip, { label: 'W', value: st.W }),
          e(StatPip, { label: 'LD', value: st.Ld }),
          e(StatPip, { label: 'OC', value: st.OC }),
          st.Inv ? e(StatPip, { label: 'INV', value: st.Inv }) : null
        ),
        rawLabel && norm0(rawLabel) !== norm0(unit.name)
          ? e('div', { className: 'muted', style: { fontSize: 11, marginTop: 8 } }, 'Spawned as: ', rawLabel)
          : null
      ),
      e(WeaponTable, { title: 'RANGED', rows: s.ranged }),
      e(WeaponTable, { title: 'MELEE', rows: s.melee }),
      // abilities (names only)
      s.abilities && s.abilities.length
        ? e('div', { className: 'tile', style: { marginTop: 'var(--pad-2)' } },
            e('div', { className: 'eyebrow' }, 'Abilities'),
            e('div', { className: 'row', style: { gap: 6, flexWrap: 'wrap', marginTop: 6 } },
              s.abilities.map((a, i) => e('span', { key: i, className: 'chip', style: { fontSize: 11 } }, a))),
            e('div', { className: 'muted', style: { fontSize: 10, marginTop: 6 } }, 'See the rulebook for full ability rules.')
          )
        : null,
      // keywords
      (s.keywords && s.keywords.length) || (s.factionKeywords && s.factionKeywords.length)
        ? e('div', { className: 'tile', style: { marginTop: 'var(--pad-2)' } },
            e('div', { className: 'eyebrow' }, 'Keywords'),
            e('div', { className: 'muted', style: { fontSize: 12, marginTop: 4 } }, (s.keywords || []).join(', ')),
            s.factionKeywords && s.factionKeywords.length
              ? e('div', { className: 'muted', style: { fontSize: 11, marginTop: 4 } }, 'Faction: ', s.factionKeywords.join(', '))
              : null
          )
        : null
    );
  }
  function norm0(x){ return String(x||'').toLowerCase().replace(/[^a-z0-9]+/g,''); }

  Object.assign(window, { DatasheetDrawer });
})();
