/* ============================================================================
   P&L App (Lite): the US demo's filter registry and engine, with Lite's fields only.
   Money out has no sales tax fields (a bill's tax is part of its cost).

   Filtre — „Dacă înregistrăm un câmp, trebuie să putem filtra după el."  (Ana)

   UN SINGUR registru de câmpuri și UN SINGUR motor de filtrare, folosite atât de
   Încasări cât și de Plăți. Niciuna dintre cele două vederi nu are logică de
   filtrare proprie. Dacă apare vreodată logică de filtrare în view_incasari.jsx
   sau view_plati.jsx, ceva s-a stricat.

   A ADĂUGA UN CÂMP FILTRABIL ÎNSEAMNĂ A EDITA REGISTRUL DE MAI JOS, ȘI ATÂT.
   (Același design ca la Retiply, brief 08 — copiat aici, nu partajat: aplicațiile
   nu au pas de build, fiecare are propriul folder.)

   Decis (2 oct 2026, Ana):
   - Filtrele NU se rețin la reîncărcarea paginii. Pornesc mereu goale.
   - Sumele se pot filtra (egal, mai mic, mai mare, între). Lite: totul e în dolari.
   - Condițiile se combină doar cu ȘI. SAU e amânat.

   Condițiile interne („contains", „between"…) sunt chei în engleză; ce vede
   utilizatorul vine din OP_LABELS.
   ============================================================================ */

const _distinct = (list, fn) =>
  [...new Set(list.map(fn).filter(v => v != null && v !== ''))].sort((a, b) => String(a).localeCompare(String(b), 'en'));

/* A row with no category can be filtered for: the filter shows it as a label. */
const NO_CATEGORY = '(no category)';
const NO_PROJECT = '(no job)';


/* Valori derivate — nu sunt coloane în baza de date, dar se văd în tabel. */
const _tva = r => vatOfRow(r);
const _brut = r => r.sumaNeta + vatOfRow(r);

/* The official names (A to Z); a name still used by a row but missing from the list is added, so no
   row can ever be impossible to filter for. */
const _union = (list, used) => [...new Set([...list, ...used])].sort((a, b) => String(a).localeCompare(String(b), 'en', { sensitivity: 'base' }));
const furnizorOptions = () => _union(DB.furnizori.map(x => x.name), DB.plati.map(r => r.furnizor).filter(Boolean));
const clientOptions = () => _union(DB.clienti.map(x => x.name), DB.incasari.map(r => r.client).filter(Boolean));

/* Lite (17 Nov 2026): only the fields Lite has. Job, type, payment method, date paid, approved by,
   truck, source and document are paid-plan features and are not offered. Money in has a Category. */
