/* Briefs — inbound brand requests, and the triage decision.
   Commit model: INSTANT. The pipeline's tabs and text filter are harmless;
   "Chase the brand" and "Reopen brief" apply immediately and raise an undo
   toast; "Pass on brief" opens a staged dialog, which carries its own model.
   Data state: populated. The no-results branch belongs to the pipeline list
   only, and never renders beside rows.
   Scope: every brief the agency has received. No period filter, so nothing on
   this screen moves when the pipeline tabs change.
   One entry point per action: a brief waiting on triage appears in the deck and
   is deliberately absent from the pipeline below, so "Match creators" and "Pass
   on brief" exist exactly once each per brief.
   Primary display: the triage deck — an inbound brief rendered at the size of
   the decision it asks for — over a hairline pipeline ledger. */
(() => {
  const {
    Button, Input, Badge, Tabs, TabsList, TabsTab, Alert, AlertTitle, AlertDescription,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  /* The pipeline holds everything that is no longer waiting on triage. Each tab
     runs its own predicate. */
  const PIPELINE_TABS = [
    { value: "pitching", label: "Pitched", predicate: (b) => b.status === "pitching" },
    { value: "won", label: "Won", predicate: (b) => b.status === "won" },
    { value: "closed", label: "Closed", predicate: BRIEF_FLAGS.isClosed },
  ];

  const matchesBrief = (brief, query) => {
    const q = query.trim().toLowerCase();
    if (!q) return true;
    return [brief.id, brief.brand, brief.title, labelOf(CATEGORIES, brief.category)].join(" ").toLowerCase().indexOf(q) > -1;
  };

  /* One inbound brief, at the size of the decision. Everything on the right is
     derived from the roster: the floor is the cheapest complete quote anyone on
     the book gives for this exact deliverable list at this usage. */
  function BriefBlock({ brief, data, now, onNavigate, onTransition }) {
    const groups = matchGroups(data.creators, brief, now, data.deals);
    const floor = rosterFloor(data.creators, brief);
    const cheapest = cheapestFitCreator(data.creators, brief);
    const inCategory = data.creators.filter((c) => c.categories.indexOf(brief.category) > -1);
    const belowFloor = floor !== null && brief.budgetCents < floor;
    const transitions = briefTransitions(brief, groups.fits.length);
    const units = briefUnits(brief);

    return (
      <article className="mq-brief">
        <div className="mq-brief__head">
          <Eyebrow>{brief.id} · arrived {formatWhen(brief.receivedAt, now)} · {brief.contact.name}, {brief.contact.role}</Eyebrow>
          <h3 className="mq-brief__brand">{brief.brand}</h3>
          <p className="mq-eyebrow">{brief.title} · {labelOf(CATEGORIES, brief.category)}</p>
          <p className="mq-brief__ask">{brief.ask}</p>
          <dl className="mq-specs">
            <dt>Wants</dt>
            <dd><KindList deliverables={brief.deliverables} /></dd>
            <dt>Usage</dt>
            <dd>{usageOf(brief.usage).label}{usageOf(brief.usage).months ? " · " + usageOf(brief.usage).months + " months · +" + Math.round(usageOf(brief.usage).uplift * 100) + "% on the organic fee" : " · no paid rights"}</dd>
            <dt>Window</dt>
            <dd>{formatAbsolute(brief.liveFromAt).split(",")[0]} – {formatAbsolute(brief.liveToAt).split(",")[0]}</dd>
            <dt>Audience</dt>
            <dd>{formatFollowers(brief.audienceMin)}+ total, they say</dd>
          </dl>
        </div>

        <div className="mq-brief__side">
          <Figure size="xl" label="Budget, one creator" value={formatMoney(brief.budgetCents)} note={formatMoney(Math.round(brief.budgetCents / units)) + " a piece across " + units + " pieces"} />
          <div className="mq-lg">
            <LedgerRow
              label="Cheapest quote on the book"
              hint={floor === null ? "Nobody on the book takes every piece this brief asks for." : cheapest.creator.name + (usageOf(brief.usage).uplift ? ", with the usage uplift" : ", organic — no usage to add")}
              value={floor === null ? <span className="mq-muted">No quote</span> : <span className={belowFloor ? "mq-bad mq-amount" : "mq-amount"}>{formatMoney(floor)}</span>}
            />
            <LedgerRow
              label="On the book in this category"
              value={inCategory.length ? inCategory.length : <span className="mq-bad">0</span>}
              hint={inCategory.length ? inCategory.map((c) => c.name.split(" ")[0]).join(", ") : "No one signed works in " + labelOf(CATEGORIES, brief.category).toLowerCase() + "."}
            />
            <LedgerRow label="Fits every axis" value={groups.fits.length ? groups.fits.length : <span className="mq-bad">0</span>} hint="Audience, category and rate, and able to take it." variant="sub" />
          </div>
          {groups.conflicts.length ? (
            <Alert variant="error">
              <AlertTitle>{groups.conflicts.length === 1 ? groups.conflicts[0].creator.name + " is under exclusivity" : groups.conflicts.length + " creators are under exclusivity"}</AlertTitle>
              <AlertDescription>{groups.conflicts.map((r) => r.creator.name.split(" ")[0] + " to " + r.conflict.brand + " until " + formatAbsolute(r.conflict.until).split(",")[0]).join(" · ")}</AlertDescription>
            </Alert>
          ) : null}
          {groups.fits.length === 0 ? (
            <Alert variant="error">
              <AlertTitle>Nobody on the book fits this brief</AlertTitle>
              <AlertDescription>
                {inCategory.length === 0 ? "No one signed works in " + labelOf(CATEGORIES, brief.category).toLowerCase() + ". " : ""}
                {belowFloor ? "The cheapest complete quote is " + formatMoney(floor) + " against a budget of " + formatMoney(brief.budgetCents) + "." : ""}
              </AlertDescription>
            </Alert>
          ) : null}
        </div>

        <div className="mq-brief__foot">
          <span className="mq-note">
            They want an answer by {formatAbsolute(brief.respondByAt).split(",")[0]} — <span className={BRIEF_FLAGS.daysToRespond(brief, now) <= 3 ? "mq-warn" : ""}>{formatCountdown(brief.respondByAt, now)}</span>.
          </span>
          <div className="mq-actions__row">
            {transitions.slice().sort((a, b) => (a.primary ? 1 : 0) - (b.primary ? 1 : 0)).map((t) => (
              <Button key={t.id} size="sm" variant={t.primary ? "default" : "outline"} onClick={() => onTransition(brief, t)}>{t.label}</Button>
            ))}
          </div>
        </div>
      </article>
    );
  }

  function BriefsScreen({ data, now, onNavigate, onBriefTransition, pushToast }) {
    const [tab, setTab] = React.useState("pitching");
    const [query, setQuery] = React.useState("");
    const briefs = data.briefs;
    const triage = briefsToTriage(briefs);
    const spec = PIPELINE_TABS.find((t) => t.value === tab);
    const inTab = briefs.filter(spec.predicate);
    const rows = inTab.filter((b) => matchesBrief(b, query)).sort((a, b) => b.receivedAt - a.receivedAt);
    const pipeline = briefs.filter((b) => !BRIEF_FLAGS.needsTriage(b));

    return (
      <div className="mq-page">
        <PageHead
          path="/briefs"
          title="Briefs"
          lede={triage.length
            ? triage.length + (triage.length === 1 ? " brief is waiting on you, worth " : " briefs are waiting on you, worth ") + formatMoney(briefValue(triage)) + (triage.length === 1 ? ". " : " between them. ") + "Each one is either worth pitching, wrong for the book, or under what anyone on it charges — the numbers beside it are computed from the roster, not typed."
            : "Nothing is waiting on triage. The " + pipeline.length + " briefs below are with brands, won, or closed."}
          actions={
            <div className="mq-actions__row">
              <Button size="sm" onClick={() => onNavigate("/briefs/new")}>New brief</Button>
              <ExportMenu scope="All briefs" onExport={(format) => pushToast({ title: "Export started", description: "Briefs · " + format + " — we'll email it to " + MARQUE_USER.name.split(" ")[0].toLowerCase() + "@marque.example" })} />
            </div>
          }
        />

        {triage.length ? (
          <section className="mq-section">
            <div className="mq-section__head">
              <h2 className="mq-h2">On your desk<span className="mq-tab-count">{triage.length}</span></h2>
              <p className="mq-note">Oldest first. Answering is the whole job here: pitch it, or say no in words the brand can hear.</p>
            </div>
            <div className="mq-triage">
              {triage.slice().sort((a, b) => a.respondByAt - b.respondByAt).map((brief) => (
                <BriefBlock key={brief.id} brief={brief} data={data} now={now} onNavigate={onNavigate} onTransition={onBriefTransition} />
              ))}
            </div>
          </section>
        ) : null}

        <section className="mq-section">
          <div className="mq-section__head">
            <h2 className="mq-h2">Everything else</h2>
            <p className="mq-note">The {pipeline.length} briefs that are no longer waiting on triage.</p>
          </div>
          <div className="mq-filters">
            <div className="mq-filters__text">
              <Input size="sm" value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Filter briefs" placeholder="Filter by brand, brief or category" startAddon={<Icon name="search" />} />
            </div>
            <Tabs value={tab} onValueChange={setTab}>
              <TabsList variant="underline" size="sm">
                {PIPELINE_TABS.map((t) => (
                  <TabsTab key={t.value} value={t.value} size="sm">
                    {t.label}<span className="mq-tab-count">{briefs.filter(t.predicate).length}</span>
                  </TabsTab>
                ))}
              </TabsList>
            </Tabs>
          </div>

          {rows.length === 0 ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="search-x" size={18} /></EmptyMedia>
                <EmptyTitle>No {spec.label.toLowerCase()} brief matches “{query}”</EmptyTitle>
                <EmptyDescription>{inTab.length} briefs sit under {spec.label.toLowerCase()}. Clear the filter to see them.</EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button onClick={() => setQuery("")}>Clear filter</Button>
              </EmptyContent>
            </Empty>
          ) : (
            <div className="mq-table-wrap">
              <Table className="mq-tbl">
                <TableHeader>
                  <TableRow>
                    <TableHead>Brief</TableHead>
                    <TableHead className="mq-drop-lg">Category</TableHead>
                    <TableHead className="mq-drop-md">Window</TableHead>
                    <TableHead className="mq-num">Budget</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Outcome</TableHead>
                    <TableHead className="mq-actions"><span className="o-sr">Action</span></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.map((brief) => {
                    const deal = dealForBrief(data.deals, brief);
                    const creator = deal ? creatorById(data.creators, deal.creatorId) : null;
                    const recessed = BRIEF_FLAGS.isClosed(brief);
                    const transitions = briefTransitions(brief, 0).filter((t) => t.primary);
                    return (
                      <TableRow key={brief.id} className={recessed ? "mq-row-recessed" : ""}>
                        <TableCell>
                          <span className="mq-who__text">
                            <button type="button" className="mq-link" onClick={() => onNavigate("/briefs/" + brief.id)}>{brief.brand}</button>
                            <span className="mq-who__meta">{brief.id} · {brief.title}</span>
                          </span>
                        </TableCell>
                        <TableCell className="mq-drop-lg mq-muted">{labelOf(CATEGORIES, brief.category)}</TableCell>
                        <TableCell className="mq-drop-md mq-mono mq-muted">{formatAbsolute(brief.liveFromAt).split(",")[0]}</TableCell>
                        <TableCell className="mq-num mq-amount">{formatMoney(brief.budgetCents)}</TableCell>
                        <TableCell><StatusBadge values={BRIEF_STATUS} value={brief.status} /></TableCell>
                        <TableCell>
                          {deal ? (
                            <span className="mq-who__text">
                              <button type="button" className="mq-link" onClick={() => onNavigate("/deals/" + deal.id)}>{creator.name}</button>
                              <span className="mq-who__meta">{formatMoney(deal.feeCents)} · {deal.id}</span>
                            </span>
                          ) : brief.status === "pitching" ? (
                            <span className="mq-row__meta">Pitched {brief.pitched.map((id) => creatorById(data.creators, id).name.split(" ")[0]).join(" and ")} on {formatAbsolute(brief.pitchedAt).split(",")[0]}</span>
                          ) : brief.status === "passed" ? (
                            <span className="mq-row__meta">{labelOf(PASS_REASONS, brief.passReason)}</span>
                          ) : (
                            <span className="mq-row__meta">{brief.lostNote}</span>
                          )}
                        </TableCell>
                        <TableCell className="mq-actions">
                          {transitions.length ? (
                            <Button variant="outline" size="xs" onClick={() => onBriefTransition(brief, transitions[0])}>{transitions[0].label}</Button>
                          ) : null}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
          <div className="mq-foot">
            <span>Showing {rows.length} of {inTab.length} {spec.label.toLowerCase()} briefs{query ? " matching “" + query + "”" : ""} · {briefs.length} received in all</span>
            <span>The brand's name opens the match. Sorted newest first.</span>
          </div>
        </section>
      </div>
    );
  }

  Object.assign(window, { BriefsScreen, PIPELINE_TABS });
})();
