/* Audiences — who each send is going to.
   Commit model: INSTANT, and this screen commits nothing: it is a read of the
   segment engine. Export is the only action, and it is page-scoped.
   Data state: one branch — populated.
   No period control: nothing here is scoped by time. The one time-bounded number
   on the screen says its window in words.
   Primary display: two column stacks, one block per audience, each carrying the
   rule it counts, its share of the reachable list, what refers to it, and three
   real members — so a materialised count is checkable without a contact
   directory. */
(() => {
  const { Badge, Button } = window.OriginDesignSystem_7c998b;

  function AudienceBlock({ audience, data, workspace, onNavigate }) {
    const share = rate(audience.size, reachableContacts(workspace));
    const uses = audienceUses(audience, data);
    return (
      <div className="md-aud">
        <div className="md-aud__head">
          <div>
            <h3 className="md-aud__name">
              <button type="button" className="md-link" onClick={() => onNavigate("/audiences/" + audience.id)}>{audience.name}</button>
            </h3>
            <span className="md-footnote">{labelOf(AUDIENCE_KINDS, audience.kind)} · evaluated {formatWhen(audience.evaluatedAt, MD_NOW)}</span>
          </div>
          <span className="md-aud__size" title={formatCount(audience.size) + " people"}>{formatCount(audience.size)}</span>
        </div>

        <p className="md-rule">{audience.rule}</p>
        {audience.pendingEvaluation ? (
          <span className="md-footnote">Estimated from the {data.contacts.length}-contact sample. The engine replaces it with the full count within the hour.</span>
        ) : null}

        <Meter
          label={formatPercent(share) + " of the " + formatCount(reachableContacts(workspace)) + " reachable · " + (audience.joined30 ? formatCount(audience.joined30) + " joined it in the last 30 days" : "nobody joined it in the last 30 days")}
          parts={[{ key: "share", percent: share * 100 }]}
        />

        <ul className="md-sample">
          {audience.sample.map((person) => (
            <li key={person.email}>
              <span>{person.name}</span>
              <span className="md-sample__email">{person.email}</span>
              <span className="md-sample__note">{person.note}</span>
            </li>
          ))}
        </ul>
        <span className="md-footnote">Three of {formatCount(audience.size)} shown.</span>

        <div className="md-chips">
          {uses.journeys.length === 0 && uses.broadcasts.length === 0
            ? <span className="md-footnote">Nothing sends to this audience.</span>
            : (
              <>
                {uses.journeys.map((journey) => (
                  <button type="button" key={journey.id} className="md-link" onClick={() => onNavigate("/journeys/" + journey.id)}>
                    <Badge size="sm" variant="secondary">{journey.name}</Badge>
                  </button>
                ))}
                {uses.broadcasts.length ? (
                  <button type="button" className="md-link" onClick={() => onNavigate("/broadcasts/" + uses.broadcasts[0].id)}>
                    <Badge size="sm" variant="secondary">{uses.broadcasts.length} {uses.broadcasts.length === 1 ? "broadcast" : "broadcasts"}</Badge>
                  </button>
                ) : null}
              </>
            )}
        </div>
      </div>
    );
  }

  function AudiencesScreen({ data, workspace, onNavigate, pushToast }) {
    const reachable = reachableContacts(workspace);
    const segments = data.audiences.filter((a) => a.kind === "segment");
    const lists = data.audiences.filter((a) => a.kind === "list");
    const largest = data.audiences.slice().sort((a, b) => b.size - a.size)[0];
    const used = data.audiences.filter((a) => audienceIsUsed(a, data));
    const half = Math.ceil(data.audiences.length / 2);

    return (
      <>
        <PageHeader
          path="/audiences"
          title="Audiences"
          actions={
            <>
              <ExportMenu scope={"All " + data.audiences.length + " audiences"} onExport={(format) => pushToast({ title: "Export started", description: data.audiences.length + " audiences · " + format })} />
              <Button size="sm" onClick={() => onNavigate("/audiences/new")}><Icon name="plus" />New audience</Button>
            </>
          }
        />

        <Figures items={[
          {
            label: "Reachable contacts",
            value: formatCount(reachable),
            qualifier: formatCount(workspace.unsubscribed) + " of the " + formatCount(workspace.contacts) + " in " + workspace.name + " have unsubscribed",
          },
          {
            label: "Audiences",
            value: formatCount(data.audiences.length),
            qualifier: segments.length + " rule-based " + (segments.length === 1 ? "segment" : "segments") + " · " + lists.length + " static " + (lists.length === 1 ? "list" : "lists"),
          },
          {
            label: "Largest audience",
            value: formatCount(largest.size),
            qualifier: largest.name + " · " + formatPercent(rate(largest.size, reachable)) + " of everyone reachable",
          },
          {
            label: "In use",
            value: formatCount(used.length),
            qualifier: data.audiences.length - used.length === 0
              ? "Every one of them is referenced by a live journey or a pending send"
              : (data.audiences.length - used.length) + (data.audiences.length - used.length === 1 ? " is not referenced" : " are not referenced") + " by a live journey or a pending send",
          },
        ]} />

        <section className="md-band md-band--fill">
          <div className="md-band__head" style={{ padding: "var(--space-6) var(--gutter-page) 0" }}>
            <div>
              <h2 className="md-band__title">Every audience, largest first</h2>
              <p className="md-band__note">Audiences overlap on purpose, so these counts do not add up to the workspace. Each one shows the rule it counts and three of the people it matched.</p>
            </div>
          </div>
          <div className="md-cols">
            <div>
              {data.audiences.slice().sort((a, b) => b.size - a.size).slice(0, half).map((audience) => (
                <AudienceBlock key={audience.id} audience={audience} data={data} workspace={workspace} onNavigate={onNavigate} />
              ))}
            </div>
            <div>
              {data.audiences.slice().sort((a, b) => b.size - a.size).slice(half).map((audience) => (
                <AudienceBlock key={audience.id} audience={audience} data={data} workspace={workspace} onNavigate={onNavigate} />
              ))}
            </div>
          </div>
        </section>
      </>
    );
  }

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