const _catOptions = list => [...new Set(list.map(c => c.name))];
const FILTER_FIELDS = {
  plati: [
    { key: 'data',        label: 'Date',               type: 'date',    get: r => r.data },
    { key: 'furnizor',    label: 'Vendor',             type: 'enum',    get: r => r.furnizor,    options: () => furnizorOptions(), searchable: true },
    { key: 'categorie',   label: 'Category',           type: 'enum',    get: r => r.categorie || NO_CATEGORY, options: () => [NO_CATEGORY, ..._catOptions(DB.categorii)], searchable: true },
    { key: 'costType',    label: 'Direct cost or overhead', type: 'enum', get: r => isOverhead(r) ? 'Overhead' : 'Direct cost', options: () => ['Direct cost', 'Overhead'] },
    { key: 'nrFactura',   label: 'Bill #',             type: 'text',    get: r => r.nrFactura,   searchable: true },
    { key: 'sumaNeta',    label: 'Amount',             type: 'number',  get: r => r.sumaNeta },
    { key: 'dataScadenta',label: 'Due date',           type: 'date',    get: r => r.dataScadenta },
    { key: 'status',      label: 'Status',             type: 'enum',    get: r => r.status,      options: () => STATUS_OUT },
    { key: 'needsReview', label: 'To review',          type: 'boolean', get: r => !!r.needsReview },
    { key: 'reviewReason',label: 'Review reason',      type: 'text',    get: r => r.reviewReason },
    { key: 'notes',       label: 'Note',               type: 'text',    get: r => r.notes,       searchable: true },
  ],
  incasari: [
    { key: 'data',        label: 'Date',               type: 'date',    get: r => r.data },
    { key: 'client',      label: 'Customer',           type: 'enum',    get: r => r.client,      options: () => clientOptions(), searchable: true },
    { key: 'categorie',   label: 'Category',           type: 'enum',    get: r => r.categorie || NO_CATEGORY, options: () => [NO_CATEGORY, ..._catOptions(DB.categoriiIn)], searchable: true },
    { key: 'nrFactura',   label: 'Invoice #',          type: 'text',    get: r => r.nrFactura,   searchable: true },
    { key: 'sumaNeta',    label: 'Amount',             type: 'number',  get: r => r.sumaNeta },
    { key: 'cotaTva',     label: 'Sales tax rate (%)', type: 'number',  get: r => r.cotaTva },
    { key: 'tva',         label: 'Sales tax',          type: 'number',  get: _tva },
    { key: 'brut',        label: 'Total',              type: 'number',  get: _brut },
    { key: 'termenPlata', label: 'Payment terms (days)', type: 'number', get: r => r.termenPlata },
    { key: 'dataScadenta',label: 'Due date',           type: 'date',    get: r => r.dataScadenta },
    { key: 'status',      label: 'Status',             type: 'enum',    get: r => r.status,      options: () => STATUS_IN },
    { key: 'needsReview', label: 'To review',          type: 'boolean', get: r => !!r.needsReview },
    { key: 'reviewReason',label: 'Review reason',      type: 'text',    get: r => r.reviewReason },
    { key: 'notes',       label: 'Note',               type: 'text',    get: r => r.notes,       searchable: true },
  ],
};

function fieldsFor(table) { return FILTER_FIELDS[table] || []; }
function filterableFields(table) { return fieldsFor(table).filter(f => f.filterable !== false); }
function fieldByKey(table, key) { return fieldsFor(table).find(f => f.key === key) || null; }


/* ---------- condiții, după tip ---------- */
const CONDITIONS = {
  text:    ['contains', 'does not contain', 'is', 'is empty', 'is not empty'],
  number:  ['=', '≠', '>', '<', 'between'],
  date:    ['is', 'before', 'after', 'between', 'is empty', 'is not empty'],
  enum:    ['is any of', 'is none of', 'is', 'is not'],
  boolean: ['is', 'is not'],
};
/* Textul din listă. Cheia internă rămâne cea din CONDITIONS. */
const OP_LABELS = {
  'contains': 'contains', 'does not contain': 'does not contain', 'is': 'is',
  'is empty': 'is empty', 'is not empty': 'is not empty',
  '=': 'equals', '≠': 'is not', '>': 'more than', '<': 'less than',
  'between': 'between', 'before': 'before', 'after': 'after',
  'is not': 'is not', 'is any of': 'is any of', 'is none of': 'is none of',
};
const _NO_VALUE = new Set(['is empty', 'is not empty']);
const _LIST_OPS = new Set(['is any of', 'is none of']);
function isListOp(op) { return _LIST_OPS.has(op); }

/* Ce condiții se oferă pentru un câmp. La câmpurile cu listă: „oricare din" și „niciunul din"
   (bifezi mai multe). „este" / „nu este" (o singură valoare) apar doar dacă un filtru
   existent le folosește deja. */
function conditionsFor(field, currentOp) {
  const all = CONDITIONS[field.type];
  if (field.type !== 'enum') return all;
  const base = ['is any of', 'is none of'];
  return !currentOp || base.includes(currentOp) ? base : [...base, currentOp];
}

/* Suma scrisă de om poate avea virgulă („1000,50"). Valoarea comparată e rotunjită
   la bani, ca 21% din 1000 să fie exact 210 și nu 209,99999. */
const _toNum = v => Number(String(v == null ? '' : v).trim().replace(',', '.'));
const _cents = x => Math.round(x * 100) / 100;


/* ---------- presetări de dată ----------
   Păstrează INTENȚIA („anul acesta"), nu datele din ziua în care a fost aleasă. */
