/* ============================================================
   P&L App (Lite) · the money maths behind P&L and the Dashboard (from the US demo's jobs.jsx)
   ------------------------------------------------------------
   Lite note (17 Nov 2026): Lite has no jobs, splits or vehicles, so the job and vehicle
   functions below always find nothing; they are kept so the maths stays the demo's tested
   maths. Inside this file 'job cost' means what the screens call a DIRECT cost. Gross profit
   (revenue minus direct costs) is new in Lite: incomeStatement() returns it.
   ------------------------------------------------------------
   Plain functions, no screens. Every screen that shows one of these figures
   calls the function here, and the rows it opens come from the SAME function,
   so a card and the rows behind it can never disagree. jobs.test.js checks them.

   The rules, in plain English:
   - Every expense category is a JOB COST (materials, subcontractors, crew payroll)
     or an OVERHEAD (rent, insurance, office, trucks). Set per category in Admin.
     A category nobody has marked yet counts as a job cost.
   - A job cost belongs to the job on the row, or is SPLIT across several jobs
     (one bill, two sites; the monthly crew payroll). A job cost with neither
     is a "cost with no job".
   - Since 13 Nov 2026 (Ana, like Socend's brief 60) a split can also change the
     CATEGORY: each part has its own amount, category and job. A part follows its
     own category: a job-cost part belongs to its job (or is "a cost with no job"),
     an overhead part needs no job. Old splits (jobs only) keep the bill's category.
     Every figure below works on PARTS (partRows), never on the whole bill, so a
     split bill counts each part in its own place and every total still adds up.
   - Overheads are shared across the jobs each month, by each job's share of
     that month's job costs ("worked out each month", Ana 26 Oct 2026). A month
     with no job costs at all has nobody to share with: its overheads stay
     "not shared" and are shown as such.
   - QuickBooks view = profit before overheads. With overheads shared = after.
   - Amounts are before sales tax. Sales tax charged to customers is owed to the
     state and is never income; money owed to us is shown WITH sales tax,
     because that is what the customer has to pay.
   ============================================================ */

/* ---------- categories and cost parts ---------- */
function catTypeOf(name) {
  const c = DB.categorii.find(x => x.name === name);
  return (c && c.costType) || 'job';
}
/* The parts of a cost: [{ job, categorie, amount }]. A cost that is not split is one part (its own job and category).
   A split part with no category of its own (splits made before 13 Nov 2026) has the bill's category. */
function costLines(p) {
  if (!(p.split && p.split.length)) return [{ job: p.proiect || '', categorie: p.categorie || '', amount: p.sumaNeta }];
  const parts = p.split.map(s => ({ job: s.job || '', categorie: s.categorie || p.categorie || '', amount: Number(s.amount) || 0 }));
  // the bill's amount was changed after it was split: the parts are scaled to it, so every total still matches the P&L
  const sum = parts.reduce((a, l) => a + l.amount, 0);
  if (sum > 0 && Math.abs(sum - p.sumaNeta) > 0.009) parts.forEach(l => { l.amount = l.amount * p.sumaNeta / sum; });
  return parts;
}
/* One "part row" per part: the bill's own fields, with the part's amount, category and job. A bill that is not split
   is returned as it is. `_whole` points back to the real bill, so opening a part opens the bill. */
function partRows(plati) {
  const out = [];
  plati.forEach(p => {
    if (!(p.split && p.split.length)) { out.push(p); return; }
    costLines(p).forEach((l, i) => out.push(Object.assign({}, p, { sumaNeta: l.amount, categorie: l.categorie, proiect: l.job, split: null, _whole: p, _part: i })));
  });
  return out;
}
function wholeOf(r) { return (r && r._whole) || r; }
/* An overhead: every part of it is in an overhead category (a part row or a bill that is not split: its category). */
function isOverhead(row) { return costLines(row).every(l => catTypeOf(l.categorie) === 'overhead'); }
/* A bill split across categories (not only across jobs). */
function hasCategorySplit(p) { return !!(p.split && p.split.length && new Set(costLines(p).map(l => l.categorie)).size > 1); }
/* The jobs a cost belongs to, with how much each carries (any part that has a job). */
function costParts(p) { return costLines(p).filter(l => l.job).map(l => ({ job: l.job, amount: l.amount })); }
/* One line per job-cost part that has a job. `row` is the real bill. */
function jobCostLines(plati) {
  return partRows(plati).filter(pr => !isOverhead(pr) && pr.proiect)
    .map(pr => ({ row: wholeOf(pr), job: pr.proiect, categorie: pr.categorie, amount: pr.sumaNeta, month: monthKey(pr.data) }));
}
/* Job-cost PARTS that nobody has tagged to a job yet (part rows, so their amount is the part's). */
function unassignedCosts(plati) { return partRows(plati).filter(pr => !isOverhead(pr) && !pr.proiect); }
/* Overhead PARTS (part rows). */
function overheadRows(plati) { return partRows(plati).filter(isOverhead); }

