/* Responses — what the customer did with the offer.
   Commit model: INSTANT. Recording a response opens a staged dialog, which
   carries its own commit model; reopening an assessment applies immediately
   with an undo toast; escalating to legal opens a confirm dialog.
   Data state: populated. The no-dispute branch below is a record state, not a
   second data state: the offer ledger is always there. */
(() => {
  const {
    Button, Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, Badge, Separator,
  } = window.OriginDesignSystem_7c998b;

  function DisputedOffer({ claim, now, onNavigate, onResponseTransition }) {
    const gap = RESPONSE_FLAGS.gap(claim);
    const transitions = responseTransitions(claim);
    return (
      <Card className="cd-decide">
        <CardHeader>
          <CardTitle>{claim.customer} has refused our offer</CardTitle>
          <CardDescription>
            <span className="cd-code">{claim.id}</span> · offer sent {formatAbsolute(claim.response.offerSentAt)} · refused {formatAbsolute(claim.response.respondedAt)}
          </CardDescription>
        </CardHeader>
        <CardPanel>
          <div className="cd-lg">
            <LedgerRow label="We offered" hint={labelOf(DECISION_OUTCOMES, claim.decision.outcome) + ", paid " + formatAbsolute(claim.settlement.sentAt)} value={formatMoney(claim.settlement.amountCents)} />
            <LedgerRow label="They demand" hint={"Their claimed figure was " + formatMoney(claim.claimedCents)} value={formatMoney(claim.response.demandCents)} />
            <LedgerRow
              className="cd-lg__row--payable"
              label={<span style={{ fontWeight: "var(--font-weight-medium)" }}>The gap</span>}
              hint={"What is being argued over, on top of the " + formatMoney(claim.settlement.amountCents) + " already paid."}
              value={formatMoney(gap)}
            />
          </div>
          <div className="cd-letter" style={{ marginTop: "var(--space-6)" }}>
            <span className="cd-h3">In their words</span>
            <p className="cd-letter__quote">{claim.response.note}</p>
            <span className="cd-h3">What we told them</span>
            <p className="cd-letter__quote">{claim.decision.justification}</p>
          </div>
        </CardPanel>
        <CardFooter className="cd-form-foot">
          <span className="cd-form-foot__note">Reopening the assessment puts the claim back on your desk with the payment already made; escalating hands the gap to legal.</span>
          {transitions.map((t) => (
            <Button key={t.id} variant={t.primary ? "default" : "outline"} onClick={() => onResponseTransition(claim, t)}>{t.label}</Button>
          ))}
          <Button variant="ghost" onClick={() => onNavigate("/claims/" + claim.id)}>Open the claim<Icon name="arrow-right" /></Button>
        </CardFooter>
      </Card>
    );
  }

  function ResponsesScreen({ data, now, onNavigate, onResponseTransition, pushToast }) {
    const claims = data.claims;
    const offers = offeredClaims(claims).slice().sort((a, b) => b.response.offerSentAt - a.response.offerSentAt);
    const answered = answeredOffers(claims);
    const accepted = offersWith(claims, "accepted");
    const disputed = disputedOffers(claims);
    const awaiting = offersWith(claims, "awaiting_response");

    return (
      <div className="cd-page">
        <PageHead
          path="/responses"
          title="Responses"
          lede={"Every offer this desk has sent, and what the customer did with it. " + answered.length + " of " + offers.length + " have answered."}
          actions={<ExportMenu scope="Offers sent" onExport={(format) => pushToast({ title: "Export started", description: "Offers sent · " + format + " — we'll email it to " + CLAIMS_USER.name.split(" ")[0].toLowerCase() + "@corvenline.example" })} />}
        />

        <div className="cd-bleed">
          <div className="cd-figures">
            <Figure
              xl
              label="Accepted and closed"
              value={formatMoney(sumOf(accepted, (c) => c.settlement.amountCents))}
              note={accepted.length + " of the " + offers.length + " offers sent, " + awaiting.length + " still with the customer"}
            />
            <Figure
              label="In dispute"
              value={formatMoney(sumOf(disputed, (c) => c.settlement.amountCents))}
              note={disputed.length + (disputed.length === 1 ? " offer refused, already paid" : " offers refused, already paid")}
            />
            <Figure
              label="Argued over"
              value={formatMoney(disputedGapTotal(claims))}
              note="The gap between what we offered and what they demand"
            />
          </div>
        </div>

        <div className="cd-split">
          <div className="cd-col">
            {disputed.length ? (
              disputed.map((claim) => <DisputedOffer key={claim.id} claim={claim} now={now} onNavigate={onNavigate} onResponseTransition={onResponseTransition} />)
            ) : (
              <Card className="cd-decide">
                <CardPanel>
                  <Empty>
                    <EmptyHeader>
                      <EmptyMedia variant="icon"><Icon name="handshake" size={18} /></EmptyMedia>
                      <EmptyTitle>No offer is in dispute</EmptyTitle>
                      <EmptyDescription>All {answered.length} answered offers were accepted. {awaiting.length ? awaiting.length + " offers are still with the customer — record their answer from the ledger beside this." : ""}</EmptyDescription>
                    </EmptyHeader>
                  </Empty>
                </CardPanel>
              </Card>
            )}
          </div>

          <div className="cd-col cd-col--tight">
            <Card>
              <CardHeader>
                <CardTitle>Offer ledger</CardTitle>
                <CardDescription>{formatPlural(offers.length, "offer")} sent, newest first.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="cd-rows">
                  {offers.map((claim) => {
                    const transitions = responseTransitions(claim);
                    const record = transitions.find((t) => t.id === "record_response");
                    const recessed = RESPONSE_FLAGS.awaitsCustomer(claim);
                    return (
                      <div className={"cd-row" + (recessed ? " cd-row--recessed" : "")} 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> · sent {formatWhen(claim.response.offerSentAt, now)}</span>
                          {recessed ? <span className="cd-record__meta">Waiting on the customer</span> : null}
                        </div>
                        <div className="cd-row__side">
                          <span className="cd-amount">{formatMoney(claim.settlement.amountCents)}</span>
                          <StatusBadge values={RESPONSE_STATUS} value={claim.response.status} />
                        </div>
                        {record ? (
                          <div className="cd-row__wide">
                            <Button variant="outline" size="xs" onClick={() => onResponseTransition(claim, record)}>{record.label}</Button>
                          </div>
                        ) : null}
                      </div>
                    );
                  })}
                </div>
              </CardPanel>
              <CardFooter className="cd-foot">
                <span>{formatMoney(sumOf(offers, (c) => c.settlement.amountCents))} offered across {formatPlural(offers.length, "claim")}</span>
              </CardFooter>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { ResponsesScreen, DisputedOffer });
})();