const DATE_PRESETS = [
  { key: 'thisMonth', label: 'This month' },
  { key: 'lastMonth', label: 'Last month' },
  { key: 'thisYear',  label: 'This year' },
  { key: 'lastYear',  label: 'Last year' },
];

function resolvePreset(key, today) {
  const t = today || todayISO();
  const y = +t.slice(0, 4), m = +t.slice(5, 7);
  const pad = n => String(n).padStart(2, '0');
  const lastDay = (yy, mm) => new Date(Date.UTC(yy, mm, 0)).getUTCDate();
  if (key === 'thisMonth') return { from: `${y}-${pad(m)}-01`, to: `${y}-${pad(m)}-${pad(lastDay(y, m))}` };
  if (key === 'lastMonth') { const yy = m === 1 ? y - 1 : y, mm = m === 1 ? 12 : m - 1;
                             return { from: `${yy}-${pad(mm)}-01`, to: `${yy}-${pad(mm)}-${pad(lastDay(yy, mm))}` }; }
  if (key === 'thisYear')  return { from: `${y}-01-01`, to: `${y}-12-31` };
  if (key === 'lastYear')  return { from: `${y - 1}-01-01`, to: `${y - 1}-12-31` };
  return null;
}

function dateBounds(f, today) {
  if (f.preset) return resolvePreset(f.preset, today);
  if (f.op === 'is')      return { from: f.value, to: f.value };
  if (f.op === 'before')  return { from: null, to: f.value, strict: 'to' };
  if (f.op === 'after')   return { from: f.value, to: null, strict: 'from' };
  if (f.op === 'between') return { from: f.value, to: f.value2 };
  return null;
}


/* ---------- un rând față de un filtru ---------- */
function matchesFilter(f, row, field, today) {
  const v = field.get(row);
  const blank = v == null || v === '';

  switch (field.type) {
    case 'text': {
      const s = String(v == null ? '' : v).toLowerCase();
      const q = String(f.value == null ? '' : f.value).toLowerCase();
      if (f.op === 'contains')         return s.includes(q);
      if (f.op === 'does not contain') return !s.includes(q);
      if (f.op === 'is')               return s === q;
      if (f.op === 'is empty')         return blank;
      if (f.op === 'is not empty')     return !blank;
      return true;
    }
    case 'number': {
      if (blank) return false;
      const n = _cents(Number(v)), a = _cents(_toNum(f.value)), b = _cents(_toNum(f.value2));
      if (f.op === '=')       return n === a;
      if (f.op === '≠')       return n !== a;
      if (f.op === '>')       return n > a;
      if (f.op === '<')       return n < a;
      if (f.op === 'between') return n >= Math.min(a, b) && n <= Math.max(a, b);
      return true;
    }
    case 'date': {
      if (f.op === 'is empty')     return blank;
      if (f.op === 'is not empty') return !blank;
      if (blank) return false;
      const b = dateBounds(f, today);
      if (!b) return true;
      if (b.from && (b.strict === 'from' ? v <= b.from : v < b.from)) return false;
      if (b.to   && (b.strict === 'to'   ? v >= b.to   : v > b.to))   return false;
      return true;
    }
    case 'enum': {
      // a field with getAll (a cost split across jobs) matches when ANY of its values does
      const vs = field.getAll ? field.getAll(row) : [v];
      const picked = Array.isArray(f.value) ? f.value : [];
      if (f.op === 'is')        return vs.includes(f.value);
      if (f.op === 'is not')    return !vs.includes(f.value);
      if (f.op === 'is any of')  return vs.some(x => picked.includes(x));
      if (f.op === 'is none of') return !vs.some(x => picked.includes(x));
      return true;
    }
    case 'boolean': {
      const want = f.value === true || f.value === 'true' || f.value === 'Yes';
      return f.op === 'is not' ? !!v !== want : !!v === want;
    }
  }
  return true;
}

