/* ============================================================
   P&L App (Lite) · Data layer, backed by the pnl-lite Supabase project
   ------------------------------------------------------------
   Built on the live US demo's screens (17 Nov 2026, brief 65). The screens were written
   for the demo's tables; this file reads and saves Lite's tables instead and hands the
   screens the SAME shape of record the demo did, so the screens barely change.

   Lite's tables (briefs/65-step2-database.sql, 65-step3-columns.sql):
     companies, company_members, categories, money_in, money_out.
   Each person only ever gets their own company's rows: the database enforces it
   (row-level security). This file also asks for company_id = theirs on every read.

   How Lite's columns map to the screens' names (the internal names stay Romanian,
   from the demo: incasari = money in, plati = money out, client = customer,
   furnizor = vendor, sumaNeta = amount before sales tax, cotaTva = sales tax rate):
     date -> data, name -> client / furnizor, amount -> sumaNeta,
     sales_tax_rate -> cotaTva, invoice_no -> nrFactura, note -> notes,
     due_date -> dataScadenta, category_id -> categorie (the category's NAME).
     paid (yes/no) -> status: Paid, Unpaid, or Overdue (unpaid and the due date has
     passed; due today is not overdue). Overdue is worked out, never stored.
     Categories: 'direct' in the database is 'job' inside the screens' maths
     (the demo called direct costs "job costs"); the screens say "Direct cost".

   Paid-plan features (jobs, vehicles, part payments, splits, documents, import) do not
   exist in Lite's tables: their lists are always empty, so the demo's maths simply
   finds nothing. The screens show them LOCKED (lock.jsx).
   ============================================================ */

/* ---------- formatters ---------- */
const US_MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const US_MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

const nfMoney = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const nfInt = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });

/* A minus sign goes before the dollar sign: -$1,234.56 */
function money(n) { return nfMoney.format(n || 0); }                                        // 1,234.56
function moneyUSD(n) { const v = n || 0; return (v < 0 ? '-$' : '$') + nfMoney.format(Math.abs(v)); }     // $1,234.56
function money0(n) { return nfInt.format(Math.round(n || 0)); }                             // 1,235
function money0USD(n) { const v = Math.round(n || 0); return (v < 0 ? '-$' : '$') + nfInt.format(Math.abs(v)); }  // $1,235
/* "1 invoice", "3 invoices": the noun with an s unless there is exactly one */
function plural(n, one, many) { return Math.abs(n) === 1 ? one : (many || one + 's'); }
function pct(n, dec = 1) { return (n || 0).toLocaleString('en-US', { minimumFractionDigits: dec, maximumFractionDigits: dec }) + '%'; }

function fmtDate(iso) {
  if (!iso) return '—';
  const [y, m, d] = iso.split('-');
  return `${m}/${d}/${y}`;                                          // 10/27/2026
}
function fmtDateLong(iso) {
  if (!iso) return '—';
  const [y, m, d] = iso.split('-');
  return `${US_MONTHS[parseInt(m, 10) - 1]} ${parseInt(d, 10)}, ${y}`;   // October 27, 2026
}
function fmtDateShort(iso) {
  if (!iso) return '—';
  const [, m, d] = iso.split('-');
  return `${US_MONTHS_SHORT[parseInt(m, 10) - 1]} ${parseInt(d, 10)}`;   // Oct 27
}
function todayISO() {
  // real current date in the user's local timezone, formatted YYYY-MM-DD
  const d = new Date();
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}
/* Calendar-day arithmetic done in UTC, so the user's time zone and the clock change cannot move the result. */
function addDays(iso, days) {
  const [y, m, d] = String(iso).split('-').map(Number);
  return new Date(Date.UTC(y, m - 1, d + (days || 0))).toISOString().slice(0, 10);
}
function daysBetween(fromIso, toIso) { return Math.round((Date.parse(toIso + 'T00:00:00Z') - Date.parse(fromIso + 'T00:00:00Z')) / 864e5); }
function monthKey(iso) { return iso ? iso.slice(0, 7) : ''; }
function monthLabel(key) {
  if (!key) return '';
  const [y, m] = key.split('-');
  return US_MONTHS_SHORT[parseInt(m, 10) - 1] + " '" + y.slice(2);     // Oct '26
}
/* "Lone Star Builders" -> "LS": the letters in the sidebar's square. */
function initialsOf(name) {
  const words = String(name || '').replace(/[^A-Za-z0-9 ]/g, ' ').split(/\s+/).filter(Boolean)
    .filter(w => !/^(llc|inc|co|corp|ltd|the|and|of)$/i.test(w));
  return ((words[0] || '?')[0] + (words[1] ? words[1][0] : '')).toUpperCase();
}

