/* Talent — the creator's file. The record behind every row on the roster, every
   name on a deal and every payout in the ledger.
   Commit model: INSTANT. Nothing on this screen commits: it is a document that
   navigates. The transitions a creator's work can take belong to the deal, the
   deliverables desk and the money ledger, so each action keeps exactly one
   entry point in the product.
   Data state: populated. A creator always has an audience, a rate card and an
   availability; the sections whose arrays are empty say so in one sentence
   rather than rendering a second state beside the first.
   Actions derive from the record: a free creator is offered the open briefs the
   fit predicate says they fit, a booked creator is offered the deal that booked
   them, and a paused creator is offered neither — the control is omitted, never
   disabled.
   Primary display: a document read top to bottom. Who they are, what they have
   delivered, what they cost, what we owe them. */
(() => {
  const { Button, Badge, Separator, MenuItem, MenuGroupLabel } = window.OriginDesignSystem_7c998b;

  /* Delivered against promised, as a bar. Drawn only for a campaign every piece
     of which is live — deliveryIndex suppresses the rest, and a half-run
     campaign at 40% of promise has not underdelivered, it is mid-flight. */
  function PromiseMeter({ deal }) {
    const index = deliveryIndex(deal);
    if (index === null) return null;
    return (
      <span className="mq-meter" role="img" aria-label={formatPercent(index) + " of the reach promised"}>
        <span className="mq-meter__fill" data-tone={index >= 1 ? "good" : "warn"} style={{ width: Math.min(100, index * 100).toFixed(1) + "%" }} />
      </span>
    );
  }

  function CampaignRow({ deal, now, onNavigate }) {
    const index = deliveryIndex(deal);
    const state = campaignState(deal);
    const live = publishedOf(deal);
    return (
      <div className="mq-tl__item" data-live={state === "complete" ? "yes" : "no"}>
        <span className="mq-tl__when" title={formatAbsolute(deal.agreedAt)}>{formatAbsolute(deal.agreedAt).split(",")[0]}</span>
        <div className="mq-tl__main">
          <button type="button" className="mq-link mq-tl__title" onClick={() => onNavigate("/deals/" + deal.id)}>{deal.brand} · {deal.title}</button>
          <span className="mq-row__meta">
            {formatMoney(deal.feeCents)} fee · {formatMoney(creatorNetOf(deal))} to them after {Math.round(deal.commissionRate * 100)}% commission · {live.length} of {deal.deliverables.length} pieces live
          </span>
          <PromiseMeter deal={deal} />
        </div>
        <div className="mq-tl__side">
          <StatusBadge values={CONTRACT_STATUS} value={deal.contract.status} />
          {index === null
            ? <span className="mq-mono mq-muted">{state === "not_started" ? "Nothing live" : "In flight"}</span>
            : <span className={"mq-mono " + (index >= 1 ? "mq-good" : "mq-warn")}>{formatPercent(index)} of promise</span>}
        </div>
      </div>
    );
  }

  function PitchMenu({ creator, fits, onNavigate }) {
    return (
      <Floating
        align="end" width="21rem" label="Open briefs this creator fits"
        trigger={<Button size="sm">Pitch to a brief<Icon name="chevron-down" /></Button>}
      >
        {(close) => (
          <>
            <MenuGroupLabel>{fits.length} open {fits.length === 1 ? "brief" : "briefs"} {creator.name.split(" ")[0]} fits</MenuGroupLabel>
            {fits.map((row) => (
              <MenuItem key={row.brief.id} onClick={() => { close(); onNavigate("/briefs/" + row.brief.id); }}>
                {row.brief.brand} · {formatMoney(row.fit.quote.totalCents)} against {formatMoney(row.brief.budgetCents)}
              </MenuItem>
            ))}
          </>
        )}
      </Floating>
    );
  }

  function TalentScreen({ creator, data, now, onNavigate, pushToast }) {
    const deals = data.deals.filter((d) => d.creatorId === creator.id).slice().sort((a, b) => b.agreedAt - a.agreedAt);
    const complete = completeDeals(deals);
    const rows = deals.reduce((all, deal) => all.concat(deal.deliverables.map((item) => ({ item: item, deal: deal, creator: creator }))), []);
    const inFlight = byDue(rows.filter((r) => !DELIVERABLE_FLAGS.isLive(r.item)));
    const attention = deliverablesNeedingAttention(rows, now);
    const payouts = payoutRows(deals, data.creators);
    const owed = payoutsOwed(payouts);
    const banked = payouts.filter((r) => PAYOUT_FLAGS.isSettled(r.payout));
    const card = rateCardOf(creator);
    const usageScopes = USAGE_SCOPES.filter((u) => u.uplift > 0);
    const live = CREATOR_FLAGS.liveExclusivities(creator, now);
    const booking = creator.booking && creator.booking.dealId ? dealById(data.deals, creator.booking.dealId) : null;
    const fits = openBriefs(data.briefs)
      .map((brief) => ({ brief: brief, fit: fitOf(creator, brief, now, data.deals) }))
      .filter((row) => row.fit.fits)
      .sort((a, b) => b.brief.budgetCents - a.brief.budgetCents);
    const blocked = unavailableBecause(creator, data.deals, now);

    return (
      <div className="mq-page mq-page--tight">
        <RecordHead
          crumb={<Crumbs path="/talent/:id" params={{ id: creator.id }} labels={{ "/talent/:id": creator.name }} />}
          id={"@" + creator.handle + " · " + creator.based + " · signed " + formatAbsolute(creator.signedAt).split(",")[0]}
          status={<StatusBadge values={CREATOR_STATUS} value={creator.status} />}
          title={creator.name}
          lede={creator.note}
          media={<Portrait creator={creator} size={88} />}
          actions={
            <div className="mq-actions__row">
              {CREATOR_FLAGS.isPitchable(creator) && fits.length ? <PitchMenu creator={creator} fits={fits} onNavigate={onNavigate} /> : null}
              {booking ? <Button size="sm" variant="outline" onClick={() => onNavigate("/deals/" + booking.id)}>Open the {booking.brand} deal<Icon name="arrow-right" /></Button> : null}
              <Button size="sm" variant="outline" onClick={() => onNavigate("/talent/" + creator.id + "/statement")}>Statement<Icon name="arrow-right" /></Button>
              <ExportMenu scope={creator.name} onExport={(format) => pushToast({ title: "Export started", description: creator.name + " · " + format + " — audience, rate card and campaign history." })} />
            </div>
          }
        >
          <div className="mq-stack" style={{ marginTop: "var(--space-2)" }}>
            {creator.categories.map((c) => <Badge key={c} variant="secondary" size="sm">{labelOf(CATEGORIES, c)}</Badge>)}
            <span className="mq-mono mq-muted">{formatFollowers(reachOf(creator))} audience · {formatPercent(engagementOf(creator))} engaged</span>
          </div>
        </RecordHead>

        <div className="mq-split">
          <div className="mq-col">
            <section className="mq-section">
              <div className="mq-section__head">
                <h2 className="mq-h2">Campaigns<span className="mq-tab-count">{deals.length}</span></h2>
                <p className="mq-note">
                  {deals.length === 0
                    ? "Nothing has been booked through the desk yet."
                    : complete.length
                      ? complete.length + " of " + deals.length + " ran to completion, and those are the only ones measured against what we promised the brand."
                      : "Nothing has finished running yet, so there is no promise to judge — the bars appear when every piece of a campaign is live."}
                </p>
              </div>
              {deals.length === 0 ? (
                <p className="mq-note">{creator.name} has no deal on this desk. {CREATOR_FLAGS.isPitchable(creator) ? (fits.length ? fits.length + " open " + (fits.length === 1 ? "brief fits" : "briefs fit") + " them today." : "No open brief fits them today.") : blocked + "."}</p>
              ) : (
                <>
                  <div className="mq-tl">
                    {deals.map((deal) => <CampaignRow key={deal.id} deal={deal} now={now} onNavigate={onNavigate} />)}
                  </div>
                  <div className="mq-foot">
                    <span>{formatMoney(sumBy(deals, "feeCents"))} of fees across {deals.length} {deals.length === 1 ? "campaign" : "campaigns"} · {formatMoney(sumOf(deals, creatorNetOf))} of it theirs</span>
                    <span>Oldest {formatAbsolute(deals[deals.length - 1].agreedAt).split(",")[0]}, newest {formatAbsolute(deals[0].agreedAt).split(",")[0]}</span>
                  </div>
                </>
              )}
            </section>

            <section className="mq-section">
              <div className="mq-section__head">
                <h2 className="mq-h2">Still to come<span className="mq-tab-count">{inFlight.length}</span></h2>
                <p className="mq-note">
                  {inFlight.length
                    ? attention.length + " of " + inFlight.length + " " + (attention.length === 1 ? "needs" : "need") + " somebody this week. The deliverables desk owns the transitions."
                    : deals.length ? "Nothing outstanding — every piece they owe is live." : "Nothing is booked, so nothing is owed."}
                </p>
              </div>
              {inFlight.length ? (
                <>
                  <div className="mq-tl">
                    {inFlight.map((row) => (
                      <div className="mq-tl__item" key={row.item.id} data-attention={DELIVERABLE_FLAGS.needsAttention(row.item, now) ? "yes" : "no"}>
                        <span className="mq-tl__when" title={formatAbsolute(row.item.dueAt)}>{formatAbsolute(row.item.dueAt).split(",")[0]}</span>
                        <div className="mq-tl__main">
                          <span className="mq-tl__title">{row.item.title}</span>
                          <span className="mq-row__meta">
                            {row.deal.brand} · {row.item.quantity > 1 ? row.item.quantity + " × " : ""}{labelOf(DELIVERABLE_KINDS, row.item.kind)}
                            {deliverableWaitingOn(row) ? " · waiting on " + deliverableWaitingOn(row) : ""}
                          </span>
                        </div>
                        <div className="mq-tl__side">
                          <StatusBadge values={DELIVERABLE_STATUS} value={row.item.status} />
                          <DueClock item={row.item} now={now} />
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="mq-foot">
                    <span>Soonest {formatAbsolute(inFlight[0].item.dueAt).split(",")[0]} — {formatCountdown(inFlight[0].item.dueAt, now)}</span>
                    <Button variant="ghost" size="xs" onClick={() => onNavigate("/deliverables")}>Open the deliverables desk<Icon name="arrow-right" /></Button>
                  </div>
                </>
              ) : null}
            </section>
          </div>

          <div className="mq-col">
            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">Audience</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <PlatformLadder creator={creator} />
                <p className="mq-note">Read from the platform rows, so a follower count changed anywhere moves every figure that mentions it. {labelOf(PLATFORMS, leadPlatformOf(creator).platform)} carries {formatPercent(leadPlatformOf(creator).followers / reachOf(creator))} of the audience.</p>
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">Availability</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <Availability creator={creator} now={now} deals={data.deals} />
                <Separator />
                <div className="mq-col mq-col--tight">
                  <Eyebrow>Exclusivity</Eyebrow>
                  {creator.exclusivities.length === 0 ? (
                    <p className="mq-note">Nothing on file. Every category is open to pitch.</p>
                  ) : creator.exclusivities.map((e) => {
                    const running = live.indexOf(e) > -1;
                    return (
                      <p className="mq-note" key={e.brand}>
                        <strong className={running ? "mq-bad" : "mq-muted"}>{e.brand}</strong> in {labelOf(CATEGORIES, e.category).toLowerCase()}
                        {running ? " until " + formatAbsolute(e.until).split(",")[0] + " — " + formatCountdown(e.until, now) : " expired " + formatAbsolute(e.until).split(",")[0]}.
                        Signed {formatAbsolute(e.signedAt).split(",")[0]}.
                      </p>
                    );
                  })}
                </div>
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">Rate card</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <div className="mq-lg">
                  {card.map((rate) => <LedgerRow key={rate.kind} label={rate.label} value={formatMoney(rate.cents)} />)}
                  <LedgerRow label="Range" hint={card.length + " of " + DELIVERABLE_KINDS.length + " kinds — the rest is work they do not take, so a brief asking for one gets no quote"} value={formatMoney(rateFloorOf(creator)) + " – " + formatMoney(rateCeilOf(creator))} variant="net" />
                </div>
                <p className="mq-note">Organic, before usage: {usageScopes.map((u) => u.label.toLowerCase() + " adds " + Math.round(u.uplift * 100) + "%").join(", ")}.</p>
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">What we owe them</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                {payouts.length === 0 ? (
                  <p className="mq-note">No campaign, so no payout and no commission. A zero here would be a figure about nothing.</p>
                ) : (
                  <>
                    <div className="mq-lg">
                      <LedgerRow label="Paid out" hint={banked.length + " of " + payouts.length + " payouts released"} value={banked.length ? formatMoney(moneyTotal(banked)) : <span className="mq-muted">Nothing yet</span>} />
                      <LedgerRow label="Outstanding" hint={owed.length ? owed.map((r) => r.deal.brand + " — " + statusValue(PAYOUT_STATUS, r.payout.status).label.toLowerCase()).join(", ") : "Nothing waiting"} value={owed.length ? formatMoney(moneyTotal(owed)) : <span className="mq-muted">Nothing</span>} />
                      <LedgerRow label="Commission we banked" hint="Only on invoices the brand has actually paid" value={formatMoney(commissionBanked(invoiceRows(deals)))} variant="net" />
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => onNavigate("/talent/" + creator.id + "/statement")}>Open their statement<Icon name="arrow-right" /></Button>
                  </>
                )}
              </div>
            </section>
          </div>
        </div>
      </div>
    );
  }

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