/* Un filtru început dar nefinalizat nu ascunde nimic cât timp se scrie. */
function isComplete(f, field) {
  if (!field) return false;
  if (field.type === 'date' && f.preset) return true;
  if (_NO_VALUE.has(f.op)) return true;
  if (field.type === 'boolean') return f.value != null;
  if (_LIST_OPS.has(f.op)) return Array.isArray(f.value) && f.value.length > 0;
  const filled = x => x !== '' && x != null;
  if (field.type === 'number') {
    const ok = x => filled(x) && !isNaN(_toNum(x));
    return f.op === 'between' ? ok(f.value) && ok(f.value2) : ok(f.value);
  }
  if (f.op === 'between') return filled(f.value) && filled(f.value2);
  return filled(f.value);
}

/* `mode` = 'and' (implicit: fiecare filtru trebuie să se potrivească) sau 'or' (oricare).
   „De verificat" rămâne MEREU ȘI: restrânge lista, nu o lărgește. */
function applyFilters(rows, filters, table, today, mode) {
  const active = (filters || []).map(f => ({ f, field: fieldByKey(table, f.key) }))
                                .filter(x => isComplete(x.f, x.field));
  if (!active.length) return rows;
  const review = active.filter(x => x.f.key === 'needsReview');
  const rest = active.filter(x => x.f.key !== 'needsReview');
  const hit = (r, x) => matchesFilter(x.f, r, x.field, today);
  return rows.filter(r =>
    review.every(x => hit(r, x)) &&
    (!rest.length || (mode === 'or' ? rest.some(x => hit(r, x)) : rest.every(x => hit(r, x)))));
}

/* Căutarea liberă e altceva decât un filtru — „găsește factura aceea". */
function applySearch(rows, q, table) {
  const needle = String(q || '').trim().toLowerCase();
  if (!needle) return rows;
  const fields = fieldsFor(table).filter(f => f.searchable);
  // A number typed in the box also looks at the amounts (net, TVA, brut), written the way the table shows them (299,98) or with a dot (299.98).
  const num = needle.replace(/\s/g, '');
  const numeric = /^\d[\d.,]*$/.test(num);
  const amountHit = r => [r.sumaNeta, vatOfRow(r), brutOfRow(r)].some(n => {
    const v = (Math.round((n || 0) * 100) / 100).toFixed(2);
    return v.includes(num) || v.replace('.', ',').includes(num) || (typeof money === 'function' && money(Number(v)).includes(num));
  });
  return rows.filter(r => fields.some(f => String(f.get(r) == null ? '' : f.get(r)).toLowerCase().includes(needle)) || (numeric && amountHit(r)));
}

/* Tot ce arată tabelul, într-un singur apel. Vederile ȘI exportul folosesc asta,
   deci fișierul și ecranul nu pot ajunge să difere. */
function visibleRows(rows, state, table, today) {
  return sortRows(applySearch(applyFilters(rows, state.filters, table, today, state.mode), state.q, table),
                  state.sort, table);
}


/* ---------- sortare ---------- */
const DEFAULT_SORT = { key: 'data', dir: 'desc' };

function sortRows(rows, sort, table) {
  const s = sort && sort.key ? sort : DEFAULT_SORT;
  const field = fieldByKey(table, s.key) || fieldByKey(table, DEFAULT_SORT.key);
  if (!field) return rows;
  const mul = s.dir === 'asc' ? 1 : -1;
  return rows.slice().sort((a, b) => {
    const x = field.get(a), y = field.get(b);
    const xb = x == null || x === '', yb = y == null || y === '';
    if (xb && yb) return 0;
    if (xb) return 1;
    if (yb) return -1;
    if (field.type === 'number') return (x - y) * mul;
    if (field.type === 'boolean') return ((x ? 1 : 0) - (y ? 1 : 0)) * mul;
    return String(x).localeCompare(String(y), 'en') * mul;
  });
}


/* ---------- descrierea unui filtru, pentru chip și pentru fișierul exportat ---------- */
/* „A, B, C +2" — primele trei valori, apoi cât au mai rămas. */
function _listText(vals) {
  const v = Array.isArray(vals) ? vals : [];
  return v.slice(0, 3).join(', ') + (v.length > 3 ? ' +' + (v.length - 3) : '');
}

