/* ============================================================================
   Names — one place for "are these two names the same?" and "which names match what I typed?"

   nameKey() is the JavaScript twin of the database function name_key(). The two MUST give the
   same answer: names.test.js checks this against answers taken from the real database.

   Two names with the same key are the same supplier / client: capital letters, accents, a
   leading "S.C." and the endings SRL / S.R.L. / SA / PFA / LTD … do not make a different one.
   ============================================================================ */

const _ACCENTS_FROM = 'ăâîșşțţéèêëöôüûáàçñ';
const _ACCENTS_TO   = 'aaisstteeeeoouuaacn';

/* Lower case, trimmed, accents folded to plain letters. */
function foldText(s) {
  return String(s == null ? '' : s).trim().toLowerCase()
    .replace(/[ăâîșşțţéèêëöôüûáàçñ]/g, c => _ACCENTS_TO[_ACCENTS_FROM.indexOf(c)]);
}

function nameKey(n) {
  const raw = String(n == null ? '' : n).trim().toLowerCase();
  const s = foldText(raw)
    .replace(/^s\.?\s?c\.?\s+/, '')
    .replace(/\b(s\.?\s?r\.?\s?l\.?|s\.?\s?a\.?|srl|sa|pfa|ltd|llc|inc|gmbh|bv|ag|ifn|\(.*\))\b\.?/g, ' ')
    .replace(/[^a-z0-9]+/g, '');
  return s || raw.replace(/\s+/g, ' ');
}

/* The official name a typed text already matches, or null. */
function findSameName(options, typed) {
  const k = nameKey(typed);
  if (!k) return null;
  return options.find(o => nameKey(o) === k) || null;
}

/* The options to show for what has been typed: names that START with it first, then names that
   merely contain it, each group in alphabetical order. Accents and capitals are ignored.
   With nothing typed: all options, alphabetical. */
function rankOptions(options, typed) {
  const q = foldText(typed);
  const byName = (a, b) => String(a).localeCompare(String(b), 'ro', { sensitivity: 'base' });
  const all = [...new Set(options.filter(o => o != null && String(o).trim() !== ''))];
  if (!q) return all.sort(byName);
  const starts = [], inside = [];
  all.forEach(o => { const f = foldText(o); if (f.startsWith(q)) starts.push(o); else if (f.includes(q)) inside.push(o); });
  return [...starts.sort(byName), ...inside.sort(byName)];
}

Object.assign(window, { foldText, nameKey, findSameName, rankOptions });
