/* Approvals — the review queue, its own screen so the act-ability predicate has
   somewhere to live at full size. Loaded after the broadcasts screens because it
   reads the same transitions. */
(() => {
  const { Button, Badge } = window.OriginDesignSystem_7c998b;

  /* Approvals — the review queue.
     Commit model: INSTANT with an undo toast; approving is consequential and
     reversible, so it is not a dialog.
     Data state: one branch — populated. Three sections, three predicates over
     one array: the act-ability predicate (isApprovableBy), yours (isMine), and
     everything else in review. */
  function ApprovalsScreen({ data, now, viewer, onNavigate, onBroadcastTransition, onBulkApprove }) {
    const inReview = broadcastsInReview(data.broadcasts);
    const yours = broadcastsToReview(data.broadcasts, viewer).slice().sort((a, b) => a.scheduledAt - b.scheduledAt);
    const submitted = inReview.filter((b) => BROADCAST_FLAGS.isMine(b, viewer));
    const others = inReview.filter((b) => yours.indexOf(b) < 0 && submitted.indexOf(b) < 0);
    const urgent = yours.filter((b) => BROADCAST_FLAGS.isReviewUrgent(b, now));
    const reach = yours.reduce((n, b) => n + broadcastRecipients(b, data.audiences).count, 0);

    const Row = ({ broadcast, actions }) => {
      const recipients = broadcastRecipients(broadcast, data.audiences);
      return (
        <div className="md-queue__row" key={broadcast.id}>
          <div className="md-queue__main">
            <button type="button" className="md-link" onClick={() => onNavigate("/broadcasts/" + broadcast.id)}>{broadcast.name}</button>
            <span className="md-footnote">
              {formatCount(recipients.count)} in {audienceName(data.audiences, broadcast.audienceId)} · submitted by {memberName(data.members, broadcast.submittedById)} {formatWhen(broadcast.submittedAt, now)}
            </span>
          </div>
          <div className="md-queue__side">
            <StatusBadge values={BROADCAST_STATUS} value={broadcast.status} />
            <span className={"md-clock" + (BROADCAST_FLAGS.isReviewUrgent(broadcast, now) ? " md-clock--warning" : " md-muted")} title={formatAbsolute(broadcast.scheduledAt)}>
              {formatCountdown(broadcast.scheduledAt, now)}
            </span>
            {actions}
          </div>
        </div>
      );
    };

    return (
      <>
        <PageHeader path="/approvals" title="Approvals" actions={
          yours.length > 1 ? <Button size="sm" onClick={() => onBulkApprove(yours)}>Approve all {yours.length}</Button> : null
        } />

        <Tiles>
          <Tile span="5" tone="hero" title="Waiting on you"
            note="In review, submitted by somebody else, and your role is entitled to approve — the one predicate the sidebar badge counts.">
            <StatRow>
              <StatTile label="On your desk" value={formatCount(yours.length)} tone={yours.length ? "warning" : undefined}
                qualifier={urgent.length ? urgent.length + " of them send within two days" : "None of them send within two days"} />
              <StatTile label="People they reach" value={formatCount(reach)}
                qualifier={"Across " + yours.length + (yours.length === 1 ? " audience" : " audiences") + ", counted as each stands now"} />
            </StatRow>
            {yours.length ? (
              <Gauge percent={(urgent.length / yours.length) * 100} value={urgent.length + " of " + yours.length}
                label="urgent" tone={urgent.length ? "warning" : "success"}
                note="Urgent means less than two days between now and the send time." />
            ) : null}
          </Tile>

          <Tile span="7" title="The queue" note="In the order they send, soonest first.">
            {yours.length === 0 ? (
              <p className="md-empty">Nothing is waiting on you. {submitted.length ? "The " + submitted.length + " you submitted need somebody else." : "Nothing is in review at all."}</p>
            ) : (
              <div className="md-queue">
                {yours.map((broadcast) => (
                  <Row key={broadcast.id} broadcast={broadcast}
                    actions={<Transitions transitions={broadcastTransitions(broadcast, viewer)} onRun={(t) => onBroadcastTransition(broadcast, t)} />} />
                ))}
              </div>
            )}
          </Tile>

          <Tile span="6" tone="muted" title={"You submitted — " + submitted.length}
            note="Yours cannot be approved by you. They are here so you can see who they are waiting on.">
            {submitted.length === 0 ? <p className="md-empty">You have nothing in review.</p> : (
              <div className="md-queue">
                {submitted.map((broadcast) => (
                  <Row key={broadcast.id} broadcast={broadcast}
                    actions={<FaceStack size={24} people={data.members.filter((m) => ROLE_CAN_APPROVE[m.teamRole] && m.id !== viewer.id)} />} />
                ))}
              </div>
            )}
          </Tile>

          <Tile span="6" tone="muted" title={"Waiting on somebody else — " + others.length}
            note="In review, but not yours to approve and not yours to answer for.">
            {others.length === 0 ? <p className="md-empty">Nothing else is in review.</p> : (
              <div className="md-queue">
                {others.map((broadcast) => <Row key={broadcast.id} broadcast={broadcast} actions={null} />)}
              </div>
            )}
          </Tile>
        </Tiles>
      </>
    );
  }

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