/* ---------- sales tax math (the demo's code called it VAT; the names are kept) ---------- */
function tvaOf(net, cota) { return (net || 0) * (cota || 0) / 100; }
function brutOf(net, cota) { return (net || 0) * (1 + (cota || 0) / 100); }
/* The sales tax of a row. tvaSuma is always null in Lite (the tax is amount × rate, saved worked out),
   but the screens read it through this, so it stays. */
function vatOfRow(r) { return (r && r.tvaSuma != null) ? Number(r.tvaSuma) : tvaOf(r && r.sumaNeta, r && r.cotaTva); }
function vatResetFor(patch) { return (('sumaNeta' in patch || 'cotaTva' in patch) && !('tvaSuma' in patch)) ? { tvaSuma: null } : {}; }
/* The rates offered when typing money in: Houston's 8.25% and 0% for work that is not taxable.
   Another rate can be typed. Money out has no rate: sales tax on a bill is part of the cost. */
const STD_VAT = [8.25, 0];
function usualVatRates() { return STD_VAT.slice(); }
function vatRateInfo(r) {
  const rate = r && r.cotaTva != null ? r.cotaTva : 0;
  return { multiple: false, rate, label: rate + '%' };
}
/* What an edit of amount / tax / total changes (amount + tax = total). Lite stores no exact tax: `exactOk` is ignored. */
function vatEditPatch(row, field, v) {
  const r2 = n => Math.round(n * 100) / 100;
  const rate = row.cotaTva || 0;
  if (field === 'net') return { sumaNeta: r2(v) };
  if (field === 'gross') return { sumaNeta: r2(v / (1 + rate / 100)) };
  return {};
}
function brutOfRow(r) { return (r ? (r.sumaNeta || 0) : 0) + vatOfRow(r); }
const round2 = n => Math.round((Number(n) || 0) * 100) / 100;

/* ---------- status ---------- */
/* What the screens show. Overdue = not paid and the due date has passed (due today is not overdue). */
const STATUS_IN = ['Paid', 'Unpaid', 'Overdue'];
const STATUS_OUT = ['Paid', 'Unpaid', 'Overdue'];
/* What a person can pick: Overdue follows from the due date by itself. */
const STATUS_PICK = ['Paid', 'Unpaid'];
const UNPAID_IN = ['Unpaid', 'Overdue'];
const UNPAID_OUT = ['Unpaid', 'Overdue'];
function statusOf(paid, dueDate, today) {
  if (paid) return 'Paid';
  return dueDate && dueDate < (today || todayISO()) ? 'Overdue' : 'Unpaid';
}
/* An unpaid row with no due date is something a person must complete (shown in To review). */
function missingDueDate(r, kind) { return (kind === 'in' ? UNPAID_IN : UNPAID_OUT).includes(r.status) && !r.dataScadenta; }
/* Kept for the screens and filters that still name them; Lite has no such fields. */
const TIP_IN = ['Invoice'];
const METODE = [];
const FUEL_CAT = null;
const REPAIRS_CAT = null;

/* ============================================================
   Supabase client
   ============================================================ */
const _sb = window.supabase.createClient(window.SUPABASE_URL, window.SUPABASE_KEY, {
  auth: { persistSession: true, autoRefreshToken: true },   // the login must survive a reload
});

/* ============================================================
   Cache + reactive store
   ============================================================ */
const DB = {
  user: null,        // { id, email } of the person logged in
  company: null,     // { id, name, plan, country, currency }
  membership: null,  // { company_id, role, terms_accepted_at }
  incasari: [],      // money in
  plati: [],         // money out
  categorii: [],     // EXPENSE categories: { id, name, costType: 'job' (direct) | 'overhead' }
  categoriiIn: [],   // INCOME categories: { id, name }
  furnizori: [],     // vendors: worked out from the money-out rows (plus any typed in this session)
  clienti: [],       // customers: worked out from the money-in rows
  // paid-plan features: always empty in Lite
  transe: [], transePl: [], proiecte: [], vehicule: [], furnizorAlias: [], clientAlias: [],
  _loaded: false,    // false until the first full load completes
  _error: null,      // a message if the database can't be reached
  _noCompany: false, // logged in, but not linked to a company yet
};

