/* Sign-off — what this desk has sent up, and what has come back.
   Commit model: INSTANT. Both row actions apply immediately and raise an undo
   toast; nothing here is irreversible and there is no Save button.
   Data state: populated, or the empty branch when nothing is waiting — one
   conditional, never both.
   Scope: everything on this desk above the adjuster's authority. No period
   filter, so no figure moves when the list does.

   Recession, deliberately not applied: every row here is waiting on the same
   person, so recessing all of them would carry no information. §5.4's real
   requirement — name what is being waited on — is met by the "With" column,
   which names the manager and how long he has had it. */
(() => {
  const {
    Button,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  /* A wait long enough to be worth a sentence rather than a number. */
  const STALE_SIGNOFF_DAYS = 7;

  function SignoffScreen({ data, now, onNavigate, onTransition }) {
    const claims = data.claims;
    const waiting = bySignoffWait(claims);
    const decided = decidedClaims(claims);
    const signed = signedOffClaims(claims);
    const oldest = longestSignoffWait(claims);
    const stale = waiting.filter((c) => daysSince(CLAIM_FLAGS.signoffWaitingSince(c), now) >= STALE_SIGNOFF_DAYS);
    const recentlySigned = signed.slice().sort((a, b) => b.decision.decidedAt - a.decision.decidedAt).slice(0, 4);

    return (
      <div className="cd-page">
        <PageHead
          path="/signoff"
          title="Sign-off"
          lede={"Decisions above your " + formatMoney(CLAIM_POLICY.authorityLimitCents) + " authority. " + CLAIMS_MANAGER.name + " signs them; you can chase one or take it back, and nothing here is yours to approve."}
        />

        <div className="cd-bleed">
          <div className="cd-figures">
            <Figure
              xl
              label="Waiting on a signature"
              value={waiting.length ? formatMoney(signoffValue(waiting)) : "Nothing waiting"}
              note={waiting.length ? formatPlural(waiting.length, "decision") + " with " + CLAIMS_MANAGER.name : "Nothing is with " + CLAIMS_MANAGER.name}
            />
            <Figure
              label="Longest wait"
              value={oldest ? formatPlural(daysSince(CLAIM_FLAGS.signoffWaitingSince(oldest), now), "day") : "—"}
              note={oldest ? oldest.id + " · " + oldest.customer : "No decision is waiting"}
            />
            <Figure
              label="Signed off on this desk"
              value={formatCount(signed.length)}
              note={"of " + formatPlural(decided.length, "decision") + " recorded, the rest inside your own authority"}
            />
          </div>
          {stale.length ? (
            <p className="cd-note" style={{ maxWidth: "46rem" }}>
              {stale.map((c) => c.id).join(", ")} {stale.length === 1 ? "has" : "have"} been unsigned for more than {formatPlural(STALE_SIGNOFF_DAYS, "day")}. Chasing writes a note to the file so the claimant can be told a date.
            </p>
          ) : null}
        </div>

        <section className="cd-section">
          <div className="cd-section__head">
            <h2 className="cd-h2">With {CLAIMS_MANAGER.name}</h2>
            <p className="cd-note">Sorted by how long each has been waiting, longest first.</p>
          </div>

          {waiting.length === 0 ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="check" size={18} /></EmptyMedia>
                <EmptyTitle>Nothing is waiting on a signature</EmptyTitle>
                <EmptyDescription>Every decision recorded on this desk was inside your {formatMoney(CLAIM_POLICY.authorityLimitCents)} authority, or has already been signed.</EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button onClick={() => onNavigate("/")}>Open the queue</Button>
              </EmptyContent>
            </Empty>
          ) : (
            <div className="cd-table-wrap">
              <Table className="cd-tbl">
                <TableHeader>
                  <TableRow>
                    <TableHead>Claim</TableHead>
                    <TableHead className="cd-drop-lg">Decision</TableHead>
                    <TableHead className="cd-num">Payable</TableHead>
                    <TableHead className="cd-num cd-drop-md">Over authority by</TableHead>
                    <TableHead>With</TableHead>
                    <TableHead className="cd-actions"><span className="o-sr">Action</span></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {waiting.map((claim) => {
                    const payable = payableOf(claim);
                    const waited = daysSince(CLAIM_FLAGS.signoffWaitingSince(claim), now);
                    const chase = claimTransitions(claim).find((t) => t.id === "chase_signoff");
                    return (
                      <TableRow key={claim.id}>
                        <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> · {claim.container}</span>
                          </span>
                        </TableCell>
                        <TableCell className="cd-drop-lg cd-muted">
                          <span className="cd-record">
                            <span>{labelOf(DECISION_OUTCOMES, claim.decision.outcome)}</span>
                            <span className="cd-record__meta">Recorded {formatWhen(claim.decision.decidedAt, now)} by {claim.decision.decidedBy}</span>
                          </span>
                        </TableCell>
                        <TableCell className="cd-num cd-amount">{formatMoney(payable)}</TableCell>
                        <TableCell className="cd-num cd-drop-md cd-muted">{formatMoney(payable - CLAIM_POLICY.authorityLimitCents)}</TableCell>
                        <TableCell>
                          <span className="cd-record">
                            <StatusBadge values={CLAIM_STATUS} value={claim.status} />
                            <span className="cd-record__meta">{CLAIMS_MANAGER.name} · {formatPlural(waited, "day")}</span>
                          </span>
                        </TableCell>
                        <TableCell className="cd-actions">
                          <Button variant="outline" size="xs" onClick={() => onTransition(claim, chase)}>{chase.label}</Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
          <div className="cd-foot">
            <span>{formatPlural(waiting.length, "decision")} waiting · {formatMoney(signoffValue(waiting))} in total</span>
            <span>Taking one back reopens its assessment on your desk.</span>
          </div>
        </section>

        <section className="cd-section">
          <div className="cd-section__head">
            <h2 className="cd-h2">Signed off before</h2>
            <p className="cd-note">The last {recentlySigned.length} of {formatPlural(signed.length, "decision")} {CLAIMS_MANAGER.name} has signed, newest first.</p>
          </div>
          <div className="cd-rows">
            {recentlySigned.map((claim) => (
              <div className="cd-row" key={claim.id}>
                <div className="cd-row__main">
                  <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)} · signed by {claim.decision.signedOffBy}</span>
                </div>
                <div className="cd-row__side">
                  <span className="cd-amount">{formatMoney(payableOf(claim))}</span>
                  <span className="cd-record__meta" title={formatAbsolute(claim.decision.decidedAt)}>Decided {formatWhen(claim.decision.decidedAt, now)}</span>
                </div>
              </div>
            ))}
          </div>
        </section>
      </div>
    );
  }

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