/* Statement — what one creator has earned, and what is still coming. The
   answer to the question a talent manager gets weekly, in a form that can be
   sent to the creator.
   Commit model: INSTANT. Nothing commits here: releasing a payout is money
   leaving the account and lives on the money ledger, which is its one entry
   point in the product.
   Data state: populated or empty, never both — a creator with no deal gets one
   sentence and a way back, because a statement of nothing is not a statement.
   Actions derive from the record: the release control appears on the ledger,
   not here; this screen offers the export and the ledger link.
   Primary display: one table, because that is what a statement is. Every
   figure beneath it sums the exact rows above it. */
(() => {
  const {
    Button, Separator, Table, TableHeader, TableBody, TableFooter, TableRow, TableHead, TableCell,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  function StatementScreen({ creator, data, now, onNavigate, pushToast }) {
    const s = creatorStatement(data.deals, data.creators, creator);
    const years = statementYears(s.deals);
    const standard = AGENCY_POLICY.standardCommissionRate;
    const below = s.deals.filter((d) => d.commissionRate < standard);

    if (s.deals.length === 0) {
      return (
        <div className="mq-page">
          <PageHead
            path="/talent/:id/statement"
            params={{ id: creator.id }}
            labels={{ "/talent/:id": creator.name }}
            title={creator.name + " — statement"}
            lede="Nothing has been booked for them through this desk, so there is nothing to state."
          />
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon"><Icon name="receipt" size={18} /></EmptyMedia>
              <EmptyTitle>No campaign, no statement</EmptyTitle>
              <EmptyDescription>A statement is a sum of deals, and {creator.name.split(" ")[0]} has none on the book. It will fill itself in the moment a brief becomes a deal.</EmptyDescription>
            </EmptyHeader>
            <EmptyContent>
              <Button onClick={() => onNavigate("/talent/" + creator.id)}>Back to their file</Button>
            </EmptyContent>
          </Empty>
        </div>
      );
    }

    return (
      <div className="mq-page">
        <PageHead
          path="/talent/:id/statement"
          params={{ id: creator.id }}
          labels={{ "/talent/:id": creator.name }}
          title={creator.name + " — statement"}
          lede={"Every campaign booked through the desk since " + formatAbsolute(s.deals[s.deals.length - 1].agreedAt).split(",")[0] + ". " + formatMoney(s.netCents) + " is theirs across " + s.deals.length + " " + (s.deals.length === 1 ? "campaign" : "campaigns") + ", " + (s.paidCents ? "of which " + formatMoney(s.paidCents) + " has been paid." : "and none of it has been paid out yet.")}
          actions={<ExportMenu scope={creator.name + " statement"} onExport={(format) => pushToast({ title: "Export started", description: creator.name + " · " + format + " — every campaign, fee, commission and payout on this statement." })} />}
        />

        <div className="mq-bleed">
          <div className="mq-figures">
            <Figure size="xl" label="Theirs, after commission" value={formatMoney(s.netCents)} note={formatMoney(s.grossCents) + " billed to brands, " + formatMoney(s.commissionCents) + " ours"} />
            <Figure size="xl" label="Paid out" value={s.paid.length ? formatMoney(s.paidCents) : "Nothing yet"} note={s.paid.length ? s.paid.length + " of " + s.payouts.length + " payouts released, latest " + formatAbsolute(s.paid.slice().sort((a, b) => b.payout.paidAt - a.payout.paidAt)[0].payout.paidAt).split(",")[0] : "No payout has left the account for them"} />
            <Figure size="xl" label="Still owed" value={s.owed.length ? formatMoney(s.owedCents) : "Nothing"} note={s.owed.length ? [s.releasable.length ? s.releasable.length + " ready to release" : null, s.blocked.length ? s.blocked.length + " held until the brand pays" : null].filter(Boolean).join(", ") : "Every campaign they have run has been settled"} />
          </div>
          <p className="mq-note">
            Commission has worked out at {formatPercent(s.effectiveRate)} across their book against a standard of {Math.round(standard * 100)}%
            {below.length ? ", because " + below.map((d) => d.brand + " was signed at " + Math.round(d.commissionRate * 100) + "%").join(" and ") + "." : "."}
            {" "}Every deal stores the rate it was signed at, and this reads those rather than today's standard.
          </p>
        </div>

        <section className="mq-section">
          <div className="mq-section__head">
            <h2 className="mq-h2">Campaign by campaign<span className="mq-tab-count">{s.deals.length}</span></h2>
            <p className="mq-note">{years.length === 1 ? "All of it in " + years[0] + "." : years.join(", ") + ". "}Newest first. A payout is only ready once the brand's invoice has landed, so the last column is the brand's clock as much as ours.</p>
          </div>
          <div className="mq-table-wrap">
            <Table className="mq-tbl">
              <TableHeader>
                <TableRow>
                  <TableHead>Campaign</TableHead>
                  <TableHead className="mq-drop-lg">Agreed</TableHead>
                  <TableHead className="mq-num">Fee</TableHead>
                  <TableHead className="mq-num mq-drop-md">Commission</TableHead>
                  <TableHead className="mq-num">Theirs</TableHead>
                  <TableHead>Payout</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {s.deals.map((deal) => {
                  const payout = s.payouts.find((r) => r.deal.id === deal.id);
                  const settled = PAYOUT_FLAGS.isSettled(payout.payout);
                  return (
                    <TableRow key={deal.id}>
                      <TableCell>
                        <span className="mq-cellstack">
                          <button type="button" className="mq-link" onClick={() => onNavigate("/deals/" + deal.id)}>{deal.brand} · {deal.title}</button>
                          <span className="mq-row__meta">{deal.id} · {publishedOf(deal).length} of {deal.deliverables.length} pieces live</span>
                        </span>
                      </TableCell>
                      <TableCell className="mq-drop-lg mq-muted"><span className="mq-mono" title={formatAbsolute(deal.agreedAt)}>{formatAbsolute(deal.agreedAt).split(",")[0]}</span></TableCell>
                      <TableCell className="mq-num mq-amount">{formatMoney(deal.feeCents)}</TableCell>
                      <TableCell className="mq-num mq-drop-md mq-muted">{formatMoney(commissionOf(deal))} <span className="mq-mono">({Math.round(deal.commissionRate * 100)}%)</span></TableCell>
                      <TableCell className="mq-num mq-amount">{formatMoney(creatorNetOf(deal))}</TableCell>
                      <TableCell>
                        <span className="mq-cellstack">
                          <StatusBadge values={PAYOUT_STATUS} value={payout.payout.status} />
                          <span className="mq-row__meta">
                            {settled
                              ? payout.payout.reference + " · " + formatAbsolute(payout.payout.paidAt).split(",")[0]
                              : PAYOUT_FLAGS.isReleasable(payout.payout)
                                ? "Ready — next run " + formatAbsolute(nextPayoutRun(now)).split(",")[0]
                                : "Held until " + deal.brand + " pay " + deal.invoice.id}
                          </span>
                        </span>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
              <TableFooter>
                <TableRow>
                  <TableCell>{s.deals.length} {s.deals.length === 1 ? "campaign" : "campaigns"}</TableCell>
                  <TableCell className="mq-drop-lg" />
                  <TableCell className="mq-num mq-amount">{formatMoney(s.grossCents)}</TableCell>
                  <TableCell className="mq-num mq-drop-md">{formatMoney(s.commissionCents)}</TableCell>
                  <TableCell className="mq-num mq-amount">{formatMoney(s.netCents)}</TableCell>
                  <TableCell>{formatMoney(s.paidCents)} paid{s.owed.length ? ", " + formatMoney(s.owedCents) + " owed" : ""}</TableCell>
                </TableRow>
              </TableFooter>
            </Table>
          </div>
          <div className="mq-foot">
            <span>Fees are what the brand was billed; theirs is the fee less the commission stored on that deal. Nothing on this statement is a rounded figure.</span>
            <Button variant="ghost" size="xs" onClick={() => onNavigate("/money")}>Open the money ledger<Icon name="arrow-right" /></Button>
          </div>
        </section>

        {s.blocked.length ? (
          <section className="mq-section">
            <div className="mq-section__head">
              <h2 className="mq-h2">Why {formatMoney(moneyTotal(s.blocked))} has not moved</h2>
            </div>
            <div className="mq-sheet mq-sheet--tight">
              <div className="mq-lg">
                {s.blocked.map((r) => (
                  <LedgerRow
                    key={r.payout.id}
                    label={r.deal.brand}
                    hint={r.deal.invoice.status === "draft"
                      ? r.deal.invoice.id + " has not been issued — " + (r.deal.invoice.holdReason || "").toLowerCase()
                      : r.deal.invoice.id + " was due " + formatAbsolute(INVOICE_FLAGS.dueAt(r.deal.invoice)).split(",")[0] + " and is " + formatCountdown(INVOICE_FLAGS.dueAt(r.deal.invoice), now)}
                    value={formatMoney(r.amount)}
                  />
                ))}
              </div>
              <Separator />
              <p className="mq-note">We pay creators out of what the brand has paid us, so a late brand is a late payout. The chase lives on the money ledger, next to the invoice it belongs to.</p>
            </div>
          </section>
        ) : null}
      </div>
    );
  }

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