/* A failed save is shown on screen: what failed, and why. */
function reportError(what, error) {
  console.error(what, error);
  const reason = error && (error.message || error.details) ? String(error.message || error.details) : 'unknown error';
  window.dispatchEvent(new CustomEvent('app-error', { detail: { msg: what + ': ' + reason } }));
}

const _listeners = new Set();
function notify() { _listeners.forEach(fn => fn()); }
function subscribe(fn) { _listeners.add(fn); return () => _listeners.delete(fn); }

function useDB() {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => subscribe(force), []);
  return DB;
}

function companyName() { return (DB.company && DB.company.name) || 'Your company'; }

/* ============================================================
   Mappers: database row  <->  the screens' record
   ============================================================ */
const num = v => (v == null ? 0 : Number(v));
const _catNameById = id => { const c = DB.categorii.concat(DB.categoriiIn).find(x => x.id === id); return c ? c.name : ''; };

function rowToInc(r) {
  const rec = {
    id: r.id, nr: null,
    data: r.date, client: r.name, proiect: null,
    tip: 'Invoice', nrFactura: r.invoice_no || '', descriere: '',
    sumaNeta: num(r.amount), cotaTva: num(r.sales_tax_rate), tvaSuma: null,
    categorie: _catNameById(r.category_id), categoryId: r.category_id || null,
    metoda: null,
    termenPlata: r.due_date && r.date ? daysBetween(r.date, r.due_date) : null,
    dataScadenta: r.due_date || null,
    paid: !!r.paid, status: statusOf(r.paid, r.due_date),
    source: 'manual', sourceFile: null,
    notes: r.note || null,
    createdAt: r.created_at,
  };
  Object.assign(rec, reviewFlagsIncasare(rec));
  return rec;
}
function rowToPl(r) {
  const rec = {
    id: r.id, nr: null,
    data: r.date, furnizor: r.name, proiect: null,
    categorie: _catNameById(r.category_id), categoryId: r.category_id || null,
    nrFactura: r.invoice_no || '', descriere: '',
    sumaNeta: num(r.amount), cotaTva: 0, tvaSuma: null, sumaBruta: null,
    metoda: null, dataPlatii: null,
    dataScadenta: r.due_date || null,
    paid: !!r.paid, status: statusOf(r.paid, r.due_date), aprobatDe: null,
    source: 'manual', sourceFile: null, vehiclePlate: null, split: null,
    notes: r.note || null,
    createdAt: r.created_at,
  };
  Object.assign(rec, reviewFlagsPlata(rec));
  return rec;
}
const rowToCat = r => ({ id: r.id, name: r.name, costType: r.cost_type === 'direct' ? 'job' : r.cost_type, sort: r.sort || 0 });

/* A change from the screens (their names) -> the database's columns. Anything Lite has no
   column for (job, type, method...) is dropped here, so it can never reach the database. */
function _toCols(patch, kind, current) {
  const out = {};
  const cats = kind === 'in' ? DB.categoriiIn : DB.categorii;
  if ('data' in patch) out.date = patch.data;
  if ('client' in patch && kind === 'in') out.name = String(patch.client || '').trim();
  if ('furnizor' in patch && kind === 'out') out.name = String(patch.furnizor || '').trim();
  if ('sumaNeta' in patch) out.amount = round2(patch.sumaNeta);
  if ('nrFactura' in patch) out.invoice_no = patch.nrFactura ? String(patch.nrFactura).trim() : null;
  if ('notes' in patch) out.note = patch.notes ? String(patch.notes) : null;
  if ('dataScadenta' in patch) out.due_date = patch.dataScadenta || null;
  if ('status' in patch) out.paid = patch.status === 'Paid';
  if ('categorie' in patch) {
    const c = cats.find(x => x.name === patch.categorie);
    out.category_id = c ? c.id : null;
  }
  if (kind === 'in' && ('sumaNeta' in patch || 'cotaTva' in patch)) {
    const amount = 'sumaNeta' in patch ? round2(patch.sumaNeta) : (current ? current.sumaNeta : 0);
    const rate = 'cotaTva' in patch ? Number(patch.cotaTva) || 0 : (current ? current.cotaTva : 0);
    out.sales_tax_rate = rate;
    out.sales_tax = round2(amount * rate / 100);   // always worked out: amount × rate
  }
  return out;
}