/* ---------- overheads shared by month ---------- */
/* Returns { byJob: {job: amount}, lines: [{job, month, amount, monthOverheads}], unshared, unsharedMonths } */
function overheadShares(plati) {
  const ohByMonth = {}, jobByMonth = {};
  overheadRows(plati).forEach(p => { const m = monthKey(p.data); ohByMonth[m] = (ohByMonth[m] || 0) + p.sumaNeta; });
  jobCostLines(plati).forEach(l => {
    const m = jobByMonth[l.month] || (jobByMonth[l.month] = {});
    m[l.job] = (m[l.job] || 0) + l.amount;
  });
  const byJob = {}, lines = [];
  let unshared = 0; const unsharedMonths = [];
  Object.keys(ohByMonth).sort().forEach(m => {
    const jobs = jobByMonth[m] || {}, total = Object.values(jobs).reduce((a, b) => a + b, 0);
    if (!(total > 0)) { unshared += ohByMonth[m]; unsharedMonths.push(m); return; }
    Object.keys(jobs).forEach(job => {
      const amount = ohByMonth[m] * jobs[job] / total;
      byJob[job] = (byJob[job] || 0) + amount;
      lines.push({ job, month: m, amount, monthOverheads: ohByMonth[m], jobShare: jobs[job] / total });
    });
  });
  return { byJob, lines, unshared, unsharedMonths };
}

/* ---------- money in ---------- */
const BILLED_TYPES = ['Invoice', 'Change order'];   // what retainage is held on (not deposits, not the release itself)
/* What is still owed on a money-in row, sales tax included. */
function owedOn(r) { return UNPAID_IN.includes(r.status) ? Math.max(0, brutOfRow(r) - incasatOf(r.id)) : 0; }
function daysLate(r, today) { return r.dataScadenta ? daysBetween(r.dataScadenta, today) : 0; }

/* Unpaid invoices by how late they are. Every bucket keeps its rows, so a card opens exactly what it counts. */
const OWED_BUCKETS = [
  { key: 'notdue', label: 'Not due yet', test: d => d <= 0 },
  { key: 'd30', label: '1–30 days late', test: d => d >= 1 && d <= 30 },
  { key: 'd60', label: '31–60 days late', test: d => d >= 31 && d <= 60 },
  { key: 'd90', label: '61–90 days late', test: d => d >= 61 && d <= 90 },
  { key: 'd90p', label: 'Over 90 days', test: d => d > 90 },
];
function owedAgeing(incasari, today) {
  const owing = incasari.filter(r => owedOn(r) > 0.004);
  return OWED_BUCKETS.map(b => {
    const rows = owing.filter(r => b.test(daysLate(r, today)));
    return { key: b.key, label: b.label, rows, total: rows.reduce((s, r) => s + owedOn(r), 0) };
  });
}

/* ---------- accounts payable: unpaid bills by due date (brief 28) ----------
   What is still owed on each bill (minus part payments), by how many days until it is due. A bill with no
   due date cannot be placed: it is kept apart (noDueDate) and shown on the card, never silently dropped. */
function owedOut(p) { return UNPAID_OUT.includes(p.status) ? Math.max(0, brutOfRow(p) - platitOf(p.id)) : 0; }
const PAY_BUCKETS = [
  { key: 'overdue', label: 'Overdue', test: d => d < 0 },
  { key: 'd7', label: 'Due in 0–7 days', test: d => d >= 0 && d <= 7 },
  { key: 'd14', label: 'Due in 8–14 days', test: d => d >= 8 && d <= 14 },
  { key: 'd30', label: 'Due in 15–30 days', test: d => d >= 15 && d <= 30 },
  { key: 'd30p', label: 'Due in over 30 days', test: d => d > 30 },
];
function payablesAgeing(plati, today) {
  const owing = plati.filter(p => owedOut(p) > 0.004);
  const dated = owing.filter(p => p.dataScadenta), noDueDate = owing.filter(p => !p.dataScadenta);
  const buckets = PAY_BUCKETS.map(b => {
    const rows = dated.filter(p => b.test(daysBetween(today, p.dataScadenta)));
    return { key: b.key, label: b.label, rows, total: rows.reduce((s, p) => s + owedOut(p), 0) };
  });
  return { buckets, noDueDate, noDueTotal: noDueDate.reduce((s, p) => s + owedOut(p), 0) };
}

