/* ============================================================
   P&L App (Lite) · Due dates (from the US demo's): what must be paid, what must be collected, and when.

   Pure logic only (no screens) so it can be tested. The Dashboard cards and the alerts bell both read it, and a click
   on a card opens the list with a filter built HERE — the same function that decides what is in the bucket — so the
   number on the card and the rows in the list can never disagree.

   "Unpaid" = the status says so (În așteptare, Parțial plătit/încasat, Restant). The amount counted is what is STILL
   owed (gross minus part payments). A payment with no due date cannot be placed in a bucket: it is counted
   separately ("fără scadență") and shown in Admin. Due today is NOT overdue.
   ============================================================ */
const ALERT_DAYS = 7;   // "au scadența în următoarele 7 zile" — the amber alert (Ana, 5 Oct 2026: was 3)

const DUE_BUCKETS = [
  { key: 'overdue', label: 'Overdue',        from: null, to: -1 },
  { key: 'd0_7',    label: 'Today – 7 days', from: 0,    to: 7 },
  { key: 'd8_14',   label: '8 – 14 days',    from: 8,    to: 14 },
  { key: 'd15_30',  label: '15 – 30 days',   from: 15,   to: 30 },
  { key: 'd31',     label: 'Over 30 days',   from: 31,   to: null },
];

function _daysFromToday(iso, today) { return Math.round((Date.parse(iso + 'T00:00:00Z') - Date.parse(today + 'T00:00:00Z')) / 864e5); }
function _unpaidStatuses(kind) { return kind === 'in' ? UNPAID_IN : UNPAID_OUT; }
function _rowsOf(kind) { return kind === 'in' ? DB.incasari : DB.plati; }

/* what is still owed on a row (never negative) */
function outstandingOf(r, kind) {
  const paid = kind === 'in' ? incasatOf(r.id) : platitOf(r.id);
  return Math.max(0, brutOfRow(r) - paid);
}

/* the unpaid rows of a kind, and the part of them that has no due date */
function unpaidRows(kind) { return _rowsOf(kind).filter(r => _unpaidStatuses(kind).includes(r.status)); }

/* { overdue:{n,sum}, d0_7:{n,sum}, ..., next:{row,days}|null, missing:n, total:{n,sum} } */
function dueSummary(kind, today) {
  const t = today || todayISO();
  const out = { next: null, missing: 0, total: { n: 0, sum: 0 } };
  DUE_BUCKETS.forEach(b => { out[b.key] = { n: 0, sum: 0 }; });
  unpaidRows(kind).forEach(r => {
    if (!r.dataScadenta) { out.missing++; return; }
    const d = _daysFromToday(r.dataScadenta, t), amt = outstandingOf(r, kind);
    const b = DUE_BUCKETS.find(x => (x.from === null || d >= x.from) && (x.to === null || d <= x.to));
    out[b.key].n++; out[b.key].sum += amt;
    out.total.n++; out.total.sum += amt;
    if (d >= 0 && (!out.next || r.dataScadenta < out.next.row.dataScadenta)) out.next = { row: r, days: d };
  });
  return out;
}

/* the list filter that shows EXACTLY the rows of a bucket (or of "due within N days") */
function dueListState(kind, bucketKey, today) {
  const t = today || todayISO();
  const status = { key: 'status', op: 'is any of', value: _unpaidStatuses(kind).slice() };
  let date;
  if (bucketKey === 'upcoming') date = { key: 'dataScadenta', op: 'after', value: addDays(t, -1) };       // today and later (the "next due" card)
  else if (bucketKey === 'within') date = { key: 'dataScadenta', op: 'between', value: t, value2: addDays(t, ALERT_DAYS) };
  else {
    const b = DUE_BUCKETS.find(x => x.key === bucketKey);
    if (b.from === null) date = { key: 'dataScadenta', op: 'before', value: t };                       // due before today
    else if (b.to === null) date = { key: 'dataScadenta', op: 'after', value: addDays(t, b.from - 1) };  // later than the last day of the previous bucket
    else date = { key: 'dataScadenta', op: 'between', value: addDays(t, b.from), value2: addDays(t, b.to) };
  }
  return { filters: [status, date], q: '', sort: { key: 'dataScadenta', dir: 'asc' }, mode: 'and', advanced: false };
}

