/* Claimant — one customer, and everything this desk knows about them.
   Commit model: INSTANT, and in fact read-only: a claimant record holds no
   transitions of its own, because every action belongs to a claim. Nothing on
   this screen is a control except navigation.
   Data state: populated. A claimant with no claims cannot be reached — the
   record is created by its claims — so there is no empty branch here.
   Derivation: the claimant fixture holds only what a claim cannot (who to write
   to, when they first shipped, their lane and terms). Every figure below is
   their own claims read through the same helpers the queue and payments use. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter, Button,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
  } = window.OriginDesignSystem_7c998b;

  function ClaimantScreen({ claimant, data, now, onNavigate, onNewClaim }) {
    const s = claimantSummary(claimant, data.claims, data.recoveries, now);
    const disputedGap = disputedGapTotal(s.rows);

    const lede = formatPlural(s.rows.length, "claim") + " against us, first filed "
      + formatAbsolute(s.firstClaim.claimedAt).split(",")[0]
      + (s.open.length ? ". " + formatPlural(s.open.length, "claim") + " still open" : ". Nothing open")
      + (s.rejected.length ? ", " + formatPlural(s.rejected.length, "claim") + " turned down." : ".");

    return (
      <div className="cd-page">
        <PageHead
          path="/claimants/:id"
          params={{ id: claimant.id }}
          labels={{ "/claimants/:id": claimant.name }}
          title={claimant.name}
          lede={lede}
          actions={<Button size="sm" onClick={() => onNewClaim(claimant.id)}>New claim</Button>}
        />

        <div className="cd-facts">
          <span><strong>{claimant.contact}</strong> · {claimant.email}</span>
          <span>{claimant.lane}</span>
          <span>{claimant.terms}</span>
          <span>Shipping with us since {formatAbsolute(claimant.since).split(",")[0]}</span>
        </div>

        <div className="cd-bleed">
          <div className="cd-figures">
            <Figure
              xl
              label="Claimed against us"
              value={formatMoney(s.claimed)}
              note={"across " + formatPlural(s.rows.length, "claim") + " on the " + CLAIMS_CARRIER.region + " desk"}
            />
            <Figure
              label="Still open"
              value={s.open.length ? formatMoney(s.openClaimed) : "Nothing open"}
              note={s.open.length
                ? formatPlural(s.open.length, "claim") + " claimed, nearest bar " + formatCountdown(CLAIM_FLAGS.timeBarAt(s.nearestBar), now)
                : "Every claim they have filed is closed"}
            />
            <Figure
              label="Paid out"
              value={s.released.length ? formatMoney(s.releasedTotal) : "Nothing paid"}
              note={s.released.length
                ? formatPlural(s.released.length, "settlement") + " sent or cleared"
                : "No settlement has left the account"}
            />
          </div>
        </div>

        <section className="cd-section">
          <div className="cd-section__head">
            <h2 className="cd-h2">Their claims</h2>
            <p className="cd-note">Every claim this claimant has filed, open and closed, soonest time bar first.</p>
          </div>
          <div className="cd-table-wrap">
            <Table className="cd-tbl">
              <TableHeader>
                <TableRow>
                  <TableHead>Claim</TableHead>
                  <TableHead className="cd-drop-lg">Cargo</TableHead>
                  <TableHead className="cd-num">Claimed</TableHead>
                  <TableHead className="cd-num">Payable</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="cd-drop-md">Time bar</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {byUrgency(s.rows, now).map((claim) => {
                  const recessed = CLAIM_FLAGS.isWaitingOnOthers(claim);
                  const payable = payableOf(claim);
                  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)}><code>{claim.id}</code></button>
                          <span className="cd-record__meta">{claim.incident}</span>
                        </span>
                      </TableCell>
                      <TableCell className="cd-drop-lg cd-muted">
                        <span className="cd-record">
                          <span>{claim.commodity}</span>
                          <span className="cd-record__meta">{claim.container} · {claim.pol} → {claim.pod}</span>
                        </span>
                      </TableCell>
                      <TableCell className="cd-num cd-amount">{formatMoney(claim.claimedCents)}</TableCell>
                      <TableCell className="cd-num">
                        {claim.decision && claim.decision.outcome === "reject"
                          ? <span className="cd-muted">Nothing payable</span>
                          : payable === null
                            ? <span className="cd-muted">Not assessed</span>
                            : <span className="cd-amount">{formatMoney(payable)}</span>}
                      </TableCell>
                      <TableCell>
                        <span className="cd-record">
                          <StatusBadge values={CLAIM_STATUS} value={claim.status} />
                          {recessed ? <span className="cd-record__meta">Waiting on {waitingOn(claim)}</span> : null}
                        </span>
                      </TableCell>
                      <TableCell className="cd-drop-md">
                        {CLAIM_FLAGS.isOpen(claim)
                          ? <ClaimClock claim={claim} now={now} mini />
                          : <span className="cd-muted cd-clock">Closed {formatWhen(claim.decision ? claim.decision.decidedAt : claim.claimedAt, now)}</span>}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
          <div className="cd-foot">
            <span>{formatPlural(s.rows.length, "claim")} · {formatMoney(s.claimed)} claimed in total</span>
            <span>Figures read the same helpers as the work queue.</span>
          </div>
        </section>

        <div className="cd-split cd-split--even">
          <Card>
            <CardHeader>
              <CardTitle>How our offers landed</CardTitle>
              <CardDescription>What this claimant did once we put a figure to them.</CardDescription>
            </CardHeader>
            <CardPanel>
              {s.offers.length === 0 ? (
                <p className="cd-note">No offer has been put to them yet, so there is nothing to read here.</p>
              ) : (
                <dl className="cd-kv">
                  <div><dt>Offers made</dt><dd>{formatCount(s.offers.length)}</dd></div>
                  <div><dt>Answered</dt><dd>{formatCount(s.answered.length)}</dd></div>
                  <div><dt>Accepted</dt><dd>{formatCount(s.accepted.length)}</dd></div>
                  <div><dt>Disputed</dt><dd>{formatCount(s.disputed.length)}</dd></div>
                  {s.disputed.length ? <div><dt>Held against us</dt><dd>{formatMoney(disputedGap)}</dd></div> : null}
                </dl>
              )}
            </CardPanel>
            {s.disputed.length ? (
              <CardFooter className="cd-card-footer">
                <span className="cd-footnote">{s.disputed.map((c) => c.id).join(", ")} {s.disputed.length === 1 ? "is" : "are"} in dispute.</span>
                <button type="button" className="cd-record__link" onClick={() => onNavigate("/responses")}>Open responses</button>
              </CardFooter>
            ) : null}
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Recovered on their claims</CardTitle>
              <CardDescription>What we pursued from the party that caused the damage.</CardDescription>
            </CardHeader>
            <CardPanel>
              {s.recoveries.length === 0 ? (
                <p className="cd-note">No recovery has been opened against any of their claims.</p>
              ) : (
                <div className="cd-rows">
                  {s.recoveries.map((recovery) => (
                    <div className="cd-row" key={recovery.id}>
                      <div className="cd-row__main">
                        <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> · from {recovery.claimId}</span>
                      </div>
                      <div className="cd-row__side">
                        <StatusBadge values={RECOVERY_STATUS} value={recovery.status} />
                        <span className="cd-record__meta">
                          {recovery.recoveredCents ? formatMoney(recovery.recoveredCents) + " back of " + formatMoney(recovery.soughtCents) : formatMoney(recovery.soughtCents) + " sought"}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardPanel>
          </Card>
        </div>
      </div>
    );
  }

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