/* Deal — the sheet. Negotiated fee, commission, deliverables with their own due
   dates, usage rights and where the paper stands.
   Commit model: INSTANT. Every control on this screen confirms itself: the
   contract transitions apply immediately and raise an undo toast, and
   cancelling the deal is irreversible so it opens a confirm dialog. There is no
   Save button anywhere.
   Data state: populated. A deal always has a fee, a contract and a deliverable
   list; where a figure is not yet meaningful it is suppressed with a word.
   Actions derive from the record: the contract's own status decides which
   transition the header offers, and a deal with anything published cannot be
   cancelled at all — the transition is omitted, not disabled.
   Deliverables are read-only here. The deal sheet is the document; the
   deliverables desk owns their transitions, so each action has exactly one
   entry point per screen. */
(() => {
  const { Button, Badge, Alert, AlertTitle, AlertDescription, AlertAction, Separator } = window.OriginDesignSystem_7c998b;

  /* Three stages, in the order the paper moves. `void` is not one of them — it
     is where a deal leaves the sequence, so it is appended rather than drawn as
     a step the contract is still travelling towards. */
  const CONTRACT_STAGES = CONTRACT_STATUS.filter((s) => s.id !== "void");

  function ContractSteps({ deal, now }) {
    const stamps = { drafted: deal.contract.draftedAt, out_for_signature: deal.contract.sentAt, signed: deal.contract.signedAt };
    const isVoid = CONTRACT_FLAGS.isVoid(deal);
    const current = isVoid ? CONTRACT_STAGES.length : CONTRACT_STAGES.findIndex((s) => s.id === deal.contract.status);
    const terminal = CONTRACT_FLAGS.isSigned(deal);
    return (
      <div className="mq-steps">
        {CONTRACT_STAGES.map((stage, i) => {
          const state = i < current ? "done" : i === current ? (terminal ? "done" : "current") : "ahead";
          const when = stamps[stage.id];
          return (
            <div className="mq-step" key={stage.id} data-state={state}>
              <span className="mq-step__label">{stage.label}</span>
              <span className="mq-step__when">
                {when ? formatAbsolute(when).split(",")[0] : i === current ? "now" : "not yet"}
                {i === current && stage.id === "out_for_signature" ? " · " + CONTRACT_FLAGS.daysOut(deal, now) + " days out" : ""}
              </span>
            </div>
          );
        })}
        {isVoid ? (
          <div className="mq-step" data-state="current">
            <span className="mq-step__label">Void</span>
            <span className="mq-step__when">{formatAbsolute(deal.contract.voidedAt).split(",")[0]}</span>
          </div>
        ) : null}
      </div>
    );
  }

  function DeliverableItem({ row, now }) {
    const item = row.item;
    const attention = DELIVERABLE_FLAGS.needsAttention(item, now);
    return (
      <div className="mq-tl__item" data-live={DELIVERABLE_FLAGS.isLive(item) ? "yes" : "no"} data-attention={attention ? "yes" : "no"}>
        <span className="mq-tl__when" title={formatAbsolute(item.dueAt)}>{formatAbsolute(item.dueAt).split(",")[0]}</span>
        <div className="mq-tl__main">
          <span className="mq-tl__title">{item.title}</span>
          <span className="mq-row__meta">{item.quantity > 1 ? item.quantity + " × " : ""}{labelOf(DELIVERABLE_KINDS, item.kind)}{DELIVERABLE_FLAGS.isLive(item) ? " · live " + formatAbsolute(item.publishedAt).split(",")[0] + " · " + formatFollowers(item.metrics.reach) + " reached" : ""}</span>
          {item.revisionNote ? <span className="mq-quote">“{item.revisionNote}” — {item.revisionBy}, {formatAbsolute(item.revisionAt).split(",")[0]}</span> : null}
        </div>
        <div className="mq-tl__side">
          <StatusBadge values={DELIVERABLE_STATUS} value={item.status} />
          <DueClock item={item} now={now} />
        </div>
      </div>
    );
  }

  function DealScreen({ deal, data, now, onNavigate, onContractTransition, onDealTransition }) {
    const creator = creatorById(data.creators, deal.creatorId);
    const brief = briefForDeal(data.briefs, deal);
    const usage = usageOf(deal.usage);
    const usageEnd = usageEndsAt(deal);
    const published = publishedOf(deal);
    const quote = quoteFor(creator, brief);
    const rows = byDue(deal.deliverables.map((item) => ({ item: item, deal: deal, creator: creator })));
    const attention = rows.filter((r) => DELIVERABLE_FLAGS.needsAttention(r.item, now));
    const transitions = contractTransitions(deal).concat(dealTransitions(deal, published.length));

    return (
      <div className="mq-page mq-page--tight">
        <RecordHead
          crumb={<Crumbs path="/deals/:id" params={{ id: deal.id }} labels={{ "/deals/:id": deal.id }} />}
          id={deal.id + " · agreed " + formatAbsolute(deal.agreedAt).split(",")[0]}
          status={<StatusBadge values={CONTRACT_STATUS} value={deal.contract.status} />}
          title={deal.brand + " × " + creator.name}
          lede={deal.title + ". " + (brief ? "From " + brief.id + ", pitched " + formatAbsolute(brief.pitchedAt).split(",")[0] + "." : "")}
          actions={
            <div className="mq-actions__row">
              {transitions.map((t) => (
                <Button key={t.id} size="sm" variant={t.destructive ? "destructive-outline" : t.primary ? "default" : "outline"}
                  onClick={() => (t.id === "void_deal" ? onDealTransition(deal, t) : onContractTransition(deal, t))}>
                  {t.label}
                </Button>
              ))}
            </div>
          }
        >
          <div className="mq-stack" style={{ marginTop: "var(--space-2)" }}>
            <Who creator={creator} size={32} meta={"@" + creator.handle + " · " + formatFollowers(reachOf(creator)) + " total audience"} />
          </div>
        </RecordHead>

        <ContractSteps deal={deal} now={now} />

        {CONTRACT_FLAGS.awaitsCountersign(deal) ? (
          <Alert variant="warning">
            <AlertTitle>Nothing can start until {deal.brand} countersign</AlertTitle>
            <AlertDescription>
              Sent on {formatAbsolute(deal.contract.sentAt).split(",")[0]}, {CONTRACT_FLAGS.daysOut(deal, now)} days ago. The first deliverable is due {formatAbsolute(rows[0].item.dueAt).split(",")[0]} — {formatCountdown(rows[0].item.dueAt, now)} — and the invoice is held behind the signature.
            </AlertDescription>
          </Alert>
        ) : null}

        <div className="mq-split">
          <div className="mq-col">
            <section className="mq-section">
              <div className="mq-section__head">
                <h2 className="mq-h2">Deliverables<span className="mq-tab-count">{deal.deliverables.length}</span></h2>
                <p className="mq-note">
                  {published.length} live, {attention.length} needing you{attention.length ? " — " + attention.map((r) => r.item.title).join(", ") : ""}. Submitting, approving and publishing happen on the deliverables desk.
                </p>
              </div>
              <div className="mq-tl">
                {rows.map((row) => <DeliverableItem key={row.item.id} row={row} now={now} />)}
              </div>
              <div className="mq-foot">
                <span>{deal.deliverables.length} deliverables · first due {formatAbsolute(rows[0].item.dueAt).split(",")[0]}, last {formatAbsolute(rows[rows.length - 1].item.dueAt).split(",")[0]}</span>
                <Button variant="ghost" size="xs" onClick={() => onNavigate("/deliverables")}>Open the deliverables desk<Icon name="arrow-right" /></Button>
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">Usage rights</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <div className="mq-lg">
                  <LedgerRow label="Scope" value={usage.label} hint={usage.uplift ? "Charged at +" + Math.round(usage.uplift * 100) + "% on the organic fee" : "No paid rights — the brand may not run these as ads"} />
                  <LedgerRow label="Runs from" value={formatAbsolute(deal.usageStartAt).split(",")[0]} hint={usage.months ? "The first post going live starts the clock" : "Nothing to run"} />
                  <LedgerRow
                    label="Expires"
                    value={usageEnd ? formatAbsolute(usageEnd).split(",")[0] : <span className="mq-muted">Not applicable</span>}
                    hint={usageEnd ? formatCountdown(usageEnd, now) + " — after that the brand takes the assets down or renews" : "Organic only, so there is nothing to expire"}
                    variant="sub"
                  />
                </div>
              </div>
            </section>
          </div>

          <div className="mq-col">
            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">The money</h2></div>
              <div className="mq-sheet">
                <div className="mq-lg">
                  <LedgerRow label="Negotiated fee" hint={brief && quote.complete ? "Rate card quoted " + formatMoney(quote.totalCents) + " against a budget of " + formatMoney(brief.budgetCents) : "What the brand pays, agreed in writing"} value={formatMoney(deal.feeCents)} />
                  <LedgerRow label={"Agency commission, " + Math.round(deal.commissionRate * 100) + "%"} hint={deal.commissionRate === AGENCY_POLICY.standardCommissionRate ? "Our standard rate" : "Negotiated below our standard " + Math.round(AGENCY_POLICY.standardCommissionRate * 100) + "%"} value={"− " + formatMoney(commissionOf(deal))} />
                  <LedgerRow label={creator.name + " takes"} value={formatMoney(creatorNetOf(deal))} variant="net" />
                </div>
                <Separator />
                <div className="mq-lg">
                  <LedgerRow
                    label={"Invoice to " + deal.brand}
                    hint={deal.invoice.status === "draft" ? deal.invoice.holdReason : deal.invoice.status === "paid" ? "Banked " + formatAbsolute(deal.invoice.paidAt).split(",")[0] : "Issued " + formatAbsolute(deal.invoice.issuedAt).split(",")[0] + ", net " + AGENCY_POLICY.paymentTermsDays}
                    value={<span className="mq-stack" style={{ justifyContent: "flex-end" }}><StatusBadge values={INVOICE_STATUS} value={deal.invoice.status} /><span className="mq-amount">{formatMoney(invoiceAmountOf(deal))}</span></span>}
                  />
                  <LedgerRow
                    label={"Payout to " + creator.name.split(" ")[0]}
                    hint={deal.payout.status === "awaiting_funds" ? "Held until " + deal.brand + " pay" : deal.payout.status === "paid" ? "Released " + formatAbsolute(deal.payout.paidAt).split(",")[0] + " · " + deal.payout.reference : "Funds are in — release on the next run"}
                    value={<span className="mq-stack" style={{ justifyContent: "flex-end" }}><StatusBadge values={PAYOUT_STATUS} value={deal.payout.status} /><span className="mq-amount">{formatMoney(payoutAmountOf(deal))}</span></span>}
                  />
                </div>
                <Button variant="outline" size="sm" onClick={() => onNavigate("/money")}>Open the money ledger<Icon name="arrow-right" /></Button>
              </div>
            </section>

            <section className="mq-section">
              <div className="mq-section__head"><h2 className="mq-h2">Against the promise</h2></div>
              <div className="mq-sheet mq-sheet--tight">
                <div className="mq-lg">
                  <LedgerRow label="Reach promised" hint={"Agreed in the pitch on " + (brief ? formatAbsolute(brief.pitchedAt).split(",")[0] : formatAbsolute(deal.agreedAt).split(",")[0])} value={formatFollowers(deal.promise.reach)} />
                  <LedgerRow label="Reach delivered" hint={published.length + " of " + deal.deliverables.length + " pieces live"} value={published.length ? formatFollowers(actualReach(deal)) : <span className="mq-muted">Nothing live yet</span>} />
                  <LedgerRow
                    label="Against promise"
                    hint={campaignState(deal) === "complete" ? "Every piece is live, so the campaign can be judged" : "Judged only once every piece is live"}
                    value={deliveryIndex(deal) === null
                      ? <span className="mq-muted">{campaignState(deal) === "not_started" ? "Not yet measurable" : "In flight"}</span>
                      : <span className={deliveryIndex(deal) >= 1 ? "mq-good" : "mq-warn"}>{formatPercent(deliveryIndex(deal))}</span>}
                    variant="sub"
                  />
                </div>
                <Button variant="ghost" size="sm" onClick={() => onNavigate("/performance")}>See the campaign<Icon name="arrow-right" /></Button>
              </div>
            </section>

            {brief ? (
              <section className="mq-section">
                <div className="mq-section__head"><h2 className="mq-h2">Where it came from</h2></div>
                <div className="mq-sheet mq-sheet--tight">
                  <div className="mq-col mq-col--tight">
                    <Eyebrow>{brief.id} · {brief.contact.name}, {brief.contact.role}</Eyebrow>
                    <p className="mq-note">{brief.ask}</p>
                    <div className="mq-stack">
                      <Badge variant="secondary" size="sm">{labelOf(CATEGORIES, brief.category)}</Badge>
                      <span className="mq-mono mq-muted">Budget {formatMoney(brief.budgetCents)}</span>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => onNavigate("/briefs/" + brief.id)}>Open the brief<Icon name="arrow-right" /></Button>
                  </div>
                </div>
              </section>
            ) : null}
          </div>
        </div>
      </div>
    );
  }

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