function describeFilter(f, table, today) {
  const field = fieldByKey(table, f.key);
  if (!field) return f.key;
  const opl = OP_LABELS[f.op] || f.op;
  if (field.type === 'date') {
    const b = dateBounds(f, today);
    const range = b ? [b.from ? fmtDate(b.from) : '…', b.to ? fmtDate(b.to) : '…'].join(' – ') : '';
    if (f.preset) {
      const p = DATE_PRESETS.find(x => x.key === f.preset);
      return `${field.label}: ${p ? p.label : f.preset} (${range})`;
    }
    return `${field.label} ${opl} ${f.op === 'between' ? range : fmtDate(f.value)}`;
  }
  if (_NO_VALUE.has(f.op)) return `${field.label} ${opl}`;
  if (field.type === 'boolean') return `${field.label} ${opl} ${f.value === true ? 'Yes' : 'No'}`;
  if (f.op === 'is any of')  return `${field.label}: ${_listText(f.value)}`;
  if (f.op === 'is none of') return `${field.label} ${opl} ${_listText(f.value)}`;
  if (f.op === 'between') return `${field.label} ${opl} ${f.value} and ${f.value2}`;
  return `${field.label} ${opl} ${f.value}`;
}


/* ---------- starea unui tabel: filtre, căutare, sortare ----------
   Doar în memorie: se păstrează cât timp pagina rămâne deschisă (trecerea de la o
   filă la alta nu le pierde), dar la reîncărcare pornesc goale — decis de Ana. */
/* `mode`: 'and' | 'or' — cum se combină filtrele. `advanced`: se vede panoul de reguli. */
function newFilterState() { return { filters: [], q: '', sort: null, mode: 'and', advanced: false }; }

/* Kept in memory while the page stays open, so moving between tabs does not lose
   a filter. Gone on reload — Ana's decision (2 Oct 2026): filters are never
   written to the browser or the database. */
const _kept = {};
function keepFilters(table, state) { _kept[table] = state; }
function keptFilters(table) { return _kept[table] || null; }


/* ---------- comutatorul „De verificat" și numărul lui ----------
   E o scurtătură pentru filtrul needsReview, nu un test separat. Numărul = câte
   rânduri ar arăta comutatorul, ținând cont de celelalte filtre active.

   Numele NU e reviewCount: data.jsx are deja un reviewCount() și, fără pas de
   build, o a doua funcție cu același nume o înlocuiește în tăcere peste tot. */
function reviewFilterOn(filters) {
  return (filters || []).some(f => f.key === 'needsReview' && f.op === 'is' && f.value === true);
}
function toggleReviewFilter(filters) {
  return reviewFilterOn(filters)
    ? filters.filter(f => f.key !== 'needsReview')
    : [...(filters || []).filter(f => f.key !== 'needsReview'), { key: 'needsReview', op: 'is', value: true }];
}
function filteredReviewCount(rows, state, table, today) {
  const others = (state.filters || []).filter(f => f.key !== 'needsReview');
  const withReview = [...others, { key: 'needsReview', op: 'is', value: true }];
  return applySearch(applyFilters(rows, withReview, table, today, state.mode), state.q, table).length;
}

/* O condiție de pornire rezonabilă pentru un câmp abia ales. */
function newFilter(field) {
  if (!field) return null;
  if (field.type === 'date')    return { key: field.key, op: 'between' };      // starts empty: the person picks the dates (no quick buttons, Ana 6 Oct 2026)
  if (field.type === 'boolean') return { key: field.key, op: 'is', value: true };
  if (field.type === 'enum')    return { key: field.key, op: 'is any of', value: [] };
  if (field.type === 'number')  return { key: field.key, op: '=', value: '' };
  return { key: field.key, op: 'contains', value: '' };
}

Object.assign(window, {
  FILTER_FIELDS, CONDITIONS, OP_LABELS, DATE_PRESETS, DEFAULT_SORT, NO_PROJECT, NO_CATEGORY,
  fieldsFor, filterableFields, fieldByKey, conditionsFor, isListOp,
  resolvePreset, dateBounds, matchesFilter, isComplete,
  applyFilters, applySearch, sortRows, visibleRows,
  describeFilter, newFilterState, keepFilters, keptFilters,
  reviewFilterOn, toggleReviewFilter, filteredReviewCount, newFilter,
});
