/* Recovery — the mirror image of the claim: once we have paid the customer, we
   pursue whoever caused the damage.
   Commit model: INSTANT. Filing a notice applies immediately with an undo
   toast; recording money back opens a staged dialog; writing a recovery off is
   irreversible and opens a confirm dialog.
   Data state: populated.
   Recession: a recovery sitting with the counterparty is open work the adjuster
   cannot act on, so it is recessed — the same rule as the queue and payments. */
(() => {
  const {
    Button, Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter, Meter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge,
  } = window.OriginDesignSystem_7c998b;

  function RecoveryScreen({ data, now, onNavigate, onRecoveryTransition, pushToast }) {
    const recoveries = data.recoveries;
    const claims = data.claims;
    const closed = closedRecoveries(recoveries);
    const open = openRecoveries(recoveries);
    const toFile = recoveriesToFile(recoveries);
    const rate = recoveryRate(recoveries);
    const byKind = recoveryByKind(recoveries, COUNTERPARTY_KINDS);
    const pursuedClosed = sumBy(closed, "soughtCents");
    const recovered = sumBy(closed, "recoveredCents");
    const rows = recoveries.slice().sort((a, b) => RECOVERY_FLAGS.daysLeft(a, now) - RECOVERY_FLAGS.daysLeft(b, now));

    return (
      <div className="cd-page">
        <PageHead
          path="/recovery"
          title="Recovery"
          lede={"Claims we have paid and are pursuing against the terminal, the trucker or the packer. Each recovery carries its own deadline, and " + toFile.length + " of the " + open.length + " open files is waiting on you."}
          actions={<><ExportMenu scope="Recoveries" onExport={(format) => pushToast({ title: "Export started", description: "Recoveries · " + format + " — we'll email it to " + CLAIMS_USER.name.split(" ")[0].toLowerCase() + "@corvenline.example" })} /><Button size="sm" onClick={() => onNavigate("/recovery/new")}>New recovery</Button></>}
        />

        <div className="cd-bleed">
          <div className="cd-split cd-split--band">
            <div className="cd-section">
              <div className="cd-figures">
                <Figure
                  xl
                  label="Recovery rate"
                  value={formatPercent(rate)}
                  note={formatMoney(recovered) + " back out of " + formatMoney(pursuedClosed) + " pursued and closed, across " + closed.length + " files. Open files are not in the rate."}
                />
                <Figure
                  label="Still in play"
                  value={formatMoney(sumBy(open, "soughtCents"))}
                  note={open.length + " open recoveries, " + toFile.length + " of them waiting on you to serve notice"}
                />
              </div>
            </div>
            <div className="cd-section">
              <div className="cd-section__head">
                <h2 className="cd-h2">Who we are pursuing</h2>
                <p className="cd-note">Share of the {formatMoney(sumBy(recoveries, "soughtCents"))} pursued across all {formatPlural(recoveries.length, "recovery", "recoveries")}.</p>
              </div>
              <div className="cd-col cd-col--tight">
                {byKind.map((row) => (
                  <div key={row.kind} style={{ display: "flex", flexDirection: "column", gap: "var(--space-1-5)" }}>
                    <div className="cd-mix__head" style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-4)", fontSize: "var(--text-sm)" }}>
                      <span>{row.label}<span className="cd-tab-count">{row.count}</span></span>
                      <span className="cd-amount">{formatMoney(row.sought)}</span>
                    </div>
                    <Meter value={row.sought} max={sumBy(recoveries, "soughtCents")} aria-label={row.label + " share of the amount pursued"} />
                    {row.recovered ? <div className="cd-figure__note">{formatMoney(row.recovered)} recovered so far</div> : null}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <section className="cd-section">
          <div className="cd-section__head">
            <h2 className="cd-h2">Recovery files</h2>
            <p className="cd-note">Sorted by their own deadline, soonest first — a recovery's clock is contractual, not the cargo time bar.</p>
          </div>
          <div className="cd-table-wrap">
            <Table className="cd-tbl">
              <TableHeader>
                <TableRow>
                  <TableHead>Counterparty</TableHead>
                  <TableHead className="cd-drop-lg">Paid claim</TableHead>
                  <TableHead className="cd-num">Sought</TableHead>
                  <TableHead className="cd-num">Recovered</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="cd-drop-md">Their deadline</TableHead>
                  <TableHead className="cd-actions"><span className="o-sr">Action</span></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((recovery) => {
                  const claim = claimById(claims, recovery.claimId);
                  const transitions = recoveryTransitions(recovery);
                  const daysLeft = RECOVERY_FLAGS.daysLeft(recovery, now);
                  const recessed = RECOVERY_FLAGS.isOpen(recovery) && !RECOVERY_FLAGS.awaitsAdjuster(recovery);
                  return (
                    <TableRow key={recovery.id} className={recessed ? "cd-row-recessed" : ""}>
                      <TableCell>
                        <span className="cd-record">
                          <button type="button" className="cd-record__link" onClick={() => onNavigate("/recovery/" + recovery.id)}>{recovery.counterparty.name}</button>
                          <span className="cd-record__meta"><code>{recovery.id}</code> · {labelOf(COUNTERPARTY_KINDS, recovery.counterparty.kind)}</span>
                        </span>
                      </TableCell>
                      <TableCell className="cd-drop-lg">
                        <span className="cd-muted">{claim ? claim.customer : recovery.claimId}</span>
                      </TableCell>
                      <TableCell className="cd-num cd-amount">{formatMoney(recovery.soughtCents)}</TableCell>
                      <TableCell className="cd-num">
                        {recovery.recoveredCents ? <span className="cd-amount">{formatMoney(recovery.recoveredCents)}</span> : <span className="cd-muted">—</span>}
                      </TableCell>
                      <TableCell>
                        <span className="cd-record">
                          <StatusBadge values={RECOVERY_STATUS} value={recovery.status} />
                          {recovery.status === "negotiating" && recovery.offerCents ? <span className="cd-record__meta">Offered {formatMoney(recovery.offerCents)}</span> : null}
                          {recessed ? <span className="cd-record__meta">Waiting on {recovery.counterparty.name}</span> : null}
                        </span>
                      </TableCell>
                      <TableCell className="cd-drop-md">
                        {RECOVERY_FLAGS.isOpen(recovery) ? (
                          <span className="cd-cell-clock">
                            <span className={clockClass(timeTone(daysLeft))} title={formatAbsolute(recovery.fileByAt)}>{formatCountdown(recovery.fileByAt, now)}</span>
                            <TimeBar startAt={recovery.openedAt} endAt={recovery.fileByAt} now={now} mini label={"Recovery deadline: " + formatCountdown(recovery.fileByAt, now)} />
                          </span>
                        ) : (
                          <span className="cd-muted cd-clock">Closed {formatWhen(recovery.closedAt, now)}</span>
                        )}
                      </TableCell>
                      <TableCell className="cd-actions">
                        {transitions.filter((t) => t.primary).map((t) => (
                          <Button key={t.id} size="xs" onClick={() => onRecoveryTransition(recovery, t)}>{t.label}</Button>
                        ))}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
          <div className="cd-foot">
            <span>Showing {rows.length} of {formatPlural(recoveries.length, "recovery", "recoveries")} · {formatMoney(sumBy(recoveries, "soughtCents"))} pursued in total</span>
            <span>{open.length} open, {closed.length} closed.</span>
          </div>
        </section>
      </div>
    );
  }

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