/* ============================================================
   Loading
   ============================================================ */
/* The database returns AT MOST 1,000 rows per request and says nothing when it cuts the list off.
   So rows are fetched 1,000 at a time until a short page comes back. checkRowsComplete() proves nothing was missed. */
const _PAGE = 1000;
async function fetchAllRows(table, orderCol) {
  let all = [];
  for (let from = 0; ; from += _PAGE) {
    const { data, error } = await _sb.from(table).select('*').eq('company_id', DB.company.id)
      .order(orderCol, { ascending: false }).order('id', { ascending: true })
      .range(from, from + _PAGE - 1);
    if (error) return { data: null, error };
    all = all.concat(data);
    if (data.length < _PAGE) return { data: all, error: null };
  }
}

/* Run in the browser console: await checkRowsComplete()
   Counts each table in the database and compares it with what the app loaded. ok:true is the pass. */
async function checkRowsComplete() {
  const tables = { money_in: DB.incasari, money_out: DB.plati };
  const out = {};
  for (const t of Object.keys(tables)) {
    const { count, error } = await _sb.from(t).select('*', { count: 'exact', head: true }).eq('company_id', DB.company.id);
    out[t] = error ? { ok: false, error: error.message } : { ok: count === tables[t].length, loaded: tables[t].length, expected: count };
  }
  out.ok = Object.values(out).every(x => x.ok);
  return out;
}

async function reloadCategorii() {
  const { data, error } = await fetchAllRows('categories', 'created_at');
  if (error) throw error;
  const sorted = data.slice().sort((a, b) => (a.sort || 0) - (b.sort || 0) || a.name.localeCompare(b.name));
  DB.categorii = sorted.filter(c => c.kind === 'expense').map(rowToCat);
  DB.categoriiIn = sorted.filter(c => c.kind === 'income').map(rowToCat);
  notify();
}
async function reloadIncasari() {
  const { data, error } = await fetchAllRows('money_in', 'date');
  if (error) { reportError('Could not load money in', error); return; }
  DB.incasari = data.map(rowToInc);
  _rebuildNames('client');
  notify();
}
async function reloadPlati() {
  const { data, error } = await fetchAllRows('money_out', 'date');
  if (error) { reportError('Could not load money out', error); return; }
  DB.plati = data.map(rowToPl);
  _rebuildNames('furnizor');
  notify();
}

async function loadAll() {
  try {
    // Which company am I in? The database only shows a person their own membership rows.
    const { data: mem, error: e1 } = await _sb.from('company_members')
      .select('company_id, role, terms_accepted_at, created_at').eq('user_id', DB.user.id).order('created_at');
    if (e1) throw e1;
    if (!mem || !mem.length) { DB._noCompany = true; return; }
    // Version 1: one company per person. If someone is ever in two, the first one opens.
    DB.membership = mem[0];
    const { data: co, error: e2 } = await _sb.from('companies').select('*').eq('id', mem[0].company_id).single();
    if (e2) throw e2;
    DB.company = co;
    await reloadCategorii();                              // first: the rows need the category names
    await Promise.all([reloadIncasari(), reloadPlati()]);
    DB._error = null;
  } catch (e) {
    console.error('loadAll', e);
    DB._error = 'Could not load your data.';
  } finally {
    DB._loaded = true;
    notify();
  }
}

/* ---------- saving: money in ---------- */
async function addIncasare(rec) {
  const row = _toCols({ cotaTva: 8.25, ...rec, status: rec.status || 'Unpaid' }, 'in', null);
  const { error } = await _sb.from('money_in').insert({ ...row, company_id: DB.company.id });
  if (error) { reportError('Could not add it', error); return; }
  await reloadIncasari();
}
async function updateIncasare(id, patch) {
  const cur = DB.incasari.find(r => r.id === id);
  const row = _toCols(patch, 'in', cur);
  if (!Object.keys(row).length) return;
  const { error } = await _sb.from('money_in').update(row).eq('id', id);
  if (error) { reportError('Could not save the change', error); return; }
  await reloadIncasari();
}
async function deleteIncasare(id) {
  const { error } = await _sb.from('money_in').delete().eq('id', id);
  if (error) { reportError('Could not delete it', error); return; }
  await reloadIncasari();
}

