/* Deliverable — one post or asset, as a record. The thing a row on the
   deliverables desk was always standing in for.
   Commit model: INSTANT, with the two multi-field transitions opening the
   staged dialog App.jsx owns (record revisions, mark published). Consequential
   moves apply here and raise an undo toast.
   Data state: populated. A deliverable always has a deal, a creator, a kind and
   a due date; the sections that depend on it being live say so in a sentence
   instead of rendering an empty second state.
   Actions derive from the record: the header carries exactly what
   deliverableTransitions() allows at this status, so a scheduled piece is
   offered submission and a published one is offered nothing.
   Primary display: a document — what was asked for, what happened to it, and
   what it did once it was live. */
(() => {
  const { Button, Badge, Separator, MenuItem, Alert, AlertTitle, AlertDescription } = window.OriginDesignSystem_7c998b;

  function HistoryStep({ entry, now }) {
    return (
      <div className="mq-tl__item">
        <span className="mq-tl__when" title={formatAbsolute(entry.at)}>{formatAbsolute(entry.at).split(",")[0]}</span>
        <div className="mq-tl__main">
          <span className="mq-tl__title">{entry.what}</span>
          <span className="mq-row__meta">{entry.who}{entry.note ? " — “" + entry.note + "”" : ""}</span>
        </div>
        <div className="mq-tl__side">
          <span className="mq-mono mq-muted" title={formatAbsolute(entry.at)}>{formatWhen(entry.at, now)}</span>
        </div>
      </div>
    );
  }

  function DeliverableScreen({ row, data, now, onNavigate, onDeliverableTransition, pushToast }) {
    const { item, deal, creator } = row;
    const brief = briefForDeal(data.briefs, deal);
    const brand = brandById(data.brands, deal.brandId);
    const transitions = deliverableTransitions(item);
    const primary = transitions.find((t) => t.primary);
    const rest = transitions.filter((t) => !t.primary);
    const siblings = siblingDeliverables(row, data.creators);
    const history = deliverableHistory(row);
    const live = DELIVERABLE_FLAGS.isLive(item);
    const share = postShareOfCampaign(row);
    const waiting = deliverableWaitingOn(row);
    const rightsEnd = RIGHTS_FLAGS.endsAt(deal);
    const line = brief ? brief.deliverables.find((l) => l.kind === item.kind) : null;

    return (
      <div className="mq-page mq-page--tight">
        <RecordHead
          crumb={<Crumbs path="/deliverables/:id" params={{ id: item.id }} labels={{ "/deliverables/:id": item.title }} />}
          id={item.id + " · " + (item.quantity > 1 ? item.quantity + " × " : "") + labelOf(DELIVERABLE_KINDS, item.kind)}
          status={<StatusBadge values={DELIVERABLE_STATUS} value={item.status} />}
          title={item.title}
          lede={creator.name + " for " + deal.brand + ", on " + deal.title + ". " + (waiting ? "Waiting on " + waiting + "." : live ? "Live since " + formatAbsolute(item.publishedAt).split(",")[0] + "." : "Ours to move.")}
          actions={
            <div className="mq-actions__row">
              {primary ? <Button size="sm" onClick={() => onDeliverableTransition(row, primary)}>{primary.label}</Button> : null}
              {rest.length ? (
                <Floating align="end" width="15rem" label="More actions"
                  trigger={<Button variant="outline" size="sm">More<Icon name="chevron-down" /></Button>}>
                  {(close) => rest.map((t) => <MenuItem key={t.id} onClick={() => { close(); onDeliverableTransition(row, t); }}>{t.label}</MenuItem>)}
                </Floating>
              ) : null}
            </div>
          }
        >
          <div className="mq-stack" style={{ marginTop: "var(--space-2)" }}>
            <Who creator={creator} size={28} onClick={() => onNavigate("/talent/" + creator.id)} />
            <DueClock item={item} now={now} />
          </div>
        </RecordHead>

        {DELIVERABLE_FLAGS.needsRevision(item) ? (
          <Alert variant="warning">
            <AlertTitle>{item.revisionBy} sent it back on {formatAbsolute(item.revisionAt).split(",")[0]}</AlertTitle>
            <AlertDescription>“{item.revisionNote}” — the revised cut is due {formatAbsolute(item.dueAt).split(",")[0]}, {formatCountdown(item.dueAt, now)}.</AlertDescription>
          </Alert>
        ) : null}

        <div className="mq-split">
          <div className="mq-col">
            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">What was asked for</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                {brief ? (
                  <>
                    <p className="mq-lede" style={{ fontSize: "var(--text-base)" }}>{brief.ask}</p>
                    <dl className="mq-specs">
                      <dt>Brief</dt>
                      <dd><button type="button" className="mq-link" onClick={() => onNavigate("/briefs/" + brief.id)}>{brief.id} · {brief.title}</button> — {formatMoney(brief.budgetCents)} for {briefUnits(brief)} pieces</dd>
                      <dt>This piece</dt>
                      <dd>{item.quantity > 1 ? item.quantity + " × " : ""}{labelOf(DELIVERABLE_KINDS, item.kind)}{line ? ", one of the " + line.quantity + " " + labelOf(DELIVERABLE_KINDS, line.kind).toLowerCase() + (line.quantity === 1 ? "" : "s") + " they asked for" : ""}</dd>
                      <dt>Usage</dt>
                      <dd>{usageOf(deal.usage).label}{rightsEnd === null ? " — organic only, so nothing expires" : ", running to " + formatAbsolute(rightsEnd).split(",")[0] + " (" + formatCountdown(rightsEnd, now) + ")"}</dd>
                      <dt>Contact</dt>
                      <dd>{brief.contact.name}, {brief.contact.role.toLowerCase()} at <button type="button" className="mq-link" onClick={() => onNavigate("/brands/" + brand.id)}>{brand.name}</button></dd>
                    </dl>
                  </>
                ) : (
                  <p className="mq-note">This deal has no brief behind it on the desk, so the ask lives on the deal sheet.</p>
                )}
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head">
                <h2 className="mq-h2">What has happened<span className="mq-tab-count">{history.length}</span></h2>
                <p className="mq-note">Read off the dates the record already carries, so nothing here is a story written beside them.</p>
              </div>
              <div className="mq-tl">
                {history.map((entry, i) => <HistoryStep key={entry.what + i} entry={entry} now={now} />)}
              </div>
              <div className="mq-foot">
                <span>{live ? "Live " + formatAbsolute(item.publishedAt).split(",")[0] : "Due " + formatAbsolute(item.dueAt).split(",")[0] + " — " + formatCountdown(item.dueAt, now)}</span>
                <span>{formatCountdown(item.dueAt, now).indexOf("over") > -1 && !DELIVERABLE_FLAGS.isDelivered(item) ? "Still ours to fix" : waiting ? "Waiting on " + waiting : "Nothing outstanding on this piece"}</span>
              </div>
            </section>

            {live ? (
              <section className="mq-section">
                <div className="mq-section__head">
                  <h2 className="mq-h2">What it did</h2>
                  <p className="mq-note">The platform's own numbers, entered when the post went live. They feed the campaign's promise, nothing else.</p>
                </div>
                <div className="mq-sheet mq-sheet--tight">
                  <div className="mq-figures">
                    <Figure label="Reach" value={formatFollowers(item.metrics.reach)} note={share === null ? null : formatPercent(share) + " of the " + formatFollowers(actualReach(deal)) + " this campaign has delivered"} />
                    <Figure label="Engagements" value={formatFollowers(item.metrics.engagements)} note={formatPercent(item.metrics.engagements / item.metrics.reach) + " of the accounts it reached"} />
                    <Figure label="Saves" value={formatFollowers(item.metrics.saves)} note={formatPercent(item.metrics.saves / item.metrics.engagements) + " of its engagements were saves"} />
                  </div>
                  <Separator />
                  <div className="mq-stack">
                    <span className="mq-mono mq-muted">{item.url}</span>
                    <Button variant="ghost" size="xs" onClick={() => onNavigate("/performance/" + deal.id)}>Open the wrap report<Icon name="arrow-right" /></Button>
                  </div>
                </div>
              </section>
            ) : null}
          </div>

          <div className="mq-col">
            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">The deal</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <div className="mq-lg">
                  <LedgerRow label="Fee" hint={deal.id + " · agreed " + formatAbsolute(deal.agreedAt).split(",")[0]} value={formatMoney(deal.feeCents)} />
                  <LedgerRow label={"To " + creator.name.split(" ")[0]} hint={"After " + Math.round(deal.commissionRate * 100) + "% commission"} value={formatMoney(creatorNetOf(deal))} variant="net" />
                </div>
                <div className="mq-stack">
                  <StatusBadge values={CONTRACT_STATUS} value={deal.contract.status} />
                  <StatusBadge values={INVOICE_STATUS} value={deal.invoice.status} />
                  <StatusBadge values={PAYOUT_STATUS} value={deal.payout.status} />
                </div>
                <Button variant="ghost" size="sm" onClick={() => onNavigate("/deals/" + deal.id)}>Open the deal sheet<Icon name="arrow-right" /></Button>
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head">
                <h2 className="mq-h2">The rest of the campaign<span className="mq-tab-count">{siblings.length}</span></h2>
                <p className="mq-note">{publishedOf(deal).length} of {deal.deliverables.length} pieces are live. This one is marked.</p>
              </div>
              <div className="mq-rows">
                {siblings.map((sibling) => {
                  const current = sibling.item.id === item.id;
                  return (
                    <div className={"mq-row" + (DELIVERABLE_FLAGS.isWithBrand(sibling.item) ? " mq-row--recessed" : "")} key={sibling.item.id}>
                      <div className="mq-row__main">
                        <span className="mq-row__title">
                          {current
                            ? <span>{sibling.item.title} <Badge size="sm" variant="secondary">This piece</Badge></span>
                            : <button type="button" className="mq-link" onClick={() => onNavigate("/deliverables/" + sibling.item.id)}>{sibling.item.title}</button>}
                        </span>
                        <span className="mq-row__meta">{labelOf(DELIVERABLE_KINDS, sibling.item.kind)}{deliverableWaitingOn(sibling) ? " · waiting on " + deliverableWaitingOn(sibling) : ""}</span>
                      </div>
                      <div className="mq-row__side">
                        <StatusBadge values={DELIVERABLE_STATUS} value={sibling.item.status} />
                        <DueClock item={sibling.item} now={now} />
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="mq-foot">
                <span>Soonest outstanding {byDue(siblings.filter((s) => !DELIVERABLE_FLAGS.isDelivered(s.item))).length ? formatAbsolute(byDue(siblings.filter((s) => !DELIVERABLE_FLAGS.isDelivered(s.item)))[0].item.dueAt).split(",")[0] : "nothing"}</span>
                <Button variant="ghost" size="xs" onClick={() => onNavigate("/deliverables")}>The whole desk<Icon name="arrow-right" /></Button>
              </div>
            </section>
          </div>
        </div>
      </div>
    );
  }

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