/* Wrap report — one campaign against the promise we made to win it. The
   artifact that gets sent to the brand, and the thing to read before a
   renewal conversation.
   Commit model: INSTANT. Nothing commits: marking a post live belongs to the
   deliverables desk, where the numbers are entered.
   Data state: one branch, chosen by campaignState() — a finished campaign is
   measured, an in-flight one states what is live so far and says plainly that
   it is not measurable yet, and a campaign with nothing live is neither.
   Suppression, not zeroing: deliveryIndex() returns null until every piece is
   live, so this screen prints a word where a percentage would be a lie.
   Primary display: the promise wall for one campaign — the delivered bar
   against the promised wall — over the posts that built it. */
(() => {
  const { Button, Badge, Separator, Alert, AlertTitle, AlertDescription, Table, TableHeader, TableBody, TableFooter, TableRow, TableHead, TableCell } = window.OriginDesignSystem_7c998b;

  const WALL = 72; /* Where the promised line sits on the track, as on the wall. */

  function WrapScreen({ deal, data, now, onNavigate, pushToast }) {
    const creator = creatorById(data.creators, deal.creatorId);
    const brand = brandById(data.brands, deal.brandId);
    const brief = briefForDeal(data.briefs, deal);
    const state = campaignState(deal);
    const index = deliveryIndex(deal);
    const engIndex = engagementIndex(deal);
    const live = publishedOf(deal).slice().sort((a, b) => b.metrics.reach - a.metrics.reach);
    const rows = allDeliverables([deal], data.creators);
    const outstanding = byDue(rows.filter((r) => !DELIVERABLE_FLAGS.isLive(r.item)));
    const reach = actualReach(deal);
    const rightsEnd = RIGHTS_FLAGS.endsAt(deal);
    const expiring = RIGHTS_FLAGS.isExpiring(deal, now);
    const share = Math.min(100, (reach / deal.promise.reach) * WALL);
    const under = index !== null && index < 1;

    return (
      <div className="mq-page mq-page--tight">
        <RecordHead
          crumb={<Crumbs path="/performance/:id" params={{ id: deal.id }} labels={{ "/performance/:id": deal.brand + " · " + deal.title }} />}
          id={deal.id + " · " + formatAbsolute(deal.agreedAt).split(",")[0] + " · " + usageOf(deal.usage).label.toLowerCase()}
          status={<StatusBadge values={CONTRACT_STATUS} value={deal.contract.status} />}
          title={deal.brand + " · " + deal.title}
          lede={index === null
            ? state === "not_started"
              ? "Nothing is live yet, so there is nothing to measure. " + rows.length + " pieces are booked and the first is due " + formatAbsolute(outstanding[0].item.dueAt).split(",")[0] + "."
              : live.length + " of " + rows.length + " pieces are live and have reached " + formatFollowers(reach) + " against a promise of " + formatFollowers(deal.promise.reach) + ". The campaign is not measured until all of it is out — half a campaign is not underdelivery."
            : "Every piece is live. We reached " + formatFollowers(reach) + " against the " + formatFollowers(deal.promise.reach) + " we promised — " + formatPercent(index) + " of it."}
          actions={
            <div className="mq-actions__row">
              <Button size="sm" variant="outline" onClick={() => onNavigate("/brands/" + brand.id)}>{brand.name}<Icon name="arrow-right" /></Button>
              <ExportMenu scope={deal.brand + " wrap report"} onExport={(format) => pushToast({ title: "Export started", description: deal.brand + " · " + format + " — the promise, the delivery and every post behind it." })} />
            </div>
          }
        >
          <div className="mq-stack" style={{ marginTop: "var(--space-2)" }}>
            <Who creator={creator} size={28} onClick={() => onNavigate("/talent/" + creator.id)} />
            {brief ? <Badge size="sm" variant="secondary">{labelOf(CATEGORIES, brief.category)}</Badge> : null}
            <span className="mq-mono mq-muted">{formatMoney(deal.feeCents)} fee</span>
          </div>
        </RecordHead>

        {expiring ? (
          <Alert variant="warning">
            <AlertTitle>{brand.name}'s usage rights end on {formatAbsolute(rightsEnd).split(",")[0]}</AlertTitle>
            <AlertDescription>
              {usageOf(deal.usage).label} for {usageOf(deal.usage).months} months from {formatAbsolute(deal.usageStartAt).split(",")[0]} — {formatCountdown(rightsEnd, now)}. Renew the window with them or the assets have to come down, and a renewal is priced at {Math.round(usageOf(deal.usage).uplift * 100)}% on top of the organic fee.
            </AlertDescription>
          </Alert>
        ) : null}

        <section className="mq-section">
          <div className="mq-section__head">
            <h2 className="mq-h2">Against the promise</h2>
            <p className="mq-note">The promise is what we told {brand.name} in the pitch on {brief && brief.pitchedAt ? formatAbsolute(brief.pitchedAt).split(",")[0] : formatAbsolute(deal.agreedAt).split(",")[0]}. The bar is what the live posts have actually done.</p>
          </div>
          <div className="mq-prow">
            <div className="mq-who">
              <Portrait creator={creator} size={40} />
              <span className="mq-who__text">
                <span className="mq-who__name">{formatFollowers(reach)} reached</span>
                <span className="mq-who__meta">{live.length} of {rows.length} pieces live</span>
              </span>
            </div>
            <div className="mq-prow__track">
              <div className="mq-ptrack">
                <span className="mq-ptrack__fill" data-under={under ? "yes" : "no"} data-flight={state === "in_flight" ? "yes" : "no"} style={{ width: share.toFixed(1) + "%" }} />
                <span className="mq-ptrack__wall" style={{ insetInlineStart: WALL + "%" }} />
                <span className="mq-ptrack__walllabel" style={{ insetInlineStart: WALL + "%" }}>promised {formatFollowers(deal.promise.reach)}</span>
              </div>
            </div>
            <div>
              <div className={"mq-pindex" + (index === null ? " mq-muted" : under ? " mq-warn" : " mq-good")} style={index === null ? { fontSize: "var(--text-sm)" } : null}>
                {index === null ? (state === "in_flight" ? "In flight" : "Not yet live") : formatPercent(index)}
              </div>
              <div className="mq-figure__note" style={{ textAlign: "right" }}>{index === null ? "not measurable yet" : "of the reach promised"}</div>
            </div>
          </div>
          <div className="mq-figures">
            <Figure label="Engagement rate" value={actualEngagementRate(deal) === null ? "—" : formatPercent(actualEngagementRate(deal))} note={engIndex === null ? "Promised " + formatPercent(deal.promise.engagementRate) + " — measured once every piece is live" : formatPercent(engIndex) + " of the " + formatPercent(deal.promise.engagementRate) + " promised"} />
            <Figure label="Engagements" value={formatFollowers(actualEngagements(deal))} note={"Across " + live.length + " live " + (live.length === 1 ? "piece" : "pieces")} />
            <Figure label="Saves" value={formatFollowers(actualSaves(deal))} note={actualEngagements(deal) ? formatPercent(actualSaves(deal) / actualEngagements(deal)) + " of engagements — the number that predicts a renewal" : "Nothing live yet"} />
            <Figure label="Cost per thousand reached" value={reach ? formatMoney(Math.round(deal.feeCents / (reach / 1000))) : "—"} note={reach ? "On the " + formatMoney(deal.feeCents) + " fee, at the reach delivered so far" : "No reach yet, so no cost to divide"} />
          </div>
        </section>

        <section className="mq-section">
          <div className="mq-section__head">
            <h2 className="mq-h2">The posts<span className="mq-tab-count">{live.length}</span></h2>
            <p className="mq-note">{live.length ? "Ranked by reach. Every figure is the platform's own, entered when the post went live." : "Nothing is live, so there is nothing to rank."}</p>
          </div>
          {live.length ? (
            <div className="mq-table-wrap">
              <Table className="mq-tbl">
                <TableHeader>
                  <TableRow>
                    <TableHead>Post</TableHead>
                    <TableHead className="mq-drop-lg">Live</TableHead>
                    <TableHead className="mq-num">Reach</TableHead>
                    <TableHead className="mq-num">Engagements</TableHead>
                    <TableHead className="mq-num mq-drop-md">Saves</TableHead>
                    <TableHead className="mq-num">Share of reach</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {live.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell>
                        <span className="mq-cellstack">
                          <button type="button" className="mq-link" onClick={() => onNavigate("/deliverables/" + item.id)}>{item.title}</button>
                          <span className="mq-row__meta">{labelOf(DELIVERABLE_KINDS, item.kind)} · {item.url}</span>
                        </span>
                      </TableCell>
                      <TableCell className="mq-drop-lg mq-muted"><span className="mq-mono" title={formatAbsolute(item.publishedAt)}>{formatAbsolute(item.publishedAt).split(",")[0]}</span></TableCell>
                      <TableCell className="mq-num">{formatFollowers(item.metrics.reach)}</TableCell>
                      <TableCell className="mq-num">{formatFollowers(item.metrics.engagements)}</TableCell>
                      <TableCell className="mq-num mq-drop-md mq-muted">{formatFollowers(item.metrics.saves)}</TableCell>
                      <TableCell className="mq-num">{formatPercent(item.metrics.reach / reach)}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
                <TableFooter>
                  <TableRow>
                    <TableCell>{live.length} live of {rows.length} booked</TableCell>
                    <TableCell className="mq-drop-lg" />
                    <TableCell className="mq-num">{formatFollowers(reach)}</TableCell>
                    <TableCell className="mq-num">{formatFollowers(actualEngagements(deal))}</TableCell>
                    <TableCell className="mq-num mq-drop-md">{formatFollowers(actualSaves(deal))}</TableCell>
                    <TableCell className="mq-num">100%</TableCell>
                  </TableRow>
                </TableFooter>
              </Table>
            </div>
          ) : null}
          {outstanding.length ? (
            <div className="mq-foot">
              <span>{outstanding.length} {outstanding.length === 1 ? "piece is" : "pieces are"} still to come — soonest {formatAbsolute(outstanding[0].item.dueAt).split(",")[0]}, {formatCountdown(outstanding[0].item.dueAt, now)}{deliverableWaitingOn(outstanding[0]) ? ", waiting on " + deliverableWaitingOn(outstanding[0]) : ""}</span>
              <Button variant="ghost" size="xs" onClick={() => onNavigate("/deliverables/" + outstanding[0].item.id)}>Open the next piece<Icon name="arrow-right" /></Button>
            </div>
          ) : (
            <div className="mq-foot">
              <span>Every booked piece is live, which is why this campaign can be measured at all.</span>
              <Button variant="ghost" size="xs" onClick={() => onNavigate("/performance")}>The whole promise wall<Icon name="arrow-right" /></Button>
            </div>
          )}
        </section>

        <section className="mq-section">
          <div className="mq-section__head"><h2 className="mq-h2">What to say at the renewal</h2></div>
          <div className="mq-sheet mq-sheet--tight">
            <p className="mq-lede" style={{ fontSize: "var(--text-base)" }}>
              {index === null
                ? "Nothing yet. The conversation is worth having once every piece is out — until then any number quoted at " + brand.name + " is a number we would have to revise."
                : under
                  ? "We came in at " + formatPercent(index) + " of the reach we promised, " + formatFollowers(deal.promise.reach - reach) + " short. Lead with the saves — " + formatPercent(actualSaves(deal) / actualEngagements(deal)) + " of engagements — and go into the next brief with a promise built on what " + creator.name.split(" ")[0] + " actually delivered here rather than on their follower count."
                  : "We came in at " + formatPercent(index) + " of promise, " + formatFollowers(reach - deal.promise.reach) + " over. That is the number to open with, and it is the argument for holding the rate on the next brief from them."}
            </p>
            <Separator />
            <dl className="mq-specs">
              <dt>Promised</dt>
              <dd>{formatFollowers(deal.promise.reach)} reach at {formatPercent(deal.promise.engagementRate)} engagement</dd>
              <dt>Delivered</dt>
              <dd>{formatFollowers(reach)} reach{actualEngagementRate(deal) === null ? "" : " at " + formatPercent(actualEngagementRate(deal)) + " engagement"}{index === null ? " so far" : ""}</dd>
              <dt>Rights</dt>
              <dd>{rightsEnd === null ? "Organic only — nothing to renew and nothing to take down." : usageOf(deal.usage).label + " to " + formatAbsolute(rightsEnd).split(",")[0] + " (" + formatCountdown(rightsEnd, now) + ")"}</dd>
              <dt>Their record</dt>
              <dd><button type="button" className="mq-link" onClick={() => onNavigate("/brands/" + brand.id)}>{brand.name}</button> — {brandDaysToPay(data.deals, brand) === null ? "no settled invoice yet" : brandDaysToPay(data.deals, brand).days + " days to pay on average"}</dd>
            </dl>
          </div>
        </section>
      </div>
    );
  }

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