/* ---------- saving: money out ---------- */
async function addPlata(rec) {
  const row = _toCols({ ...rec, status: rec.status || 'Unpaid' }, 'out', null);
  const { error } = await _sb.from('money_out').insert({ ...row, company_id: DB.company.id });
  if (error) { reportError('Could not add it', error); return; }
  await reloadPlati();
}
async function updatePlata(id, patch) {
  const row = _toCols(patch, 'out', DB.plati.find(r => r.id === id));
  if (!Object.keys(row).length) return;
  const { error } = await _sb.from('money_out').update(row).eq('id', id);
  if (error) { reportError('Could not save the change', error); return; }
  await reloadPlati();
}
async function deletePlata(id) {
  const { error } = await _sb.from('money_out').delete().eq('id', id);
  if (error) { reportError('Could not delete it', error); return; }
  await reloadPlati();
}

/* ---------- categories ---------- */
/* kind: 'expense' (costType 'job' = direct, or 'overhead') or 'income'. */
async function addCategorie(name, costType, kind) {
  const k = kind || 'expense';
  const all = DB.categorii.concat(DB.categoriiIn);
  const sort = all.reduce((m, c) => Math.max(m, c.sort || 0), 0) + 1;
  const { error } = await _sb.from('categories').insert({
    company_id: DB.company.id, name: String(name).trim(), kind: k,
    cost_type: k === 'expense' ? (costType === 'overhead' ? 'overhead' : 'direct') : null, sort,
  });
  if (error) { reportError(error.code === '23505' ? 'That category already exists' : 'Could not add the category', error); return false; }
  await reloadCategorii();
  return true;
}
/* Used by the pick-or-add field: add the category unless the same name already exists in another
   spelling; return the name to select. A category added this way is a direct cost until changed in Admin. */
async function addCategorieNamed(name, kind) {
  const typed = String(name || '').trim();
  if (!typed) return null;
  const list = kind === 'income' ? DB.categoriiIn : DB.categorii;
  const same = findSameName(list.map(c => c.name), typed);
  if (same) return same;
  if (!(await addCategorie(typed, 'job', kind || 'expense'))) return null;
  return typed;
}
async function renameCategorie(id, name) {
  const { error } = await _sb.from('categories').update({ name: String(name).trim() }).eq('id', id);
  if (error) { reportError(error.code === '23505' ? 'That name is already used' : 'Could not rename it', error); return; }
  // rows point at the category by id, so they follow the new name by themselves
  await reloadCategorii();
  await Promise.all([reloadIncasari(), reloadPlati()]);
}
/* Direct cost or overhead: what gross profit and net income are built on. */
async function setCategoryType(id, costType) {
  const { error } = await _sb.from('categories').update({ cost_type: costType === 'overhead' ? 'overhead' : 'direct' }).eq('id', id);
  if (error) { reportError('Could not save the change', error); return; }
  await reloadCategorii();
}
/* Only a category no row uses can be deleted (the database refuses the others too). */
async function deleteCategorie(id) {
  const { error } = await _sb.from('categories').delete().eq('id', id);
  if (error) { reportError(error.code === '23503' ? 'This category is still used by some rows' : 'Could not delete it', error); return; }
  await reloadCategorii();
}
function countPlatiByCat(name) { return DB.plati.filter(p => p.categorie === name).length; }
function countByCategoryId(id) { return DB.plati.filter(p => p.categoryId === id).length + DB.incasari.filter(r => r.categoryId === id).length; }

/* ---------- vendors and customers ----------
   Lite keeps no separate list: the names are the ones on the rows. A name typed in a form is
   kept in memory until it is saved on a row. Rename and merge change the rows themselves. */
const _typedNames = { furnizor: new Set(), client: new Set() };
function _rebuildNames(kind) {
  const rows = kind === 'furnizor' ? DB.plati.map(r => r.furnizor) : DB.incasari.map(r => r.client);
  const names = [...new Set([...rows, ..._typedNames[kind]].filter(Boolean))].sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
  const list = names.map(n => ({ id: n, name: n, key: nameKey(n) }));
  if (kind === 'furnizor') DB.furnizori = list; else DB.clienti = list;
}
function namesOf(kind) { return (kind === 'furnizor' ? DB.furnizori : DB.clienti).map(x => x.name); }
function countByName(kind, name) {
  return kind === 'furnizor' ? DB.plati.filter(p => p.furnizor === name).length : DB.incasari.filter(r => r.client === name).length;
}
function clientSuggestions() { return namesOf('client'); }
function furnizorSuggestions() { return namesOf('furnizor'); }
/* Add a name to pick from, or, if the same name already exists in another spelling
   ("HOME DEPOT #6512" when "Home Depot" is there), return the existing one. */
