/* People — the workspace directory, and one person's page.

   Commit model: INSTANT. Nothing on either screen stages; a role change is not
   made here, it is made on /settings/team, which is staged and says so.
   Data state: one branch — populated. Six people is the fixture, and a workspace
   with nobody in it cannot be signed into.

   Every figure on a profile is read off the records that NAME the person
   (personLoad in metrics.js) rather than stored on them, so the tiles here and
   the lists on /journeys and /broadcasts cannot disagree. */
(() => {
  const { Button, Badge, Avatar, Separator } = window.OriginDesignSystem_7c998b;

  function RoleBadge({ member }) {
    return (
      <Badge size="sm" variant={ROLE_CAN_APPROVE[member.teamRole] ? "success" : "secondary"}>
        {labelOf(TEAM_ROLES, member.teamRole)}
      </Badge>
    );
  }

  function PeopleScreen({ data, now, viewer, onNavigate, onInvite }) {
    const approvers = data.members.filter((m) => ROLE_CAN_APPROVE[m.teamRole]);
    const owedAcross = (data.comments || []).filter((c) => data.members.some((m) => COMMENT_FLAGS.isAwaitingReply(c, m.id, data.comments)));
    const loads = data.members.map((m) => ({ member: m, load: personLoad(data, m.id, now) }));
    const busiest = loads.slice().sort((a, b) => (b.load.journeys.length + b.load.broadcasts.length) - (a.load.journeys.length + a.load.broadcasts.length))[0];

    return (
      <>
        <PageHeader path="/people" title="People" actions={
          <Button size="sm" onClick={onInvite}><Icon name="user-plus" size={14} />Invite teammate</Button>
        } />

        <Tiles>
          <Tile span="7" tone="hero" title="Who is in this workspace"
            note="Six people, and what each of them is answerable for. Roles are changed on Team and roles — this page reads them.">
            <StatRow>
              <StatTile label="People" value={formatCount(data.members.length)}
                qualifier={approvers.length + " can approve a send · " + (data.members.length - approvers.length) + " cannot"} />
              <StatTile label="Notes waiting" value={formatCount(owedAcross.length)} tone={owedAcross.length ? "warning" : undefined}
                qualifier="Notes holding a mention nobody has answered yet, anywhere in the workspace" onClick={() => onNavigate("/inbox")} />
              <StatTile label="Carrying most" value={busiest.member.name.split(" ")[0]}
                qualifier={busiest.load.journeys.length + " journeys and " + busiest.load.broadcasts.length + " broadcasts name " + busiest.member.name.split(" ")[0]} />
            </StatRow>
            <PillMeter label={"Who can approve a send — " + approvers.length + " of " + data.members.length}
              parts={[{ key: "can", percent: (approvers.length / data.members.length) * 100, tone: "success" }]}
              foot={approvers.map((m) => m.name).join(", ") + " — an approval always needs somebody other than the person who submitted." } />
          </Tile>

          <Tile span="5" title="Faces on the work" note="Everybody who has written on a record or been pulled into one this month.">
            <FaceStack people={data.members} max={6} size={40} />
            <KeyValues rows={data.members.slice(0, 4).map((m) => ({
              label: m.name.split(" ")[0] + " · " + m.role,
              value: formatWhen(m.lastActiveAt, now),
            }))} />
            <span className="md-footnote">Last seen, newest first. Two more people are in the grid below.</span>
          </Tile>

          {loads.map(({ member, load }) => (
            <Tile key={member.id} span="4" className="md-persontile">
              <div className="md-person">
                <Avatar size={44} src={member.avatar} alt="" fallback={initialsOf(member.name)} />
                <div className="md-person__text">
                  <button type="button" className="md-link md-person__name" onClick={() => onNavigate("/people/" + member.id)}>{member.name}</button>
                  <span className="md-person__role">{member.role}</span>
                </div>
                <RoleBadge member={member} />
              </div>
              <p className="md-tile__note">{member.focus}</p>
              <div className="md-chips">
                <Chip icon="workflow">{load.liveJourneys.length} live {load.liveJourneys.length === 1 ? "journey" : "journeys"}</Chip>
                <Chip icon="send">{load.broadcasts.length} {load.broadcasts.length === 1 ? "broadcast" : "broadcasts"}</Chip>
                {load.owed.length ? <Chip tone="warning" icon="clock">{load.owed.length} owed</Chip> : null}
                {load.attention.length ? <Chip tone="danger" icon="triangle-alert">{load.attention.length} needing attention</Chip> : null}
              </div>
              <div className="md-tile__foot">
                <span>{member.location} · {formatWhen(member.lastActiveAt, now)}</span>
                <Button variant="ghost" size="sm" onClick={() => onNavigate("/people/" + member.id)}>Open<Icon name="arrow-right" size={14} /></Button>
              </div>
            </Tile>
          ))}
        </Tiles>
      </>
    );
  }

  function PersonScreen({ data, now, memberId, viewer, onNavigate, onBroadcastTransition, onReactToNote }) {
    const member = memberById(data.members, memberId);
    const load = personLoad(data, memberId, now);
    const acts = activityFor(data.activity || [], memberId).slice(0, 8);
    const notes = load.notes.slice().sort((a, b) => b.at - a.at).slice(0, 3);
    const mine = member.id === viewer.id;

    return (
      <>
        <PageHeader path="/people/:id" params={{ id: memberId }} title={member.name} crumb={member.name} actions={
          <>
            {mine ? <Button variant="outline" size="sm" onClick={() => onNavigate("/me/profile")}><Icon name="pencil" size={14} />Edit your profile</Button> : null}
            <Button variant="outline" size="sm" onClick={() => onNavigate("/settings/team")}><Icon name="shield" size={14} />Change role</Button>
          </>
        } />

        <Tiles>
          <Tile span="8" tone="hero">
            <div className="md-hero">
              <Avatar className="md-hero__avatar" size={92} src={member.avatar} alt="" fallback={initialsOf(member.name)} />
              <div className="md-hero__text">
                <span className="md-hero__name">{member.name}{mine ? " (you)" : ""}</span>
                <span className="md-hero__line">{member.role} · {member.focus}</span>
                <div className="md-chips">
                  <RoleBadge member={member} />
                  <Chip icon="map-pin">{member.location}</Chip>
                  <Chip icon="clock">{member.timezone.split("/")[1].replace("_", " ")}</Chip>
                  <Chip icon="calendar">Joined {formatAbsolute(member.joinedAt).split(",")[0]}</Chip>
                  <Chip icon="mail">{member.email}</Chip>
                </div>
              </div>
            </div>
          </Tile>

          <Tile span="4" title="Right now" note={"Last seen " + formatWhen(member.lastActiveAt, now) + "."}>
            <StatRow>
              <StatTile label="Owed replies" value={formatCount(load.owed.length)} tone={load.owed.length ? "warning" : undefined}
                qualifier={load.owed.length ? "Mentions of " + member.name.split(" ")[0] + " with no answer since" : "Nothing is waiting on " + (mine ? "you" : member.name.split(" ")[0])}
                onClick={mine ? () => onNavigate("/inbox") : undefined} />
              <StatTile label="In review" value={formatCount(load.submitted.length)}
                qualifier={load.submitted.length ? "Submitted by " + member.name.split(" ")[0] + ", waiting on somebody else" : "Nothing submitted and unapproved"} />
            </StatRow>
          </Tile>

          <Tile span="12" flush title="What they own" note="Read off the records that name them — the same rows Journeys and Broadcasts show.">
            <div className="md-tiles" style={{ padding: "var(--gutter-page)", paddingBlockStart: 0 }}>
              <Tile span="6" title="Journeys" note={load.journeys.length + " named " + member.name.split(" ")[0] + " as owner"}>
                {load.journeys.length === 0 ? <p className="md-empty">No journey names {member.name.split(" ")[0]} as its owner.</p> : (
                  <div className="md-queue">
                    {load.journeys.map((journey) => (
                      <div className="md-queue__row" key={journey.id}>
                        <div className="md-queue__main">
                          <button type="button" className="md-link" onClick={() => onNavigate("/journeys/" + journey.id)}>{journey.name}</button>
                          <span className="md-footnote">{formatCount(journeyEnrolled(journey))} enrolled · {journey.trigger}</span>
                        </div>
                        <div className="md-queue__side">
                          <StatusBadge values={JOURNEY_STATUS} value={journey.status} />
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </Tile>
              <Tile span="6" title="Broadcasts" note={load.broadcasts.length + " one-off sends, newest first"}>
                {load.broadcasts.length === 0 ? <p className="md-empty">No broadcast names {member.name.split(" ")[0]} as its owner.</p> : (
                  <div className="md-queue">
                    {load.broadcasts.slice().sort((a, b) => (b.scheduledAt || 0) - (a.scheduledAt || 0)).map((broadcast) => (
                      <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">{audienceName(data.audiences, broadcast.audienceId)} · {broadcastClock(broadcast, now)}</span>
                        </div>
                        <div className="md-queue__side">
                          <StatusBadge values={BROADCAST_STATUS} value={broadcast.status} />
                          <Transitions transitions={broadcastTransitions(broadcast, viewer).filter((t) => t.primary)} onRun={(t) => onBroadcastTransition(broadcast, t)} />
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </Tile>
            </div>
          </Tile>

          <Tile span="7" title="What they have written" note={load.notes.length + " notes on journeys, broadcasts and audiences. The three most recent."}>
            {notes.length === 0 ? <p className="md-empty">{member.name.split(" ")[0]} has not written on a record yet.</p> : (
              <div className="md-notes">
                {notes.map((comment) => (
                  <div key={comment.id}>
                    <button type="button" className="md-link md-footnote" onClick={() => onNavigate(recordRoute(comment.record.type, comment.record.id))}>
                      on {recordTitle(data, comment.record.type, comment.record.id)}
                    </button>
                    <Note comment={comment} comments={data.comments} members={data.members} viewer={viewer} now={now} onReact={onReactToNote} />
                  </div>
                ))}
              </div>
            )}
          </Tile>

          <Tile span="5" title="Their activity" note="What this person did, newest first.">
            <div className="md-feed">
              {acts.length === 0 ? <p className="md-empty">Nothing recorded for {member.name.split(" ")[0]}.</p> : acts.map((entry) => {
                const verb = ACTIVITY_VERBS.find((v) => v.value === entry.verb) || { label: entry.verb, icon: "dot" };
                return (
                  <div className="md-feed__row" key={entry.id}>
                    <span className="md-feed__icon"><Icon name={verb.icon} size={14} /></span>
                    <span className="md-feed__text">
                      <span>
                        {verb.label}{" "}
                        {entry.record ? (
                          <button type="button" className="md-link" onClick={() => onNavigate(recordRoute(entry.record.type, entry.record.id))}>
                            {recordTitle(data, entry.record.type, entry.record.id)}
                          </button>
                        ) : null}
                      </span>
                      {entry.note ? <span className="md-feed__note">{entry.note}</span> : null}
                    </span>
                    <span className="md-feed__when" title={formatAbsolute(entry.at)}>{formatWhen(entry.at, now)}</span>
                  </div>
                );
              })}
            </div>
            <div className="md-tile__foot">
              <span>The whole workspace feed is on Activity.</span>
              <Button variant="ghost" size="sm" onClick={() => onNavigate("/activity")}>Open activity<Icon name="arrow-right" size={14} /></Button>
            </div>
          </Tile>
        </Tiles>
      </>
    );
  }

  Object.assign(window, { PeopleScreen, PersonScreen });
})();