/* ---------- one job ---------- */
function jobFacts(job, plati, incasari, today) {
  const p = DB.proiecte.find(x => x.nume === job) || { nume: job };
  const inRows = incasari.filter(r => r.proiect === job);
  const billed = inRows.reduce((s, r) => s + r.sumaNeta, 0);
  const costLines = jobCostLines(plati).filter(l => l.job === job);
  const costs = costLines.reduce((s, l) => s + l.amount, 0);
  const oh = overheadShares(plati);
  const ohLines = oh.lines.filter(l => l.job === job);
  const ohShare = oh.byJob[job] || 0;
  const profitBefore = billed - costs, profitAfter = profitBefore - ohShare;

  const extraApproved = p.extraWorkApproved || 0;
  const extraRows = inRows.filter(r => r.tip === 'Change order');
  const extraInvoiced = extraRows.reduce((s, r) => s + r.sumaNeta, 0);
  const contract = p.contractValue == null ? null : p.contractValue + extraApproved;

  const owedRows = inRows.filter(r => owedOn(r) > 0.004);
  const owed = owedRows.reduce((s, r) => s + owedOn(r), 0);
  const oldestDaysLate = owedRows.reduce((m, r) => Math.max(m, daysLate(r, today)), 0);

  // retainage: the customer holds back a % of each invoice until the job is finished, then releases it
  const pctHeld = p.retainagePct || 0;
  const heldLines = pctHeld > 0 ? inRows.filter(r => BILLED_TYPES.includes(r.tip)).map(r => ({ row: r, amount: r.sumaNeta * pctHeld / 100 })) : [];
  const releaseLines = inRows.filter(r => r.tip === 'Retainage release').map(r => ({ row: r, amount: -r.sumaNeta }));
  const retainageLines = heldLines.concat(releaseLines);
  const retainageHeld = Math.max(0, retainageLines.reduce((s, l) => s + l.amount, 0));
  const retainageReleased = releaseLines.length > 0 && retainageHeld < 0.005;
  const retainageDue = pctHeld > 0 && p.endDate ? addDays(p.endDate, 30) : null;

  const byCat = {}, byVendor = {};
  costLines.forEach(l => {
    const c = byCat[l.categorie] || (byCat[l.categorie] = { name: l.categorie, amount: 0, lines: [] });
    c.amount += l.amount; c.lines.push(l);
    const v = byVendor[l.row.furnizor] || (byVendor[l.row.furnizor] = { name: l.row.furnizor, amount: 0, lines: [] });
    v.amount += l.amount; v.lines.push(l);
  });
  const sortDesc = o => Object.values(o).sort((a, b) => b.amount - a.amount);

  return {
    job: p, inRows, billed, costLines, costs, ohLines, ohShare, profitBefore, profitAfter,
    marginBefore: billed ? profitBefore / billed * 100 : 0, marginAfter: billed ? profitAfter / billed * 100 : 0,
    budget: p.budget, budgetUsed: p.budget ? costs / p.budget * 100 : null,
    contract, stillToBill: contract == null ? null : contract - billed,
    owedRows, owed, oldestDaysLate,
    retainagePct: pctHeld, retainageLines, retainageHeld, retainageReleased, retainageDue,
    extraApproved, extraRows, extraInvoiced, extraNotInvoiced: Math.max(0, extraApproved - extraInvoiced),
    byCategory: sortDesc(byCat), byVendor: sortDesc(byVendor),
  };
}

/* ---------- the income statement ---------- */
const INCOME_TAX_RATE = 0.25;   // estimate the owners set aside, paid quarterly to the IRS (the LLC is pass-through)
function incomeStatement(plati, incasari) {
  const revenue = incasari.reduce((s, r) => s + r.sumaNeta, 0);
  const salesTax = incasari.reduce((s, r) => s + vatOfRow(r), 0);
  const jobCostRows = partRows(plati).filter(p => !isOverhead(p));   // parts: a split bill counts each part in its place
  const ohRows = overheadRows(plati);
  const jobCosts = jobCostRows.reduce((s, p) => s + p.sumaNeta, 0);
  const overheads = ohRows.reduce((s, p) => s + p.sumaNeta, 0);
  const gross = revenue - jobCosts;                 // gross profit: revenue minus direct costs
  const net = gross - overheads;
  const taxSetAside = Math.max(0, net) * INCOME_TAX_RATE;
  return { revenue, salesTax, jobCostRows, jobCosts, gross, ohRows, overheads, net, taxSetAside, afterTax: net - taxSetAside };
}

/* ---------- vehicles ---------- */
/* Every cost that carries a license plate: fuel, repairs, or other (insurance, tolls, registration). */
function vehicleKind(p) { return p.categorie === FUEL_CAT ? 'fuel' : p.categorie === REPAIRS_CAT ? 'repairs' : 'other'; }
function vehicleCosts(plati) {
  const byPlate = {};
  // every part of a bill with a plate is a truck cost, each under its own kind: a bill split Fuel / Insurance shows
  // its fuel part under fuel and its insurance part under other, exactly as two separate bills would
  partRows(plati).filter(p => p.vehiclePlate).forEach(p => {
    const v = byPlate[p.vehiclePlate] || (byPlate[p.vehiclePlate] = { plate: p.vehiclePlate, fuel: [], repairs: [], other: [] });
    v[vehicleKind(p)].push(p);
  });
  return byPlate;
}

Object.assign(window, {
  catTypeOf, isOverhead, costLines, partRows, wholeOf, hasCategorySplit, costParts, jobCostLines, unassignedCosts, overheadRows, overheadShares,
  owedOn, daysLate, OWED_BUCKETS, owedAgeing, owedOut, PAY_BUCKETS, payablesAgeing, jobFacts, INCOME_TAX_RATE, incomeStatement, vehicleKind, vehicleCosts, BILLED_TYPES,
});