async function addName(kind, name) {
  const typed = String(name || '').trim();
  if (!typed) return null;
  const same = findSameName(namesOf(kind), typed);
  if (same) return same;
  _typedNames[kind].add(typed);
  _rebuildNames(kind); notify();
  return typed;
}
/* Rename everywhere at once: every row with the old name gets the new one. `id` is the old name. */
async function renameName(kind, id, newName) {
  const to = String(newName || '').trim();
  if (!to || to === id) return true;
  const table = kind === 'furnizor' ? 'money_out' : 'money_in';
  const { error } = await _sb.from(table).update({ name: to }).eq('company_id', DB.company.id).eq('name', id);
  if (error) { reportError('Could not rename it', error); return false; }
  _typedNames[kind].delete(id);
  await (kind === 'furnizor' ? reloadPlati() : reloadIncasari());
  return true;
}
/* Merge one name into another: its rows move to the other name. */
function mergeNames(kind, fromId, toId) { return renameName(kind, fromId, toId); }
/* Remove a name nobody uses (only one typed in this session can be unused). */
async function deleteName(kind, id) {
  if (countByName(kind, id) > 0) return false;
  _typedNames[kind].delete(id);
  _rebuildNames(kind); notify();
  return true;
}
function reloadFurnizori() { _rebuildNames('furnizor'); notify(); }
function reloadClienti() { _rebuildNames('client'); notify(); }

/* ---------- paid-plan features: nothing in Lite ---------- */
function transeOf() { return []; }
function transePlOf() { return []; }
function platitOf() { return 0; }
function incasatOf() { return 0; }
/* What has really been collected / paid on a row: all of it when it is marked Paid, otherwise nothing. */
function incasatEfectiv(r) { return r.status === 'Paid' ? brutOfRow(r) : 0; }
function platitEfectiv(r) { return r.status === 'Paid' ? brutOfRow(r) : 0; }
function paidOfParts(list) { return list.reduce((s, r) => s + platitEfectiv(wholeOf(r)) * (r._whole && r._whole.sumaNeta ? r.sumaNeta / r._whole.sumaNeta : 1), 0); }
function activeProjects() { return []; }
function activeVehicles() { return []; }

/* ---------- To review: worked out from the row, never stored ---------- */
const _FUTURE_LIMIT_DAYS = 183;   // ~6 months: a date further out than this is almost always a typo
function reviewFlagsPlata(o) {
  const reasons = [];
  if (!o.categorie) reasons.push('Missing category');
  if (o.data && o.data > addDays(todayISO(), _FUTURE_LIMIT_DAYS)) reasons.push('Future date');
  return { needsReview: reasons.length > 0, reviewReason: reasons.join('; ') || null };
}
function reviewFlagsIncasare(o) {
  const reasons = [];
  if (o.data && o.data > addDays(todayISO(), _FUTURE_LIMIT_DAYS)) reasons.push('Future date');
  return { needsReview: reasons.length > 0, reviewReason: reasons.join('; ') || null };
}
function reviewCount() {
  return DB.incasari.filter(r => r.needsReview || missingDueDate(r, 'in')).length + DB.plati.filter(r => r.needsReview || missingDueDate(r, 'out')).length;
}

/* totals over a list of records (amount before tax based) */
function totals(list) {
  return list.reduce((a, r) => {
    const t = vatOfRow(r);
    a.net += r.sumaNeta; a.tva += t; a.brut += r.sumaNeta + t; return a;
  }, { net: 0, tva: 0, brut: 0, count: list.length });
}

/* ============================================================
   Terms (first login): the date is stored on the person's membership row.
   ============================================================ */
async function acceptTerms() {
  const at = new Date().toISOString();
  const { error } = await _sb.from('company_members').update({ terms_accepted_at: at })
    .eq('user_id', DB.user.id).eq('company_id', DB.membership.company_id);
  if (error) { reportError('Could not save', error); return false; }
  DB.membership = { ...DB.membership, terms_accepted_at: at };
  notify();
  return true;
}

/* ============================================================
   Authentication: thin wrappers over supabase.auth.
   The database only answers a logged-in person, so this file loads NOTHING when it
   runs. app.jsx calls startSession() once a session exists.
   ============================================================ */
