/* ============================================================
   P&L App (Lite) · Accountant CSV export (from the US demo's; Lite's columns only)
   ------------------------------------------------------------
   One-click export of every money in + money out row in a chosen period
   into a single CSV the accountant (or bookkeeper) can open in Excel.

   Format choices (US Excel friendly):
   - ',' (comma) as the column separator, '.' as the decimal mark.
   - Numbers have NO thousands separator (1234.56) so Excel reads them as numbers.
   - Dates are MM/DD/YYYY.
   - A UTF-8 BOM is prepended so any accent in a name shows correctly.
   ============================================================ */

/* one CSV cell: always quoted, with embedded quotes doubled. A cell that starts with = + - @ is a formula
   to Excel (a name typed as "=HYPERLINK(...)" would run): it gets a ' in front so it stays plain text.
   Numbers are written with csvNum, never through here, so "-500.00" stays a number. */
function csvCell(v) {
  let s = (v == null ? '' : String(v));
  if (/^[=+\-@\t\r]/.test(s) && !/^-?\d+(\.\d+)?$/.test(s)) s = "'" + s;
  return '"' + s.replace(/"/g, '""') + '"';
}
/* number -> "1234.56" (dot decimal, no grouping) */
function csvNum(n) {
  return (Number(n) || 0).toFixed(2);
}
function _typeCell(r) { return isOverhead(r) ? 'Overhead' : 'Direct cost'; }
/* the company's name in a file name: "Lone Star Builders" -> "Lone_Star_Builders" */
function fileSlug() { return companyName().replace(/[^A-Za-z0-9]+/g, '_').replace(/^_|_$/g, '') || 'Company'; }

/* Build the full CSV text for [from, to] (inclusive, ISO dates). */
function buildAccountantCSV(from, to) {
  const inRange = r => r.data >= from && r.data <= to;

  // money in and money out in one chronological ledger
  const rows = [
    ...DB.incasari.filter(inRange).map(r => ({
      tip: 'Money in', data: r.data, nrFactura: r.nrFactura, partener: r.client, categorie: r.categorie, kind: 'Income',
      notes: r.notes, sumaNeta: r.sumaNeta, cotaTva: r.cotaTva, status: r.status, due: r.dataScadenta,
    })),
    ...DB.plati.filter(inRange).map(r => ({
      tip: 'Money out', data: r.data, nrFactura: r.nrFactura, partener: r.furnizor, categorie: r.categorie, kind: r.categorie ? _typeCell(r) : '',
      notes: r.notes, sumaNeta: r.sumaNeta, cotaTva: 0, status: r.status, due: r.dataScadenta,
    })),
  ].sort((a, b) => a.data.localeCompare(b.data) || a.tip.localeCompare(b.tip));

  const headers = ['Type', 'Date', 'Invoice / bill #', 'Customer / vendor', 'Category', 'Direct cost or overhead',
    'Note', 'Amount', 'Sales tax rate %', 'Sales tax', 'Total', 'Status', 'Due date'];

  const lines = [headers.map(csvCell).join(',')];
  for (const r of rows) {
    const tva = vatOfRow(r);
    lines.push([
      csvCell(r.tip), csvCell(fmtDate(r.data)), csvCell(r.nrFactura || ''), csvCell(r.partener || ''), csvCell(r.categorie || ''),
      csvCell(r.kind), csvCell(r.notes || ''), csvNum(r.sumaNeta), csvCell(r.cotaTva), csvNum(tva), csvNum(r.sumaNeta + tva),
      csvCell(r.status || ''), csvCell(r.due ? fmtDate(r.due) : ''),
    ].join(','));
  }
  return '\ufeff' + lines.join('\r\n');
}

/* trigger a browser download of the CSV for the period */
function downloadAccountantCSV(from, to) {
  const csv = buildAccountantCSV(from, to);
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${fileSlug()}_accountant_export_${from}_${to}.csv`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

/* ---------- the filtered export: exactly the rows on screen ----------
   Takes the rows the view already shows, in the order it shows them, so the screen and the file
   cannot differ. And it SAYS it is a subset: the filters, the search and the row count are written
   at the top of the file. The accountant export (P&L tab) stays unfiltered: everything in a period. */
function buildFilteredCSV(table, rows, state) {
  const isIn = table === 'incasari';
  const pre = [`${companyName()}, ${isIn ? 'money in' : 'money out'}, exported ${fmtDate(todayISO())}`];
  const active = (state.filters || []).filter(f => isComplete(f, fieldByKey(table, f.key)));
  if (active.length) active.forEach(f => pre.push('Filter: ' + describeFilter(f, table)));
  else pre.push('No filters applied');
  if (state.mode === 'or' && active.length > 1) pre.push('The filters are combined with OR: a row shows if it matches ANY of them');
  if (state.q) pre.push(`Search: "${state.q}"`);
  pre.push(`${rows.length} ${rows.length === 1 ? 'row' : 'rows'}. This is ${active.length || state.q ? 'a FILTERED list, not the whole ledger' : 'the whole ledger'}. The accountant export on the P&L tab has everything in a period.`);

  const headers = isIn
    ? ['#', 'Date', 'Customer', 'Category', 'Invoice #', 'Note', 'Amount', 'Sales tax rate %', 'Sales tax', 'Total', 'Paid', 'Terms (days)', 'Due date', 'Status', 'To review', 'Review reason']
    : ['#', 'Date', 'Vendor', 'Category', 'Direct cost or overhead', 'Bill #', 'Note', 'Amount', 'Paid', 'Due date', 'Status', 'To review', 'Review reason'];

  const lines = pre.map(t => csvCell('# ' + t));
  lines.push(headers.map(csvCell).join(','));
  rows.forEach((r, i) => {
    const tva = vatOfRow(r);
    const common = [csvCell(i + 1), csvCell(fmtDate(r.data))];
    const tail = [csvCell(r.needsReview ? 'Yes' : 'No'), csvCell(r.reviewReason || '')];
    lines.push((isIn
      ? [...common, csvCell(r.client), csvCell(r.categorie || ''), csvCell(r.nrFactura || ''), csvCell(r.notes || ''),
         csvNum(r.sumaNeta), csvCell(r.cotaTva), csvNum(tva), csvNum(r.sumaNeta + tva), csvNum(incasatEfectiv(r)), csvCell(r.termenPlata == null ? '' : r.termenPlata),
         csvCell(r.dataScadenta ? fmtDate(r.dataScadenta) : ''), csvCell(r.status), ...tail]
      : [...common, csvCell(r.furnizor), csvCell(r.categorie || ''), csvCell(r.categorie ? _typeCell(r) : ''), csvCell(r.nrFactura || ''), csvCell(r.notes || ''),
         csvNum(r.sumaNeta), csvNum(platitEfectiv(r)), csvCell(r.dataScadenta ? fmtDate(r.dataScadenta) : ''), csvCell(r.status), ...tail]
    ).join(','));
  });

  /* The footer uses totals(), the same function as the bar under the table, so the file and the screen cannot differ. */
  const t = totals(rows);
  const paid = rows.reduce((s, r) => s + (isIn ? incasatEfectiv(r) : platitEfectiv(r)), 0);
  const blank = n => Array(n).fill('""');
  lines.push((isIn
    ? [csvCell('Total'), ...blank(5), csvNum(t.net), '""', csvNum(t.tva), csvNum(t.brut), csvNum(paid)]
    : [csvCell('Total'), ...blank(6), csvNum(t.net), csvNum(paid)]).join(','));
  return '\ufeff' + lines.join('\r\n');
}

/* The period in the file name: the date filter's limits if there is one, otherwise the range of the rows exported. */
function filteredExportRange(table, rows, state) {
  const df = (state.filters || []).find(f => f.key === 'data' && isComplete(f, fieldByKey(table, 'data')));
  const b = df ? dateBounds(df) : null;
  const dates = rows.map(r => r.data).filter(Boolean).sort();
  return { from: (b && b.from) || dates[0] || todayISO(), to: (b && b.to) || dates[dates.length - 1] || todayISO() };
}

function downloadFilteredCSV(table, rows, state) {
  const { from, to } = filteredExportRange(table, rows, state);
  const csv = buildFilteredCSV(table, rows, state);
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${fileSlug()}_${table === 'incasari' ? 'money_in' : 'money_out'}_${from}_${to}.csv`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

/* ---------- period helpers ---------- */
function monthBounds(iso) {
  const start = iso.slice(0, 7) + '-01';
  const [y, m] = iso.split('-').map(Number);
  const lastDay = new Date(y, m, 0).getDate();           // day 0 of next month = last day of this month
  const end = `${iso.slice(0, 7)}-${String(lastDay).padStart(2, '0')}`;
  return { start, end };
}

/* ---------- Export modal ---------- */
function ExportModal({ open, onClose }) {
  useDB();
  const today = todayISO();
  const [from, setFrom] = useState(today.slice(0, 4) + '-01-01');
  const [to, setTo] = useState(today);

  // live count of what the current period will export
  const inRange = r => r.data >= from && r.data <= to;
  const inCount = DB.incasari.filter(inRange).length;
  const plCount = DB.plati.filter(inRange).length;
  const total = inCount + plCount;

  function preset(kind) {
    if (kind === 'month') { const b = monthBounds(today); setFrom(b.start); setTo(b.end); }
    else if (kind === 'year') { setFrom(today.slice(0, 4) + '-01-01'); setTo(today); }
    else if (kind === 'all') { setFrom('2000-01-01'); setTo(today); }
  }

  function doExport() {
    if (total === 0) return;
    downloadAccountantCSV(from, to);
    onClose();
  }

  return (
    <Modal open={open} onClose={onClose} width={540} icon="download"
      title="Accountant export"
      subtitle="Download every money in and money out row in the chosen period, in one CSV file for your accountant."
      footer={<>
        <Button variant="ghost" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon="download" onClick={doExport} disabled={total === 0}>
          Download CSV ({total})
        </Button>
      </>}>
      <div className="flex flex-col gap-4">
        <div className="flex flex-wrap gap-2">
          <Button variant="soft" size="sm" onClick={() => preset('month')}>This month</Button>
          <Button variant="soft" size="sm" onClick={() => preset('year')}>This year</Button>
          <Button variant="soft" size="sm" onClick={() => preset('all')}>All time</Button>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <Field label="From">
            <Input type="date" value={from} max={to} onChange={e => setFrom(e.target.value)} />
          </Field>
          <Field label="To">
            <Input type="date" value={to} min={from} max={today} onChange={e => setTo(e.target.value)} />
          </Field>
        </div>
        <div className="rounded-xl px-4 py-3 text-[13px] flex items-center justify-between" style={{ background: '#EAF1F2', color: 'var(--primary)' }}>
          <span className="font-medium">In the chosen period</span>
          <span className="num">{inCount} money in · {plCount} money out</span>
        </div>
        {total === 0 && (
          <p className="text-[12.5px] text-muted">Nothing in this period. Pick another range.</p>
        )}
      </div>
    </Modal>
  );
}

/* ---------- Export button (mount this in a view header) ---------- */
function ExportButton({ size = 'sm', variant = 'outline' }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button variant={variant} size={size} icon="download" onClick={() => setOpen(true)}>Accountant export</Button>
      <ExportModal open={open} onClose={() => setOpen(false)} />
    </>
  );
}

window.ExportButton = ExportButton;
window.csvCell = csvCell;
window.buildAccountantCSV = buildAccountantCSV;
window.downloadAccountantCSV = downloadAccountantCSV;
window.buildFilteredCSV = buildFilteredCSV;
window.downloadFilteredCSV = downloadFilteredCSV;
window.filteredExportRange = filteredExportRange;