/* the lines of the alerts bell: only those with something in them */
function dueAlerts(today) {
  const t = today || todayISO();
  const lines = [];
  [['out', 'to pay', 'plati'], ['in', 'to collect', 'incasari']].forEach(([kind, word, tab]) => {
    const s = dueSummary(kind, t);
    const soon = unpaidRows(kind).filter(r => r.dataScadenta && _daysFromToday(r.dataScadenta, t) >= 0 && _daysFromToday(r.dataScadenta, t) <= ALERT_DAYS).length;
    const pl = n => (kind === 'out' ? (n === 1 ? 'bill' : 'bills') : (n === 1 ? 'invoice' : 'invoices'));
    if (s.overdue.n > 0) lines.push({ key: kind + ':overdue', kind, tab, bucket: 'overdue', n: s.overdue.n, tone: 'neg',
      text: `${s.overdue.n} ${pl(s.overdue.n)} ${word} ${s.overdue.n === 1 ? 'is' : 'are'} past the due date` });
    if (soon > 0) lines.push({ key: kind + ':within', kind, tab, bucket: 'within', n: soon, tone: 'warn',
      text: `${soon} ${pl(soon)} ${word} ${soon === 1 ? 'is' : 'are'} due in the next ${ALERT_DAYS} days` });
  });
  return lines;
}
function dueAlertCount(today) { return dueAlerts(today).reduce((a, l) => a + l.n, 0); }

/* ---- the bell's number counts only what you have not seen yet (Ana, 5 Oct 2026) ----
   Every invoice inside an alert line is an "item" with its own id; the number on the bell is the items the person has not
   opened the bell for yet. Opening the bell marks every current item as seen. An invoice that newly lands in the window
   (or arrives already overdue) is a new item and brings the number back. Once a week (Monday-based) there is one more
   item: the overdue summary, shown as the first line of the bell. */
function weekStartOf(today) {
  const dow = (new Date((today || todayISO()) + 'T00:00:00Z').getUTCDay() + 6) % 7;   // Monday = 0
  return addDays(today || todayISO(), -dow);
}
function _alertRows(today) {
  const t = today || todayISO(), out = [];
  ['out', 'in'].forEach(kind => unpaidRows(kind).forEach(r => {
    if (!r.dataScadenta) return;
    const d = _daysFromToday(r.dataScadenta, t);
    if (d <= ALERT_DAYS) out.push({ id: kind + ':' + r.id, kind, overdue: d < 0 });
  }));
  return out;
}
/* the weekly overdue line, or null when nothing is overdue */
function weeklyLine(today) {
  const rows = _alertRows(today);
  const a = rows.filter(x => x.kind === 'out' && x.overdue).length, b = rows.filter(x => x.kind === 'in' && x.overdue).length;
  if (a + b === 0) return null;
  const pl = n => (n === 1 ? 'item overdue' : 'items overdue');
  return { key: 'week', kind: a >= b ? 'out' : 'in', tab: a >= b ? 'plati' : 'incasari', bucket: 'overdue', n: 1, tone: 'neg',
    text: `This week: ${a + b} ${pl(a + b)} (${a} ${a === 1 ? 'bill' : 'bills'} to pay, ${b} ${b === 1 ? 'invoice' : 'invoices'} to collect)` };
}
/* ids of everything the bell currently reports (invoices + this week's summary) */
function alertItemIds(today) {
  const ids = _alertRows(today).map(x => x.id);
  if (weeklyLine(today)) ids.push('week:' + weekStartOf(today));
  return ids;
}
function unseenCount(seen, today) {
  const s = new Set(seen || []);
  return alertItemIds(today).filter(id => !s.has(id)).length;
}

Object.assign(window, { ALERT_DAYS, DUE_BUCKETS, outstandingOf, unpaidRows, dueSummary, dueListState, dueAlerts, dueAlertCount, weekStartOf, weeklyLine, alertItemIds, unseenCount });
