/* Recovery file — one pursuit, against one counterparty, on its own clock.
   Commit model: INSTANT. Filing a notice applies immediately with an undo
   toast, recording money back opens a staged dialog, writing off opens a
   confirm dialog.
   Data state: populated. A recovery id that does not resolve is a branch in
   App, not a state of this screen. */
(() => {
  const {
    Button, Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter, Badge,
  } = window.OriginDesignSystem_7c998b;

  function RecoveryDetailScreen({ recovery, data, now, onNavigate, onRecoveryTransition }) {
    const claim = claimById(data.claims, recovery.claimId);
    const daysLeft = RECOVERY_FLAGS.daysLeft(recovery, now);
    const transitions = recoveryTransitions(recovery);
    const shortfall = RECOVERY_FLAGS.shortfall(recovery);

    return (
      <div className="cd-page">
        <div className="cd-head-record">
          <div className="cd-head-record__top">
            <div className="cd-page-head__text">
              <Crumbs path="/recovery/:id" params={{ id: recovery.id }} labels={{ "/recovery/:id": recovery.id }} />
              <span className="cd-head-record__id">
                <span className="cd-code">{recovery.id}</span>
                <StatusBadge values={RECOVERY_STATUS} value={recovery.status} />
                <Badge size="sm" variant="outline">{labelOf(COUNTERPARTY_KINDS, recovery.counterparty.kind)}</Badge>
              </span>
              <h1 className="cd-title">{recovery.counterparty.name}</h1>
              <p className="cd-lede">{recovery.basis}</p>
            </div>
            <div className="cd-page-head__actions">
              {transitions.map((t) => (
                <Button key={t.id} size="sm" variant={t.primary ? "default" : t.destructive ? "destructive-outline" : "outline"} onClick={() => onRecoveryTransition(recovery, t)}>{t.label}</Button>
              ))}
              {claim ? <Button variant="ghost" size="sm" onClick={() => onNavigate("/claims/" + claim.id)}>The paid claim<Icon name="arrow-right" /></Button> : null}
            </div>
          </div>
          <div className="cd-head-record__bar">
            <TimeBar startAt={recovery.openedAt} endAt={recovery.fileByAt} now={now} label={"Recovery deadline: " + formatCountdown(recovery.fileByAt, now)} />
            <div className="cd-head-record__left">
              <div className={clockClass(timeTone(daysLeft))} style={{ fontSize: "var(--text-sm)", fontWeight: "var(--font-weight-medium)" }} title={formatAbsolute(recovery.fileByAt)}>{formatCountdown(recovery.fileByAt, now)}</div>
              <div className="cd-figure__note">on the contract clock</div>
            </div>
            <div className="cd-head-record__ends">
              <span>Opened {formatAbsolute(recovery.openedAt).split(",")[0]}</span>
              <span>Deadline {formatAbsolute(recovery.fileByAt).split(",")[0]}</span>
            </div>
          </div>
          <div className="cd-facts">
            <span><strong>{claim ? claim.customer : recovery.claimId}</strong> · {claim ? claim.container : ""}</span>
            <span>{recovery.noticeServedAt ? "Notice served " + formatAbsolute(recovery.noticeServedAt) : "Notice not served"}</span>
            <span>{recovery.counterparty.contact}</span>
          </div>
        </div>

        <div className="cd-split">
          <div className="cd-col">
            <Card className="cd-card">
              <CardHeader>
                <CardTitle>The mirror ledger</CardTitle>
                <CardDescription>What we paid out, what we are pursuing, and what has come back. The claim owns the first figure; this file only follows it.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="cd-lg">
                  {claim ? (
                    <LedgerRow
                      label={"Paid to " + claim.customer}
                      hint={"Settlement " + claim.settlement.reference + ", cleared " + (claim.settlement.clearedAt ? formatAbsolute(claim.settlement.clearedAt) : "not yet")}
                      value={formatMoney(claim.settlement.amountCents)}
                    />
                  ) : null}
                  <LedgerRow label={"Sought from " + recovery.counterparty.name} hint={recovery.basis} value={formatMoney(recovery.soughtCents)} />
                  {recovery.offerCents ? (
                    <LedgerRow label="Their offer on the table" hint={recovery.status === "recovered" ? "Accepted and settled" : "Rejected as below the surveyed loss"} value={formatMoney(recovery.offerCents)} />
                  ) : null}
                  <LedgerRow className="cd-lg__row--sub" label="Recovered" hint={recovery.recoveredCents ? "Received " + formatAbsolute(recovery.closedAt) : "Nothing received yet"} value={formatMoney(recovery.recoveredCents)} />
                  <LedgerRow
                    className="cd-lg__row--payable"
                    label={<span style={{ fontWeight: "var(--font-weight-medium)" }}>{RECOVERY_FLAGS.isOpen(recovery) ? "Still out" : "Written down"}</span>}
                    hint={RECOVERY_FLAGS.isOpen(recovery)
                      ? "Chasing " + recovery.counterparty.name + " for the balance, " + formatCountdown(recovery.fileByAt, now) + " on the contract clock."
                      : "This file is closed at " + formatPercent(recovery.recoveredCents / recovery.soughtCents) + " of the amount sought."}
                    value={formatMoney(shortfall)}
                  />
                </div>
              </CardPanel>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Correspondence</CardTitle>
                <CardDescription>{formatPlural(recovery.log.length, "entry", "entries")}, newest first.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="cd-log">
                  {recovery.log.slice().sort((a, b) => b.at - a.at).map((entry) => (
                    <div className="cd-log__item" key={entry.at}>
                      <span className="cd-log__who">{entry.who}</span>
                      <span className="cd-log__when" title={formatAbsolute(entry.at)}>{formatWhen(entry.at, now)}</span>
                      <span className="cd-log__text">{entry.text}</span>
                    </div>
                  ))}
                </div>
              </CardPanel>
            </Card>
          </div>

          <div className="cd-col cd-col--tight">
            <Card>
              <CardHeader>
                <CardTitle>The claim behind it</CardTitle>
                <CardDescription>{claim ? claim.id + " · " + labelOf(DECISION_OUTCOMES, claim.decision.outcome) : recovery.claimId}</CardDescription>
              </CardHeader>
              <CardPanel>
                {claim ? (
                  <dl className="cd-defs">
                    <dt>Claimant</dt><dd>{claim.customer}</dd>
                    <dt>Container</dt><dd className="cd-code">{claim.container}</dd>
                    <dt>Voyage</dt><dd>{claim.vessel} {claim.voyage}</dd>
                    <dt>Damage</dt><dd>{claim.incident}</dd>
                    <dt>Claimed</dt><dd className="cd-amount">{formatMoney(claim.claimedCents)}</dd>
                    <dt>Paid</dt><dd className="cd-amount">{formatMoney(claim.settlement.amountCents)}</dd>
                  </dl>
                ) : <p className="cd-note">The paid claim is not on this desk.</p>}
              </CardPanel>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>The counterparty</CardTitle>
                <CardDescription>{labelOf(COUNTERPARTY_KINDS, recovery.counterparty.kind)}</CardDescription>
              </CardHeader>
              <CardPanel>
                <dl className="cd-defs">
                  <dt>Name</dt><dd>{recovery.counterparty.name}</dd>
                  <dt>Contact</dt><dd className="cd-code">{recovery.counterparty.contact}</dd>
                  <dt>Basis</dt><dd>{recovery.basis}</dd>
                  <dt>Opened</dt><dd>{formatAbsolute(recovery.openedAt)}</dd>
                  <dt>Notice served</dt><dd>{recovery.noticeServedAt ? formatAbsolute(recovery.noticeServedAt) : "Not served"}</dd>
                  <dt>Deadline</dt><dd>{formatAbsolute(recovery.fileByAt)}</dd>
                </dl>
              </CardPanel>
            </Card>
          </div>
        </div>
      </div>
    );
  }

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