/* screen-taxes.jsx — F1 Taxes/URSSAF report (VAT estimate, receipts ledger,
 * accountant exports). Money figures wear gold; the declaration banner is
 * the ONLY terracotta surface; NO sage anywhere (nothing here is AI).
 * → window.QScreens.Taxes
 */
(function () {
  const { useState } = React;
  const Q = window.Q, LIB = window.LIB, Icons = window.Icons;
  const { Icon } = Icons;
  const { AppBar, Card, Money, AnimatedNumber, Kicker, Segmented, StatusPill, EmptyState, EntityLink, Row } = Q;
  const t = window.t;

  /* Local YYYY-MM-DD for export file names (display-only formatting of the
     pinned api.today — never the wall clock). */
  const dayStr = (d) => {
    const x = new Date(d);
    const p = n => String(n).padStart(2, "0");
    return x.getFullYear() + "-" + p(x.getMonth() + 1) + "-" + p(x.getDate());
  };
  /* tax.urssaf.rate supplies its own "%" — strip it from the localized pct. */
  const pctBare = (n) => LIB.fmtPct(n).replace("%", "");

  /* Card header: kicker + Inter sub on the left, supporting money figure on
     the right (size 16 — the net hero above is the only large figure). */
  function CardHead({ kicker, sub, amount, currency }) {
    return (
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12, padding: "16px 16px 12px" }}>
        <div style={{ minWidth: 0 }}>
          <Kicker>{kicker}</Kicker>
          {sub && <div style={{ fontSize: 12, color: "var(--color-text-3)", marginTop: 8 }}>{sub}</div>}
        </div>
        <Money amount={amount} currency={currency} size={16} />
      </div>
    );
  }

  /* The documented invoice-row pattern (clients/projects): mono id +
     fmtDate short, signed Money cents:false, StatusPill solid. */
  function DocRow({ api, inv, last }) {
    const tot = LIB.totals(inv);
    const eff = LIB.effectiveStatus(inv, api.today);
    return (
      <Row onClick={() => api.goTab("invoices", "invoice", { id: inv.id })} last={last}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600 }}>{inv.id}</div>
          <div style={{ fontSize: 12, color: "var(--color-text-3)", marginTop: 1 }}>{window.fmtDate(inv.issued, "short")}</div>
        </div>
        <div style={{ textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
          <Money amount={LIB.docSign(inv) * tot.total} currency={inv.currency} size={14} cents={false} />
          <StatusPill status={eff} solid />
        </div>
      </Row>
    );
  }

  function ExportRow({ icon, label, sub, onClick, last }) {
    return (
      <Row onClick={onClick} last={last}>
        <div style={{ width: 38, height: 38, borderRadius: "var(--radius-lg)", background: "var(--color-surface-1)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-text-2)", flexShrink: 0 }}>
          <Icon name={icon} size={17} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{label}</div>
          {sub && <div style={{ fontSize: 12, color: "var(--color-text-3)", marginTop: 2, lineHeight: 1.4 }}>{sub}</div>}
        </div>
        <Icon name="download" size={17} color="var(--color-text-3)" style={{ flexShrink: 0 }} />
      </Row>
    );
  }

  function Taxes({ api }) {
    const { db, today } = api;
    const cur = db.COMPANY.currency;

    /* Period picker: quarters of the current year + YTD; default = the
       current quarter (the entry just before ytd). */
    const periods = LIB.taxPeriods(today);
    const defKey = periods[Math.max(0, periods.length - 2)].key;
    const [pkey, setPkey] = useState(defKey);
    const period = periods.find(p => p.key === pkey) || periods[Math.max(0, periods.length - 2)];

    const dec = LIB.nextDeclaration(db, today);
    const tr = LIB.taxReport(db, { from: period.from, to: period.to, today });
    const ur = LIB.urssafReport(db, { from: period.from, to: period.to });
    const ledger = LIB.paymentsLedger(db, { from: period.from, to: period.to });
    /* The footer total only sums receipts in the company currency — mixing
       currencies without FX would be a fake number. Track how many rows feed
       it (inCurCount) vs how many sit outside (offCount) so the footer label,
       its count and the rows that actually add up all stay coherent
       (ledger-total-excludes-visible-usd-row). */
    const inCur = ledger.filter(p => (p.currency || cur) === cur);
    const inCurCount = inCur.length;
    const offCount = ledger.length - inCurCount;
    const eurTotal = inCur.reduce((s, p) => s + (Number(p.amount) || 0), 0);

    /* Drill-down: union of the per-rate refs, newest first. */
    const docIds = [];
    tr.output.rates.forEach(r => r.refs.forEach(id => { if (docIds.indexOf(id) < 0) docIds.push(id); }));
    const docs = docIds.map(id => (db.INVOICES || []).find(i => i.id === id)).filter(Boolean)
      .sort((a, b) => (a.issued < b.issued ? 1 : a.issued > b.issued ? -1 : 0));
    const expenses = (tr.input.refs || []).map(id => (db.EXPENSES || []).find(e => e.id === id)).filter(Boolean)
      .sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
    const expVat = (e) => {
      const amt = Number(e.amount) || 0;
      return amt - amt / (1 + (Number(e.taxRate) || 0) / 100);
    };

    /* Declaration banner copy: day counts are never gold; urgency wears
       terracotta (<= 7 days or already late). */
    const urgent = dec.daysLeft <= 7;
    const dueCopy = dec.daysLeft > 0 ? t("tax.due.days", { d: dec.daysLeft })
      : dec.daysLeft === 0 ? t("tax.due.today")
      : t("tax.due.over", { d: Math.abs(dec.daysLeft) });

    const isCredit = tr.net < 0;

    /* Receipts ledger cap: first 5 rows, the rest one tap away. */
    const [more, setMore] = useState(false);

    /* Exports: real files via Q.downloadFile; the pack staggers 4 downloads
       then toasts once. */
    const csvMime = "text/csv;charset=utf-8";
    const span = period.from + "_" + period.to;
    /* P0-6 — unify the two export surfaces: deep-link the selected tax period
       into the configurable Export screen (invoices + credits, scoped to the
       period as the date range) so there is ONE export mental model, not two. */
    const openInExport = () => api.openExport({ types: ["invoice", "credit"], from: period.from, to: period.to });
    /* P1-1 (screen half) — thread the selected period into the direct Invoices
       CSV so a Q2 export carries Q2 invoices, not the whole book (pairs with
       the lib-side from/to scoping in csvInvoices). */
    const dlInvoices = () => Q.downloadFile("invoices-" + span + ".csv", LIB.csvInvoices(db, { today, from: period.from, to: period.to }), csvMime);
    const dlPayments = () => Q.downloadFile("payments-" + span + ".csv", LIB.csvPayments(db, { from: period.from, to: period.to }), csvMime);
    const dlFec = () => Q.downloadFile("fec-preview-" + span + ".txt", LIB.fecPreview(db, { from: period.from, to: period.to }), "text/plain;charset=utf-8");
    const dlPack = () => {
      const files = LIB.accountantPack(db, { from: period.from, to: period.to, today });
      files.forEach((f, i) => setTimeout(() => Q.downloadFile(f.name, f.content, f.mime), i * 350));
      setTimeout(() => Q.toast(t("toast.packExported", { count: files.length }), "download"), files.length * 350);
    };

    return (
      <div style={{ paddingBottom: 40 }}>
        <AppBar large onBack={() => api.back()} title={t("tax.title")} kicker={t("tax.kicker")} />
        <div style={{ padding: "8px 16px 0", display: "flex", flexDirection: "column", gap: 16 }}>

          {/* 2 — declaration banner (the one terracotta surface) */}
          <Card pad={14}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 38, height: 38, borderRadius: "var(--radius-lg)", background: urgent ? "var(--color-accent-muted)" : "var(--color-surface-1)", display: "flex", alignItems: "center", justifyContent: "center", color: urgent ? "var(--color-accent)" : "var(--color-text-2)", flexShrink: 0 }}>
                <Icon name="calendar" size={17} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{t("tax.due", { date: window.fmtDate(dec.due) })}</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600, marginTop: 2, color: urgent ? "var(--color-accent)" : "var(--color-text-3)" }}>{dueCopy}</div>
              </div>
            </div>
          </Card>

          {/* period picker — chosen FIRST, so the net figure below always reads
              as the answer FOR the selected period (net-vat-above-period-picker). */}
          <Segmented value={period.key} onChange={setPkey}
            options={periods.map(p => ({ value: p.key, label: p.key === "ytd" ? t("tax.period.ytd") : t("tax.period.q", p.labelParams) }))} />

          {/* 3 — net VAT due: THE answer for the selected period, sitting right
              under its picker. The only display-size figure on the screen; it
              speaks the Q.MoneyDisplay voice (Fraunces serif gold) through
              AnimatedNumber so the amount keeps count-up session memory — the
              home hero pattern. */}
          <Card pad={0} style={{ overflow: "hidden" }}>
            <div style={{ padding: 16 }}>
              <Kicker>{isCredit ? t("tax.net.credit") : t("tax.net")}</Kicker>
              <div style={{ marginTop: 8 }}>
                <AnimatedNumber amount={Math.abs(tr.net)} currency={cur} size={30} weight={600} color="var(--color-gold)" animKey="tax.net"
                  style={{ fontFamily: "var(--font-serif)", lineHeight: 1.05, letterSpacing: "-0.02em" }} />
              </div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--color-text-3)", marginTop: 8 }}>
                {t("tax.net.formula", { collected: window.fmtMoney(tr.output.total, cur), deductible: window.fmtMoney(tr.input.total, cur) })}
              </div>
            </div>
          </Card>

          {/* 4 — output VAT (collected): supporting card below the answer */}
          <Card pad={0} style={{ overflow: "hidden" }}>
            <CardHead kicker={t("tax.output")} sub={t("tax.output.sub", { count: tr.output.count })} amount={tr.output.total} currency={cur} />
            <div style={{ borderTop: "1px solid var(--color-border)" }}>
              {tr.output.rates.map((r, i) => (
                <Row key={(r.name || "") + "_" + r.rate} last={i === tr.output.rates.length - 1}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{r.name ? `${r.name} (${LIB.fmtPct(r.rate)})` : `${t("inv.vat")} ${LIB.fmtPct(r.rate)}`}</div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-3)", marginTop: 2 }}>{t("tax.base")} {window.fmtMoney(r.base, cur)}</div>
                  </div>
                  <Money amount={r.tax} currency={cur} size={14} />
                </Row>
              ))}
            </div>
            {docs.length > 0 && (
              <Q.Collapsible flat defaultOpen={false} title={t("tax.drill.invoices")} count={docs.length}>
                {docs.map((inv, i) => <DocRow key={inv.id} api={api} inv={inv} last={i === docs.length - 1} />)}
              </Q.Collapsible>
            )}
          </Card>

          {/* 5 — input VAT (deductible expenses): supporting card */}
          <Card pad={0} style={{ overflow: "hidden" }}>
            <CardHead kicker={t("tax.input")} sub={t("tax.input.sub", { count: tr.input.count })} amount={tr.input.total} currency={cur} />
            {expenses.length > 0 && (
              <Q.Collapsible flat defaultOpen={false} title={t("tax.drill.expenses")} count={expenses.length}>
                {expenses.map((e, i) => (
                  <Row key={e.id} onClick={() => api.go("expense", { id: e.id })} last={i === expenses.length - 1}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.merchant}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-3)", marginTop: 2 }}>{window.fmtDate(e.date, "short")} · {t("inv.vat")} {LIB.fmtPct(e.taxRate || 0)}</div>
                    </div>
                    <Money amount={expVat(e)} currency={e.currency || cur} size={14} />
                  </Row>
                ))}
              </Q.Collapsible>
            )}
          </Card>

          {/* 6 — URSSAF */}
          <Card pad={0} style={{ overflow: "hidden" }}>
            <CardHead kicker={t("tax.urssaf")} sub={t("tax.urssaf.sub")} amount={ur.turnover} currency={cur} />
            <Row style={{ borderTop: "1px solid var(--color-border)" }}>
              <span style={{ flex: 1, fontSize: 13, color: "var(--color-text-2)" }}>{t("tax.urssaf.rate", { rate: pctBare(ur.rate) })}</span>
            </Row>
            <Row last>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>{t("tax.urssaf.contrib")}</span>
              <Money amount={ur.contribution} currency={cur} size={16} />
            </Row>
          </Card>

          {/* 7 — livre des recettes */}
          <div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 12 }}>
              <Kicker>{t("ledger.title")}</Kicker>
              {ledger.length > 0 && <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-3)", fontVariantNumeric: "tabular-nums" }}>{t("ledger.count", { count: ledger.length })}</span>}
            </div>
            {ledger.length === 0 ? (
              <EmptyState icon="coins" title={t("ledger.empty")} />
            ) : (
              <Card pad={0} style={{ overflow: "hidden" }}>
                {ledger.slice(0, more ? ledger.length : 5).map(p => {
                  /* Currency coherence: rows in another currency are shown (the
                     receipt is real) but muted, and tagged with their own code,
                     so it reads at a glance that they sit OUTSIDE the EUR total
                     below (ledger-total-excludes-visible-usd-row). */
                  const rowCur = p.currency || cur;
                  const offCur = rowCur !== cur;
                  return (
                  <Row key={p.id} style={offCur ? { opacity: 0.62 } : undefined}>
                    <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 3 }}>
                      <EntityLink kind="client" name={p.clientName || "-"} size={14}
                        onClick={p.clientId ? () => api.goTab("clients", "client", { id: p.clientId }) : undefined} />
                      <EntityLink kind="invoice" name={p.invoiceId} mono size={12}
                        onClick={() => api.goTab("invoices", "invoice", { id: p.invoiceId })} />
                    </div>
                    <div style={{ textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 3, flexShrink: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        {offCur && (
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, letterSpacing: "0.04em", color: "var(--color-text-3)", background: "var(--color-surface-1)", borderRadius: "var(--radius-sm)", padding: "1px 5px" }}>{rowCur}</span>
                        )}
                        <Money amount={p.amount} currency={rowCur} size={14} color={offCur ? "var(--color-text-2)" : undefined} />
                      </div>
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--color-text-3)" }}>
                        {window.fmtDate(p.at, "short")} · {t("ledger.method." + (p.method || "other"))}
                      </span>
                    </div>
                  </Row>
                  );
                })}
                {ledger.length > 5 && (
                  <button className="q-tap" onClick={() => setMore(m => !m)}
                    style={{ display: "flex", alignItems: "center", justifyContent: "center", width: "100%", height: 48, fontSize: 13, fontWeight: 600, color: "var(--color-text-2)", background: "none", border: "none", borderTop: "1px solid var(--color-border)", cursor: "pointer" }}>
                    {more ? t("g.showless") : t("g.viewall", { count: ledger.length })}
                  </button>
                )}
                {/* Footer is explicit about WHICH currency it sums: the company
                    currency code rides the existing label, and the count is the
                    EUR-subset so total ⇄ count ⇄ rows-that-feed-it stay coherent. */}
                <Row last style={{ background: "var(--color-surface-1)" }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ fontSize: 14, fontWeight: 600 }}>{t("ledger.total") + " (" + cur + ")"}</span>
                    {offCount > 0 && (
                      <div style={{ fontSize: 11, color: "var(--color-text-3)", marginTop: 2 }}>
                        {t("ledger.count", { count: inCurCount })}
                      </div>
                    )}
                  </div>
                  <Money amount={eurTotal} currency={cur} size={16} />
                </Row>
              </Card>
            )}
          </div>

          {/* 8 — exports */}
          <Card pad={0} style={{ overflow: "hidden" }}>
            {/* P0-6 — one export mental model: deep-link the selected period
                into the configurable Export builder (invoices + credits, period
                as the date range). A chevron, not a download glyph: this opens a
                screen rather than writing a file. */}
            <Row onClick={openInExport}>
              <div style={{ width: 38, height: 38, borderRadius: "var(--radius-lg)", background: "var(--color-surface-1)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-text-2)", flexShrink: 0 }}>
                <Icon name="package" size={17} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{t("export.title")}</div>
                <div style={{ fontSize: 12, color: "var(--color-text-3)", marginTop: 2, lineHeight: 1.4 }}>{t("export.sub")}</div>
              </div>
              <Icon name="chevronRight" size={18} color="var(--color-text-3)" style={{ flexShrink: 0 }} />
            </Row>
            <ExportRow icon="file" label={t("export.csv.invoices")} onClick={dlInvoices} />
            <ExportRow icon="coins" label={t("export.csv.payments")} onClick={dlPayments} />
            <ExportRow icon="bank" label={t("export.fec")} onClick={dlFec} />
            <ExportRow icon="package" label={t("export.pack")} sub={t("export.pack.sub")} onClick={dlPack} last />
          </Card>

          {/* 9 — estimate footnote */}
          <div style={{ fontSize: 12, color: "var(--color-text-3)", lineHeight: 1.5, padding: "0 4px" }}>
            {t("tax.estimate.note")}
          </div>
        </div>
      </div>
    );
  }

  window.QScreens = Object.assign(window.QScreens || {}, { Taxes });
})();
