/* One audience — the rule, the people it matched, and what sends to it.
   Commit model: INSTANT, and this screen commits nothing. Export is the only
   action.
   Data state: one branch — populated.
   This is where an audience count on any other screen drills through to: the
   figure, the predicate that produced it in words, and five of the people it
   matched, with everything that points at it listed underneath. */
(() => {
  const {
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, Button,
  } = window.OriginDesignSystem_7c998b;

  function AudienceScreen({ data, workspace, now, audienceId, onNavigate, pushToast }) {
    const audience = data.audiences.find((a) => a.id === audienceId);
    const reachable = reachableContacts(workspace);
    const share = rate(audience.size, reachable);
    const uses = audienceUses(audience, data);

    return (
      <>
        <PageHeader
          path="/audiences/:id"
          params={{ id: audience.id }}
          title={audience.name}
          crumb={audience.name}
          actions={<ExportMenu scope={formatCount(audience.size) + " people in " + audience.name} onExport={(format) => pushToast({ title: "Export started", description: audience.name + " · " + formatCount(audience.size) + " people · " + format })} />}
        />

        <dl className="md-facts">
          <div>
            <dt>Kind</dt>
            <dd>{labelOf(AUDIENCE_KINDS, audience.kind)}</dd>
          </div>
          <div>
            <dt>Channel</dt>
            <dd>{labelOf(CHANNELS, audience.channel)}</dd>
          </div>
          <div>
            <dt>Last evaluated</dt>
            <dd title={formatAbsolute(audience.evaluatedAt)}>
              {audience.pendingEvaluation ? "Not yet — estimated " + formatWhen(audience.evaluatedAt, now) : formatWhen(audience.evaluatedAt, now)}
            </dd>
          </div>
          <div>
            <dt>Rule</dt>
            <dd>{audience.rule}</dd>
          </div>
        </dl>

        <Figures three items={[
          {
            label: "In this audience",
            value: (audience.pendingEvaluation ? "about " : "") + formatCount(audience.size),
            qualifier: audience.pendingEvaluation
              ? "Estimated from the " + data.contacts.length + "-contact sample. The engine replaces it with the full count within the hour."
              : audience.kind === "segment"
                ? "Everyone matching the rule at " + formatWhen(audience.evaluatedAt, now)
                : "Kept by hand; nobody is added by a rule",
          },
          {
            label: "Share of reachable",
            value: formatPercent(share),
            qualifier: (audience.pendingEvaluation ? "On the estimate above, of " : "Of ") + "the " + formatCount(reachable) + " in " + workspace.name + " who have not unsubscribed",
          },
          {
            label: "Joined in 30 days",
            value: (audience.pendingEvaluation && audience.joined30 ? "about " : "") + formatCount(audience.joined30),
            qualifier: audience.joined30
              ? formatPercent(rate(audience.joined30, audience.size)) + " of the audience is new"
              : "The rule needs 30 days of history, so nobody new can match it yet",
          },
        ]} />

        <section className="md-band md-band--fill">
          <div className="md-pair">
            <div>
              <div className="md-band__head">
                <div>
                  <h2 className="md-band__title">Journeys sending to it</h2>
                  <p className="md-band__note">A journey enrols from this audience continuously.</p>
                </div>
              </div>
              {uses.journeys.length === 0 ? (
                <p className="md-empty">No journey enrols from this audience.</p>
              ) : (
                <div className="md-list">
                  {uses.journeys.map((journey) => (
                    <div className="md-list__row" key={journey.id}>
                      <div className="md-list__main">
                        <button type="button" className="md-link" onClick={() => onNavigate("/journeys/" + journey.id)}>{journey.name}</button>
                        <span className="md-footnote">{journey.trigger} · {formatCount(journeyEnrolled(journey))} enrolled now</span>
                      </div>
                      <div className="md-list__side">
                        <StatusBadge values={JOURNEY_STATUS} value={journey.status} />
                        <span className="md-footnote" title={journey.lastSendAt ? formatAbsolute(journey.lastSendAt) : ""}>Last send {formatWhen(journey.lastSendAt, now).toLowerCase()}</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div>
              <div className="md-band__head">
                <div>
                  <h2 className="md-band__title">Broadcasts sent to it</h2>
                  <p className="md-band__note">Newest first, including the ones still waiting to go out.</p>
                </div>
              </div>
              {uses.broadcasts.length === 0 ? (
                <p className="md-empty">No broadcast has ever been sent to this audience.</p>
              ) : (
                <div className="md-list">
                  {uses.broadcasts.map((broadcast) => {
                    const recipients = broadcastRecipients(broadcast, data.audiences);
                    return (
                      <div className="md-list__row" key={broadcast.id}>
                        <div className="md-list__main">
                          <button type="button" className="md-link" onClick={() => onNavigate("/broadcasts/" + broadcast.id)}>{broadcast.name}</button>
                          <span className="md-footnote">
                            {formatCount(recipients.count)} {recipients.projected ? "in the audience now" : "attempted"}
                            {BROADCAST_FLAGS.countsTowardDelivery(broadcast) ? " · " + formatPercent(broadcastOpenRate(broadcast)) + " opened" : ""}
                          </span>
                        </div>
                        <div className="md-list__side">
                          <StatusBadge values={BROADCAST_STATUS} value={broadcast.status} />
                          <span className="md-footnote" title={broadcastClock(broadcast) ? formatAbsolute(broadcastClock(broadcast)) : ""}>{broadcastClock(broadcast) ? formatWhen(broadcastClock(broadcast), now) : "No send time"}</span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </section>

        <section className="md-band md-band--flush">
          <div className="md-band__head">
            <div>
              <h2 className="md-band__title">Who is in it</h2>
              <p className="md-band__note">A sample, so the count above can be read against real records. The rule is evaluated in full every hour.</p>
            </div>
          </div>
          <div className="md-tablewrap">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Person</TableHead>
                  <TableHead>Email</TableHead>
                  <TableHead>Why they match</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {audience.sample.map((person) => (
                  <TableRow key={person.email}>
                    <TableCell><span className="md-record__name">{person.name}</span></TableCell>
                    <TableCell><span className="md-sample__email">{person.email}</span></TableCell>
                    <TableCell className="md-muted">{person.note}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          <div className="md-tablefoot">
            <span className="md-footnote">Showing {audience.sample.length} of {(audience.pendingEvaluation ? "about " : "") + formatCount(audience.size)} people.</span>
            <span className="md-footnote">The full list lives in Contacts, which is not part of this template.</span>
          </div>
        </section>
      </>
    );
  }

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