/* Payments — scheduling the payout and watching it land.
   Commit model: INSTANT. Scheduling applies immediately and raises an undo
   toast; sending money is irreversible and opens a confirm dialog. There is no
   Save button on this screen.
   Data state: populated. The empty branch (no approved claim carries a
   settlement) is the other half of one conditional.
   Recession, chosen once for the product: an open record the adjuster cannot
   act on is recessed — here that is a payment already sitting with the bank. A
   scheduled payment can still be sent, and a cleared one is closed rather than
   blocked, so neither is recessed. */
(() => {
  const {
    Button, Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent, Badge,
  } = window.OriginDesignSystem_7c998b;

  const STAGE_TONE = {};
  SETTLEMENT_STATUS.forEach((v) => { STAGE_TONE[v.id] = v.tone; });

  /* The date a settlement's own status makes relevant — one rule per column. */
  function settlementWhen(settlement) {
    if (settlement.status === "cleared") return { label: "Cleared", at: settlement.clearedAt };
    if (settlement.status === "returned") return { label: "Returned", at: settlement.returnedAt };
    if (settlement.status === "sent") return { label: "Sent", at: settlement.sentAt };
    if (settlement.status === "scheduled") return { label: "Scheduled", at: settlement.scheduledFor };
    return { label: "Not scheduled", at: null };
  }

  function PaymentsScreen({ data, now, onNavigate, onSettlementTransition, pushToast }) {
    const claims = data.claims;
    const rows = settledClaims(claims).slice().sort((a, b) => (settlementWhen(b.settlement).at || now) - (settlementWhen(a.settlement).at || now));
    const toSchedule = settlementsToSchedule(claims);
    const scheduled = settlementsWith(claims, "scheduled");
    const cleared = settlementsWith(claims, "cleared");
    const pipeline = releasePipeline(claims);
    const pipelineTotal = settlementTotal(rows);
    const runAt = nextRunDate(now);

    return (
      <div className="cd-page">
        <PageHead
          path="/payments"
          title="Payments"
          lede={"Every claim we have approved and not yet closed out. Payment runs leave on Wednesdays; the next one is " + formatAbsolute(runAt) + "."}
          actions={<ExportMenu scope="Settlements" onExport={(format) => pushToast({ title: "Export started", description: "Settlements · " + format + " — we'll email it to " + CLAIMS_USER.name.split(" ")[0].toLowerCase() + "@corvenline.example" })} />}
        />

        <div className="cd-bleed">
          <div className="cd-split cd-split--band">
            <div className="cd-section">
              <div className="cd-figures">
                <Figure
                  xl
                  label="Waiting on you to schedule"
                  value={formatMoney(settlementTotal(toSchedule))}
                  note={toSchedule.length + " of the " + rows.length + " settlements on this desk, including anything the bank has sent back"}
                />
                <Figure
                  label="In the next run"
                  value={formatMoney(settlementTotal(scheduled))}
                  note={scheduled.length + " scheduled for " + formatAbsolute(runAt)}
                />
                <Figure
                  label="Cleared to date"
                  value={formatMoney(settlementTotal(cleared))}
                  note={cleared.length + " settlements in the customer's account"}
                />
              </div>
              <div className="cd-section">
                <h2 className="cd-h3">Where the money is, across {formatMoney(pipelineTotal)}</h2>
                <div className="cd-flow">
                  {pipeline.map((stage) => (
                    <div className="cd-flow__seg" key={stage.id} data-tone={STAGE_TONE[stage.id]} style={{ flexGrow: Math.max(1, Math.round(stage.amount / 1000)), flexBasis: 0 }}>
                      <span className="cd-flow__amount">{formatMoney(stage.amount)}</span>
                      <span className="cd-flow__label">{stage.label} · {stage.count}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="cd-section">
              <div className="cd-section__head">
                <h2 className="cd-h2">Next run</h2>
                <span className="cd-clock">{formatCountdown(runAt, now)}</span>
              </div>
              <p className="cd-note">{formatAbsolute(runAt)}. Anything scheduled before it leaves that morning.</p>
              <div className="cd-rows">
                {scheduled.length ? scheduled.map((claim) => (
                  <div className="cd-row" key={claim.id}>
                    <div className="cd-row__main">
                      <span className="cd-record__name">{claim.customer}</span>
                      <span className="cd-record__meta"><code>{claim.id}</code> · {claim.settlement.reference}</span>
                    </div>
                    <div className="cd-row__side">
                      <span className="cd-amount">{formatMoney(claim.settlement.amountCents)}</span>
                      <span className="cd-record__meta">{formatWhen(claim.settlement.scheduledFor, now)}</span>
                    </div>
                  </div>
                )) : (
                  <p className="cd-note">Nothing is scheduled for this run yet. {toSchedule.length ? toSchedule.length + " settlements are waiting on you to book one." : ""}</p>
                )}
              </div>
            </div>
          </div>
        </div>

        <section className="cd-section">
          <div className="cd-section__head">
            <h2 className="cd-h2">Settlements</h2>
            <p className="cd-note">Newest movement first.</p>
          </div>
          {rows.length === 0 ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="banknote" size={18} /></EmptyMedia>
                <EmptyTitle>Nothing approved is waiting to be paid</EmptyTitle>
                <EmptyDescription>A settlement appears here the moment a claim is approved on the decision screen.</EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button variant="outline" onClick={() => onNavigate("/")}>Back to the work queue</Button>
              </EmptyContent>
            </Empty>
          ) : (
            <div className="cd-table-wrap">
              <Table className="cd-tbl">
                <TableHeader>
                  <TableRow>
                    <TableHead>Claim</TableHead>
                    <TableHead className="cd-drop-lg">Reference</TableHead>
                    <TableHead className="cd-num">Amount</TableHead>
                    <TableHead>Settlement</TableHead>
                    <TableHead className="cd-drop-md">Movement</TableHead>
                    <TableHead className="cd-actions"><span className="o-sr">Action</span></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.map((claim) => {
                    const settlement = claim.settlement;
                    const when = settlementWhen(settlement);
                    const transitions = settlementTransitions(claim);
                    const recessed = settlement.status === "sent";
                    return (
                      <TableRow key={claim.id} className={recessed ? "cd-row-recessed" : ""}>
                        <TableCell>
                          <span className="cd-record">
                            <button type="button" className="cd-record__link" onClick={() => onNavigate("/claims/" + claim.id)}>{claim.customer}</button>
                            <span className="cd-record__meta"><code>{claim.id}</code> · {labelOf(DECISION_OUTCOMES, claim.decision.outcome)}</span>
                          </span>
                        </TableCell>
                        <TableCell className="cd-drop-lg cd-muted"><span className="cd-code">{settlement.reference || "—"}</span></TableCell>
                        <TableCell className="cd-num cd-amount">{formatMoney(settlement.amountCents)}</TableCell>
                        <TableCell>
                          <span className="cd-record">
                            <StatusBadge values={SETTLEMENT_STATUS} value={settlement.status} />
                            {settlement.status === "returned" ? <span className="cd-record__meta">{settlement.returnReason}</span> : null}
                            {settlement.status === "sent" ? <span className="cd-record__meta">With the beneficiary bank</span> : null}
                          </span>
                        </TableCell>
                        <TableCell className="cd-drop-md">
                          <span className="cd-record">
                            <span className="cd-muted" style={{ fontSize: "var(--text-xs)" }}>{when.label}</span>
                            <span title={when.at ? formatAbsolute(when.at) : ""}>{when.at ? formatWhen(when.at, now) : "—"}</span>
                          </span>
                        </TableCell>
                        <TableCell className="cd-actions">
                          {transitions.map((t) => (
                            <Button key={t.id} size="xs" onClick={() => onSettlementTransition(claim, t)}>{t.label}</Button>
                          ))}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
          <div className="cd-foot">
            <span>Showing {rows.length} of {rows.length} settlements · {formatMoney(pipelineTotal)} in total</span>
            <span>{toSchedule.length} waiting on you, {scheduled.length} in the run, {settlementsWith(claims, "sent").length} with the bank, {cleared.length} cleared.</span>
          </div>
        </section>
      </div>
    );
  }

  Object.assign(window, { PaymentsScreen, settlementWhen });
})();
