/* Team and ownership — who works this desk and whose creators are whose.
   Commit model: INSTANT, and there is deliberately nothing to commit:
   ownership is a field on the creator, so it is changed on the creator's file
   and this screen reads it. A control here would be a second entry point for
   the same fact.
   Data state: populated. Every manager has a book, even if it is an empty one,
   and a manager who owns nobody says so in a sentence.
   Actions derive from the record: a manager with somebody free to pitch is
   offered that creator; the business-affairs seat owns no roster, so it is
   offered nothing and its card says why.
   Primary display: one column stack per manager, each a card with the book
   under it — the only comparison worth making is manager against manager. */
(() => {
  const { Button, Badge, Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter, Separator } = window.OriginDesignSystem_7c998b;

  function ManagerCard({ manager, data, now, onNavigate }) {
    const book = managerBook(data, manager);
    const owns = book.roster.length;
    return (
      <Card>
        <CardHeader>
          <CardTitle>
            <span className="mq-who">
              <Portrait creator={{ name: manager.name, portrait: manager.avatar }} size={36} />
              <span className="mq-who__text">
                <span className="mq-who__name">{manager.name}</span>
                <span className="mq-who__meta">{manager.role} · {manager.desk} · since {formatAbsolute(manager.joinedAt).split(",")[0]}</span>
              </span>
            </span>
          </CardTitle>
          <CardDescription>
            {owns === 0
              ? "Owns no creator. Business affairs sits across the whole book — the paper, the invoices and the payment runs — rather than a roster of its own."
              : owns + " " + (owns === 1 ? "creator" : "creators") + " on their book, " + book.free.length + " free to pitch today, " + formatFollowers(book.reach) + " of audience between them."}
          </CardDescription>
        </CardHeader>
        <CardPanel>
          {owns === 0 ? (
            <div className="mq-lg">
              <LedgerRow label="Invoices on the desk" hint="Every campaign, whoever owns the creator" value={invoiceRows(data.deals).length} />
              <LedgerRow label="Past due" hint={invoicesOverdue(invoiceRows(data.deals), now).length ? invoicesOverdue(invoiceRows(data.deals), now).map((r) => r.deal.brand).join(", ") : "Nothing late"} value={formatMoney(moneyTotal(invoicesOverdue(invoiceRows(data.deals), now)))} variant="net" />
            </div>
          ) : (
            <>
              <div className="mq-lg">
                <LedgerRow label="Fees booked" hint={book.deals.length + " " + (book.deals.length === 1 ? "campaign" : "campaigns") + " across their book"} value={formatMoney(book.feeCents)} />
                <LedgerRow label="Commission on it" hint="At the rate each deal was signed at" value={formatMoney(book.commissionCents)} variant="net" />
              </div>
              <Separator />
              <div className="mq-rows">
                {book.roster.slice().sort((a, b) => reachOf(b) - reachOf(a)).map((creator) => (
                  <div className={"mq-row" + (creator.status === "paused" ? " mq-row--recessed" : "")} key={creator.id}>
                    <div className="mq-row__main">
                      <span className="mq-row__title">
                        <button type="button" className="mq-link" onClick={() => onNavigate("/talent/" + creator.id)}>{creator.name}</button>
                      </span>
                      <span className="mq-row__meta">
                        @{creator.handle} · {formatFollowers(reachOf(creator))} · {creator.categories.map((c) => labelOf(CATEGORIES, c)).join(", ")}
                        {unavailableBecause(creator, data.deals, now) ? " · " + unavailableBecause(creator, data.deals, now).toLowerCase() : ""}
                      </span>
                    </div>
                    <div className="mq-row__side">
                      <StatusBadge values={CREATOR_STATUS} value={creator.status} />
                      <Button variant="ghost" size="xs" onClick={() => onNavigate("/talent/" + creator.id + "/statement")}>Statement</Button>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </CardPanel>
        <CardFooter className="mq-card-footer">
          <span className="mq-note">
            {owns === 0
              ? manager.email
              : book.attention.length
                ? book.attention.length + " " + (book.attention.length === 1 ? "deliverable needs" : "deliverables need") + " somebody on their book this week."
                : "Nothing on their book needs anybody this week."}
          </span>
          {owns > 0 && book.attention.length ? <Button variant="outline" size="sm" onClick={() => onNavigate("/deliverables")}>Open the desk</Button> : null}
        </CardFooter>
      </Card>
    );
  }

  function TeamScreen({ data, now, onNavigate }) {
    const managers = data.managers;
    const withRoster = managers.filter((m) => creatorsForManager(data.creators, m).length > 0);
    const unowned = unownedCreators(data.creators, managers);
    const left = withRoster.filter((m, i) => i % 2 === 0).concat(managers.filter((m) => creatorsForManager(data.creators, m).length === 0));
    const right = withRoster.filter((m, i) => i % 2 === 1);

    return (
      <div className="mq-page">
        <PageHead
          path="/account/team"
          title="Team and ownership"
          lede={managers.length + " people on the desk, " + data.creators.length + " creators signed, " + withRoster.length + " books between them. Ownership is a field on the creator, so it is changed on their file and read here."}
        />

        <div className="mq-split mq-split--even">
          <div className="mq-col">
            {left.map((manager) => <ManagerCard key={manager.id} manager={manager} data={data} now={now} onNavigate={onNavigate} />)}
          </div>
          <div className="mq-col">
            {right.map((manager) => <ManagerCard key={manager.id} manager={manager} data={data} now={now} onNavigate={onNavigate} />)}
            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">Coverage</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <div className="mq-lg">
                  {managers.map((manager) => {
                    const owns = creatorsForManager(data.creators, manager);
                    return (
                      <LedgerRow
                        key={manager.id}
                        label={manager.name}
                        hint={owns.length ? owns.map((c) => c.name.split(" ")[0]).join(", ") : manager.role}
                        value={owns.length ? owns.length + " of " + data.creators.length : <span className="mq-muted">No roster</span>}
                      />
                    );
                  })}
                  <LedgerRow label="Unassigned" hint={unowned.length ? unowned.map((c) => c.name).join(", ") + " — nobody is answering their calls" : "Every creator on the book has a manager"} value={unowned.length ? <span className="mq-bad">{unowned.length}</span> : <span className="mq-muted">None</span>} variant="net" />
                </div>
                <p className="mq-note">A creator with no manager is the one failure this screen exists to catch: it is why the count is stated even when it is nought.</p>
              </div>
            </section>
          </div>
        </div>
      </div>
    );
  }

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