/* Search results — where the ⌘K palette lands when the answer is not one of
   the first few rows.
   Commit model: INSTANT. The field narrows the list as typed; there is nothing
   to save.
   Data state: one branch of three — no query, results, or nothing matched. Never
   two of them on screen.
   Actions derive from the record: every hit opens the record it names, and each
   line says what it matched on, so a reader can see why it is in the list.
   Primary display: grouped rows in one order, entity by entity, with the count
   in each heading counting that group and the footer counting the whole set.
   The palette and this screen run one function — searchDesk() — so the number
   the palette footer promises is the number that appears here. */
(() => {
  const {
    Button, Input, Kbd, Badge,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  /* The footer counts each group, so each group's label has to survive being
     counted to one. Keyed by the group labels searchDesk() returns. */
  const SEARCH_SINGULAR = {
    "Creators": "creator",
    "Brands": "brand",
    "Briefs": "brief",
    "Deals": "deal",
    "Deliverables": "deliverable",
    "Invoices and payouts": "invoice or payout",
  };

  function SearchScreen({ query, data, now, onNavigate, onQuery, palette }) {
    const results = searchDesk(data, query);
    const trimmed = String(query || "").trim();

    return (
      <div className="mq-page mq-page--tight">
        <PageHead
          path="/search"
          title={trimmed ? "Results for “" + trimmed + "”" : "Search the desk"}
          lede={!trimmed
            ? "The whole desk in one field: creators, brands, briefs, deals, deliverables and the money on them. ⌘K opens the same search from anywhere."
            : results.total === 0
              ? "Nothing on the desk matches that."
              : results.total + " " + (results.total === 1 ? "record" : "records") + " across " + results.groups.length + " " + (results.groups.length === 1 ? "kind" : "kinds") + ". Each line says what it matched on."}
        />

        <section className="mq-section">
          <div className="mq-filters">
            <div className="mq-filters__text">
              <Input
                size="sm" value={query || ""} autoFocus
                aria-label="Search the talent desk"
                placeholder="Wren, Tessellate, INV-26-0158, one-pan…"
                startAddon={<Icon name="search" />}
                endAddon={trimmed ? <Button variant="ghost" size="xs" onClick={() => onQuery("")}>Clear</Button> : <Kbd>⌘K</Kbd>}
                onChange={(e) => onQuery(e.target.value)}
              />
            </div>
            <span className="mq-note">Searching names, handles, cities, brands, titles, briefs, revision notes, invoice and payout references.</span>
          </div>

          {!trimmed ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="search" size={18} /></EmptyMedia>
                <EmptyTitle>Type something to search</EmptyTitle>
                <EmptyDescription>
                  {data.creators.length} creators, {data.brands.length} brands, {data.briefs.length} briefs, {data.deals.length} deals and every deliverable and invoice on them.
                </EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button variant="outline" onClick={() => palette.setOpen(true)}>Open the palette instead</Button>
              </EmptyContent>
            </Empty>
          ) : results.total === 0 ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="search-x" size={18} /></EmptyMedia>
                <EmptyTitle>Nothing matches “{trimmed}”</EmptyTitle>
                <EmptyDescription>No creator, brand, brief, deal, deliverable or reference on the desk contains that. A brand we have never worked with will not be here — brands arrive with their first brief.</EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button onClick={() => onQuery("")}>Clear the search</Button>
              </EmptyContent>
            </Empty>
          ) : (
            <div className="mq-col">
              {results.groups.map((group) => (
                <div className="mq-col mq-col--tight" key={group.label}>
                  <div className="mq-section__head">
                    <h2 className="mq-h3">{group.label}<span className="mq-tab-count">{group.items.length}</span></h2>
                  </div>
                  <div className="mq-rows">
                    {group.items.map((item) => (
                      <div className="mq-row" key={group.label + item.id}>
                        <div className="mq-row__main mq-row__wide">
                          <span className="mq-row__title">
                            <button type="button" className="mq-link" onClick={() => onNavigate(item.route)}>{item.title}</button>
                          </span>
                          <span className="mq-row__meta">{item.line}</span>
                        </div>
                        <div className="mq-row__side">
                          <Badge size="sm" variant="secondary">{matchRoute(item.route, MARQUE_ROUTES) ? matchRoute(item.route, MARQUE_ROUTES).label : item.route}</Badge>
                          <Button variant="ghost" size="xs" onClick={() => onNavigate(item.route)}>Open<Icon name="arrow-right" /></Button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
              <div className="mq-foot">
                <span>{results.total} {results.total === 1 ? "record" : "records"} matching “{trimmed}” · {results.groups.map((g) => g.items.length + " " + (g.items.length === 1 ? SEARCH_SINGULAR[g.label] : g.label.toLowerCase())).join(" · ")}</span>
                <span>Ordered by kind, then as each list orders itself</span>
              </div>
            </div>
          )}
        </section>
      </div>
    );
  }

  Object.assign(window, { SearchScreen, SEARCH_SINGULAR });
})();
