/* One broadcast — the send report.
   Commit model: INSTANT, the same tiers as the list it came from.
   Data state: one branch, chosen by whether the broadcast has attempted a send.
   A send that has gone out shows its funnel; one that has not shows what it will
   go to and who it is waiting on. There is no third state and no placeholder
   funnel of zeroes.
   Primary display: the funnel. Every row's meter is drawn against the number at
   the top — attempted — so the shape is the funnel, and each row's qualifier
   states its rate against the row above it. */
(() => {
  const { Button, Badge, Alert, AlertTitle, AlertDescription } = window.OriginDesignSystem_7c998b;

  function BroadcastScreen({ data, now, broadcastId, viewer, onNavigate, onBroadcastTransition }) {
    const broadcast = data.broadcasts.find((b) => b.id === broadcastId);
    const audience = audienceById(data.audiences, broadcast.audienceId);
    const template = contentById(data.content, broadcast.contentId);
    const domain = domainById(data.domains, broadcast.domainId);
    const transitions = broadcastTransitions(broadcast, viewer);
    const hasSent = BROADCAST_FLAGS.countsTowardDelivery(broadcast);
    const recipients = broadcastRecipients(broadcast, data.audiences);
    const urgent = BROADCAST_FLAGS.isReviewUrgent(broadcast, now);

    const funnel = hasSent ? [
      { key: "attempted", label: "Attempted", value: broadcast.sends, prev: null, prevLabel: null },
      { key: "delivered", label: "Delivered", value: broadcast.delivered, prev: broadcast.sends, prevLabel: "attempted" },
      { key: "opened", label: "Opened", value: broadcast.opened, prev: broadcast.delivered, prevLabel: "delivered" },
      { key: "clicked", label: "Clicked", value: broadcast.clicked, prev: broadcast.opened, prevLabel: "opened" },
    ] : [];

    return (
      <>
        <PageHeader
          path="/broadcasts/:id"
          params={{ id: broadcast.id }}
          title={broadcast.name}
          crumb={broadcast.name}
          actions={
            <>
              <StatusBadge values={BROADCAST_STATUS} value={broadcast.status} />
              <Transitions transitions={transitions} onRun={(t) => onBroadcastTransition(broadcast, t)} />
            </>
          }
        />

        {broadcast.failureReason ? (
          <div className="md-band">
            <Alert variant="error">
              <Icon name="triangle-alert" size={16} />
              <AlertTitle>The send stopped partway through</AlertTitle>
              <AlertDescription>
                {broadcast.failureReason} Retrying sends only to the {formatCount(broadcast.sends - broadcast.delivered)} who never received it.
              </AlertDescription>
            </Alert>
          </div>
        ) : urgent ? (
          <div className="md-band">
            <Alert variant="warning">
              <Icon name="clock" size={16} />
              <AlertTitle>Waiting on approval — {formatCountdown(broadcast.scheduledAt, now)}</AlertTitle>
              <AlertDescription>
                Nothing sends until somebody approves it. After {formatAbsolute(broadcast.scheduledAt)} the send time has passed and it would have to be rescheduled.
              </AlertDescription>
            </Alert>
          </div>
        ) : null}

        <dl className="md-facts">
          <div>
            <dt>Audience</dt>
            <dd>
              <button type="button" className="md-link" onClick={() => onNavigate("/audiences/" + audience.id)}>{audience.name}</button>
            </dd>
          </div>
          <div>
            <dt>Template</dt>
            <dd>
              <button type="button" className="md-link" onClick={() => onNavigate("/content")}>{template.name}</button>
            </dd>
          </div>
          <div>
            <dt>Subject line</dt>
            <dd>{template.subject ? template.subject : <span className="md-muted">Not written yet</span>}</dd>
          </div>
          <div>
            <dt>Sending domain</dt>
            <dd><button type="button" className="md-link" onClick={() => onNavigate("/deliverability")}>{domain.domain}</button></dd>
          </div>
          <div>
            <dt>Owner</dt>
            <dd>{memberName(data.members, broadcast.ownerId)}</dd>
          </div>
          <div>
            <dt>Submitted by</dt>
            <dd>{broadcast.submittedById ? memberName(data.members, broadcast.submittedById) : <span className="md-muted">Not submitted</span>}</dd>
          </div>
          <div>
            <dt>Approved by</dt>
            <dd>{broadcast.approvedById ? memberName(data.members, broadcast.approvedById) : <span className="md-muted">Not approved</span>}</dd>
          </div>
          <div>
            <dt>{hasSent ? "Sent" : "Sends"}</dt>
            <dd title={broadcastClock(broadcast) ? formatAbsolute(broadcastClock(broadcast)) : ""}>
              {broadcastClock(broadcast) ? formatWhen(broadcastClock(broadcast), now) : "No send time yet"}
            </dd>
          </div>
        </dl>

        {hasSent ? (
          <>
            <Figures items={[
              {
                label: "Delivered",
                value: formatCount(broadcast.delivered),
                qualifier: formatPercent(broadcastDeliveryRate(broadcast)) + " of the " + formatCount(broadcast.sends) + " attempted",
              },
              {
                label: "Open rate",
                value: formatPercent(broadcastOpenRate(broadcast)),
                qualifier: formatCount(broadcast.opened) + " opens across " + formatCount(broadcast.delivered) + " delivered",
              },
              {
                label: "Click rate",
                value: formatPercent(broadcastClickRate(broadcast)),
                qualifier: formatCount(broadcast.clicked) + " clicks across the same " + formatCount(broadcast.delivered),
              },
              {
                label: "Unsubscribes",
                value: formatCount(broadcast.unsubs),
                qualifier: formatPercent(rate(broadcast.unsubs, broadcast.delivered)) + " of what was delivered",
              },
            ]} />

            <section className="md-band md-band--flush">
              <div className="md-band__head">
                <div>
                  <h2 className="md-band__title">Where the send went</h2>
                  <p className="md-band__note">Every bar is drawn against the {formatCount(broadcast.sends)} attempted, so the shape is the funnel. Each rate is against the line above it.</p>
                </div>
              </div>
              <div className="md-funnel">
                {funnel.map((row) => (
                  <div className="md-funnel__row" key={row.key}>
                    <span className="md-funnel__label">{row.label}</span>
                    <span className="md-funnel__value">{formatCount(row.value)}</span>
                    <span className="md-funnel__bar">
                      <Meter
                        label={row.prev === null
                          ? "Everyone in " + audience.name + " when it sent"
                          : formatPercent(rate(row.value, row.prev)) + " of what was " + row.prevLabel}
                        parts={[{ key: row.key, percent: rate(row.value, broadcast.sends) * 100, tone: row.key === "attempted" ? "soft" : undefined }]}
                      />
                    </span>
                  </div>
                ))}
              </div>
            </section>
          </>
        ) : (
          <>
            <Figures three items={[
              {
                label: "Recipients",
                value: formatCount(recipients.count),
                qualifier: "Everyone in " + audience.name + " as it stands now — it is re-evaluated before the send",
              },
              {
                label: broadcast.scheduledAt ? "Sends in" : "Send time",
                value: broadcast.scheduledAt ? formatCountdown(broadcast.scheduledAt, now) : "Not set",
                qualifier: broadcast.scheduledAt ? formatAbsolute(broadcast.scheduledAt) + " · " + MD_WORKSPACE.timezone : "A draft has no send time until it is submitted",
              },
              {
                label: "Waiting on",
                value: broadcast.status === "draft" ? "Its author" : broadcast.status === "in_review" ? "An approver" : "The clock",
                qualifier: broadcast.status === "draft"
                  ? memberName(data.members, broadcast.ownerId) + " has not sent it for review yet"
                  : broadcast.status === "in_review"
                    ? "Submitted by " + memberName(data.members, broadcast.submittedById) + " " + formatWhen(broadcast.submittedAt, now)
                    : "Approved by " + memberName(data.members, broadcast.approvedById),
              },
            ]} />

            <Band title="Nothing has been sent yet" note={"There is no report until it goes out. When it does, it will send to whoever is in " + audience.name + " at that moment — " + formatCount(audience.size) + " people today."}>
              {broadcast.reviewNote ? <p className="md-rule">“{broadcast.reviewNote}” — {memberName(data.members, broadcast.submittedById)}</p> : null}
            </Band>
          </>
        )}
      </>
    );
  }

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