async function getSession() { const { data } = await _sb.auth.getSession(); return data.session; }
async function signIn(email, password) { const { error } = await _sb.auth.signInWithPassword({ email, password }); return { error }; }
/* "Forgot password": Supabase emails a link back to this page. */
async function sendPasswordReset(email) {
  const { error } = await _sb.auth.resetPasswordForEmail(email, { redirectTo: window.location.origin + window.location.pathname });
  return { error };
}
/* After an invite or a reset link: the link has logged the person in; they choose a password. */
async function setNewPassword(password) { const { error } = await _sb.auth.updateUser({ password }); return { error }; }
function onAuthChange(callback) {
  const { data } = _sb.auth.onAuthStateChange((event, session) => callback(session, event));
  return () => data.subscription.unsubscribe();
}
async function signOut() {
  await _sb.auth.signOut();
  // In a browser, start again from a clean page: nothing of the last person stays in memory
  // (not even the filters or the period they picked). The lines below cover the tests too.
  if (typeof window.location !== 'undefined' && window.location.replace) { window.location.replace(window.location.pathname); }
  // don't leave the books in memory
  Object.assign(DB, { user: null, company: null, membership: null, incasari: [], plati: [], categorii: [], categoriiIn: [],
    furnizori: [], clienti: [], _loaded: false, _error: null, _noCompany: false });
  _typedNames.furnizor.clear(); _typedNames.client.clear();
  notify();
}
function currentUserEmail() { return DB.user ? DB.user.email : null; }
async function startSession(session) {
  DB.user = { id: session.user.id, email: session.user.email };
  DB._loaded = false; DB._noCompany = false; notify();
  await loadAll();
}

/* Overdue is worked out from today's date. If the page stays open past midnight, work it out again. */
let _statusDay = todayISO();
if (typeof setInterval === 'function') setInterval(() => {
  if (todayISO() === _statusDay) return;
  _statusDay = todayISO();
  DB.incasari = DB.incasari.map(r => ({ ...r, status: statusOf(r.paid, r.dataScadenta) }));
  DB.plati = DB.plati.map(r => ({ ...r, status: statusOf(r.paid, r.dataScadenta) }));
  notify();
}, 5 * 60 * 1000);

/* Someone else in the same company may have changed things: refresh when the tab comes
   back into view after a minute or more away. (No live updates in version 1.) */
let _hiddenAt = null;
document.addEventListener('visibilitychange', () => {
  if (document.hidden) { _hiddenAt = Date.now(); return; }
  if (_hiddenAt && Date.now() - _hiddenAt > 60000 && DB.company) {
    reloadCategorii().then(() => Promise.all([reloadIncasari(), reloadPlati()])).catch(e => console.error('refresh', e));
  }
  _hiddenAt = null;
});

/* expose (the screens read these from window) */
Object.assign(window, {
  DB, useDB, subscribe, notify, companyName, initialsOf,
  money, moneyUSD, money0, money0USD, plural, pct, fmtDate, fmtDateLong, fmtDateShort, todayISO, addDays, daysBetween,
  monthKey, monthLabel, US_MONTHS, US_MONTHS_SHORT, round2,
  tvaOf, brutOf, vatOfRow, brutOfRow, vatResetFor, vatRateInfo, vatEditPatch, STD_VAT, usualVatRates, totals,
  STATUS_IN, STATUS_OUT, STATUS_PICK, TIP_IN, METODE, FUEL_CAT, REPAIRS_CAT, UNPAID_IN, UNPAID_OUT, statusOf, missingDueDate,
  addIncasare, updateIncasare, deleteIncasare, addPlata, updatePlata, deletePlata,
  transeOf, incasatOf, incasatEfectiv, transePlOf, platitOf, platitEfectiv, paidOfParts,
  addCategorie, addCategorieNamed, renameCategorie, setCategoryType, deleteCategorie, countPlatiByCat, countByCategoryId,
  activeProjects, activeVehicles, reviewCount, clientSuggestions, furnizorSuggestions,
  reviewFlagsPlata, reviewFlagsIncasare,
  loadAll, fetchAllRows, checkRowsComplete, reportError,
  namesOf, countByName, addName, renameName, mergeNames, deleteName, reloadFurnizori, reloadClienti,
  acceptTerms, getSession, signIn, signOut, sendPasswordReset, setNewPassword, onAuthChange, currentUserEmail, startSession,
  rowToInc, rowToPl,
});
