/* Reports — chart-led. The one destination whose primary display is a chart
   rather than a table: the question is "what shape was the money this month",
   and the two mix cards and the customer table beneath it are the rows behind
   the bars.
   Commit model: INSTANT — the only controls are the period scope and export.
   Data state: populated.
   Scope (§5.3): the period select sits above every figure on the screen and
   moves all of them; nothing on this screen filters a list. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Select, Meter, Button,
  } = window.OriginDesignSystem_7c998b;

  function ReportsScreen({ data, now, period, onPeriodChange, onNavigate, pushToast }) {
    const days = Number(period);
    const periodLabel = PERIODS.find((p) => p.value === period).label;

    const payments = paymentsInPeriod(data.payments, days, now);
    const expenses = expensesInPeriod(data.expenses, days, now);
    const disputes = disputesInPeriod(data.disputes, days, now);
    const succeeded = succeededPayments(payments);

    const volume = netVolume(payments);
    const spend = cardSpendTotal(expenses);
    const payoutsPaid = data.payouts.filter((p) => p.status === "paid" && p.paidAt >= now - days * 24 * 3600e3);
    const movement = movementByDay(payments, data.payouts, data.expenses, now, days);
    const mix = methodMix(payments, PAYMENT_METHODS);
    const categories = spendByCategory(expenses, EXPENSE_CATEGORIES);
    const customers = topCustomers(payments, 8);
    const disputeShare = sumBy(succeeded, "amount") ? sumBy(disputes, "amount") / sumBy(succeeded, "amount") : null;

    return (
      <div className="fd-page">
        <PageHeader
          path="/reports"
          title="Reports"
          actions={<ExportMenu scope={periodLabel} onExport={(format) => pushToast({ title: "Export started", description: periodLabel + " · " + format + " — every figure on this screen, with the rows behind it" })} />}
        />

        <div className="fd-scope">
          <div className="fd-scope__control">
            <label className="fd-scope__label" htmlFor="fd-rep-period">Period</label>
            <Select id="fd-rep-period" size="sm" items={PERIODS} value={period} onValueChange={onPeriodChange} />
          </div>
          <p className="fd-scope__note">Everything on this screen covers the {periodLabel.toLowerCase()} for {MERIDIAN_WORKSPACE.name}. Nothing here is filtered further down.</p>
        </div>

        <div className="fd-metrics">
          <MetricTile
            icon="arrow-down-left" label="Net volume in"
            value={formatMoney(volume)}
            qualifier={succeeded.length + " succeeded payments, less " + formatMoney(refundTotal(payments)) + " refunded"}
          />
          <MetricTile
            icon="arrow-up-right" label="Money out"
            value={formatMoney(spend + sumBy(payoutsPaid, "amount"))}
            qualifier={formatMoney(sumBy(payoutsPaid, "amount")) + " in " + payoutsPaid.length + " payouts that landed, " + formatMoney(spend) + " of settled card spend"}
          />
          <MetricTile
            icon="scale" label="Net position"
            value={formatMoney(volume - spend - sumBy(payoutsPaid, "amount"))}
            qualifier="Volume in, less the payouts that landed and the card spend that settled"
          />
          <MetricTile
            icon="shield-alert" label="Disputed share of volume"
            value={formatPercent(disputeShare)}
            qualifier={disputes.length + " disputes opened, " + formatMoney(sumBy(disputes, "amount")) + " against " + formatMoney(sumBy(succeeded, "amount")) + " succeeded"}
          />
        </div>

        <Card className="fd-card">
          <CardHeader>
            <CardTitle>Money in and out, by day</CardTitle>
            <CardDescription>In is payments that settled. Out is payouts that landed in the bank plus card spend that settled — approvals and authorisations are outside both.</CardDescription>
          </CardHeader>
          <CardPanel>
            <DayChart
              tall
              buckets={movement}
              series={[{ key: "in", label: "Settled in", rows: [{ key: "payments", noun: "payment" }] }, { key: "out", label: "Paid and spent out", tone: "soft", rows: [{ key: "payouts", noun: "payout" }, { key: "expenses", noun: "expense" }] }]}
              format={formatMoney}
              label="Money in and out a day"
              note={"Bars sum to " + formatMoney(sumBy(movement, "in")) + " in and " + formatMoney(sumBy(movement, "out")) + " out over the " + periodLabel.toLowerCase() + "."}
            />
          </CardPanel>
        </Card>

        <div className="fd-columns fd-columns--even">
          <div className="fd-col">
            <Card className="fd-card">
              <CardHeader>
                <CardTitle>How the volume arrived</CardTitle>
                <CardDescription>{formatMoney(sumBy(succeeded, "amount"))} succeeded across {succeeded.length} payments.</CardDescription>
              </CardHeader>
              <CardPanel>
                {mix.length ? <MixRows rows={mix} total={sumBy(succeeded, "amount")} unitLabel="succeeded volume" /> : <span className="fd-footnote">Nothing succeeded in this period.</span>}
              </CardPanel>
              <CardFooter className="fd-card-footer">
                <span className="fd-footnote">Refunded and failed payments are outside this breakdown.</span>
                <Button variant="ghost" size="sm" onClick={() => onNavigate("/payments")}>Open payments<Icon name="arrow-right" /></Button>
              </CardFooter>
            </Card>
          </div>
          <div className="fd-col">
            <Card className="fd-card">
              <CardHeader>
                <CardTitle>Where the spend went</CardTitle>
                <CardDescription>{formatMoney(spend)} of settled card spend across {settledExpenses(expenses).length} expenses.</CardDescription>
              </CardHeader>
              <CardPanel>
                {categories.length ? <MixRows rows={categories} total={spend} unitLabel="settled card spend" /> : <span className="fd-footnote">No card spend settled in this period.</span>}
              </CardPanel>
              <CardFooter className="fd-card-footer">
                <span className="fd-footnote">{pendingExpenses(expenses).length} authorisations have not settled and are outside it.</span>
                <Button variant="ghost" size="sm" onClick={() => onNavigate("/expenses")}>Open expenses<Icon name="arrow-right" /></Button>
              </CardFooter>
            </Card>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Who the volume came from</CardTitle>
            <CardDescription>The {customers.length} largest customers by net volume, {periodLabel.toLowerCase()}. Share decomposes the {formatMoney(volume)} above.</CardDescription>
          </CardHeader>
          <div className="fd-card-table">
            <Table variant="card">
              <TableHeader>
                <TableRow>
                  <TableHead>Customer</TableHead>
                  <TableHead className="fd-drop-md">Payments</TableHead>
                  <TableHead className="fd-num">Net volume</TableHead>
                  <TableHead style={{ width: "12rem" }}>Share</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {customers.map((row) => (
                  <TableRow key={row.customer}>
                    <TableCell><span className="fd-record__name">{row.customer}</span></TableCell>
                    <TableCell className="fd-drop-md fd-muted">{row.rows.length}</TableCell>
                    <TableCell className="fd-num fd-amount">{formatMoney(row.amount)}</TableCell>
                    <TableCell>
                      <span className="fd-spread">
                        <Meter value={Math.max(0, row.amount)} max={Math.max(volume, 1)} aria-label={row.customer + " share of net volume"} />
                        <span className="fd-footnote">{formatPercent(row.share)}</span>
                      </span>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          <CardFooter className="fd-card-footer">
            <span className="fd-footnote">{formatMoney(sumBy(customers, "amount"))} of the {formatMoney(volume)} net volume, from {customers.length} of the {new Set(payments.map((p) => p.customer)).size} customers who paid in the period.</span>
          </CardFooter>
        </Card>
      </div>
    );
  }

  Object.assign(window, { ReportsScreen });
})();
