Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

29.8 KB
Raw Blame
/**
 * The ticket board: five columns in lifecycle order (shaping in ticket-board.ts), each with
 * its colour bar and count, a card per ticket — title, priority, due date (danger once
 * passed), the blocked badge, a muted line naming its parent, and its owner — a search box
 * and a blocked-only switch, moving a card between columns by dragging it, which
 * confirms the move (a move into rejected asks for a one-line reason) before posting it, the
 * create form, and the tickets and files the server could not accept.
 * The whole card is one button — the board's one exception to the company pages' rule against
 * whole-area click targets, and it holds no control of its own. A click anywhere on it (Enter
 * and Space too) opens the detail dialog in place (the shell's one host renders it, so the
 * board stays where it is). Dragging it moves it: a mouse or pen press that travels a few pixels
 * lifts the card, which follows the pointer and, released over another column, asks to move
 * there. A finger has to hold the card still for a moment before it lifts, so a finger that moves
 * scrolls the page as usual (ticket-press.ts, ticket-drag.ts). The dialog's move control is the
 * way to move a ticket without dragging.
 * The priority rides on the title's line, one size under it. What a card deliberately does
 * not carry is the session count, the cost and any live session status — those are the
 * dialog's, and a ticket is not the place to watch a session run.
 * The board is always on screen: a skeleton of it until the first fetch, the empty columns
 * as drop zones — with a one-line note above them while the organization has no tickets at
 * all, dismissible and repeated in the page's "?" — the board plus an error strip when a
 * refetch fails.
 * `?column=` / `?blocked=1` deep links arrive from the overview, and `?ticket=` is this
 * page's own: it opens the dialog on arrival and follows it while it is open, so a ticket
 * being read can be linked to and survives a reload. No other page writes it — the dialog is
 * shell state, not a route.
 */
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useLocation, useSearchParams } from "react-router";
import type {
  OrgChartResponse,
  OrgTicketItem,
  OrgTicketPriority,
  OrgTicketStatus,
  OrgTicketsResponse,
} from "@adelie/server/api";
import {
  Button,
  Count,
  FieldLabel,
  GlyphIcon,
  ICONS,
  ICON_SIZE,
  Input,
  Modal,
  Notice,
  NoticeStrip,
  SearchInput,
  Segmented,
  Select,
  Skeleton,
  Switch,
  Textarea,
  toastSuccess,
} from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
import { toneDot, toneInk } from "../../lib/tone";
import { useAuth } from "../../state/auth";
import { useCompany } from "../../state/company";
import { OrgPage, useOrg } from "./org-layout";
import {
  BlockedBadge,
  INVALID_ICON,
  PrincipalChip,
  PriorityBadge,
  TitleButton,
  principalLabel,
} from "./shared";
import {
  TICKET_COLUMNS,
  allTickets,
  boardColumns,
  canMove,
  invalidTickets,
  isBlocked,
  isOverdue,
  isTicketSlug,
  isTicketStatus,
  moveNeedsReason,
} from "./ticket-board";
import { MoveTicketConfirm } from "./ticket-dialog";
import { dismissHint, hintKey, isHintDismissed } from "./page-hints";
import { agentPrincipal, splitPrincipalList } from "./principals";
import { dayKey } from "./calendar-geom";
import { TICKET_COLUMN_ATTR, useTicketBoardDrag } from "./ticket-drag";

const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];

/**
 * The colour bar atop each column. Proposed is neutral, in-progress takes the accent (it is
 * the column being worked, not a judgement), review waits on a person (attention), done is
 * finished well (success), rejected is danger.
 */
const COLUMN_BAR: Record<OrgTicketStatus, string> = {
  proposed: "bg-gray-300 dark:bg-gray-600",
  in_progress: "bg-accent",
  review: toneDot.attention,
  done: toneDot.success,
  rejected: toneDot.danger,
};

const columnClass =
  "flex min-h-[26rem] flex-col rounded-md border border-gray-200 bg-gray-50/60 transition-colors duration-150 dark:border-gray-800 dark:bg-gray-900/40";

export function TicketsPage() {
  const { projectId, orgId, org } = useOrg();
  const company = useCompany();
  const { user } = useAuth();
  const [params, setParams] = useSearchParams();
  const location = useLocation();
  useDocumentTitle(org ? `${org.name} · ${S.nav.org.tickets}` : S.nav.org.tickets);
  const [board, setBoard] = useState<OrgTicketsResponse | null>(null);
  const [chart, setChart] = useState<OrgChartResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [blockedOnly, setBlockedOnly] = useState(params.get("blocked") === "1");
  const [query, setQuery] = useState("");
  const [move, setMove] = useState<{ ticket: OrgTicketItem; to: OrgTicketStatus } | null>(null);
  /** The server's own words for a move this board asked for and had refused, drawn in that card. */
  const [moveRefusal, setMoveRefusal] = useState<string | null>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const highlightColumn = params.get("column");
  // The empty-board note goes away for good once read; the page's "?" carries the same
  // sentence. The key holds the organization, so switching to another one — which does not
  // unmount this page — re-reads the dismissal instead of carrying the last answer over.
  const emptyHintKey = hintKey(user?.userId ?? null, projectId, orgId, "tickets");
  const [hintDismissed, setHintDismissed] = useState(() => isHintDismissed(emptyHintKey));
  useEffect(() => {
    setHintDismissed(isHintDismissed(emptyHintKey));
  }, [emptyHintKey]);

  const load = useCallback(async () => {
    try {
      const [b, c] = await Promise.all([
        api.listOrgTickets(projectId, orgId),
        api.getOrgChart(projectId, orgId),
      ]);
      setBoard(b);
      setChart(c);
      setError(null);
    } catch (e) {
      setError(apiErrorText(e));
    }
  }, [projectId, orgId]);
  const { tickets: ticketsVersion, runs } = company.versions;
  useEffect(() => {
    void load();
  }, [load, ticketsVersion, runs]);

  const employees = chart?.employees ?? [];
  const names = new Map(employees.map((e) => [e.agentId, e.name]));
  const titles = new Map(
    (board === null ? [] : allTickets(board)).map((t) => [t.ticketId, t.title]),
  );
  const todayKey = dayKey(Date.now());

  const setQueryParams = (patch: Record<string, string | null>) => {
    const next = new URLSearchParams(params);
    for (const [k, v] of Object.entries(patch)) {
      if (v === null) next.delete(k);
      else next.set(k, v);
    }
    setParams(next, { replace: true });
  };
  const openTicket = (ticketId: string) => company.openTicket(projectId, orgId, ticketId);
  const drag = useTicketBoardDrag({
    onOpen: (ticket) => openTicket(ticket.ticketId),
    onDrop: (ticket, to) => {
      // A new question, not the last one: the previous refusal is not its answer.
      setMoveRefusal(null);
      setMove({ ticket, to });
    },
  });
  const { lifted, dropOver } = drag;

  // `?ticket=` and the open dialog, kept in step in both directions: the query opens the
  // dialog on arrival (a deep link, a reload), and the dialog writes itself back into the
  // query as it moves and clears it when it closes. One effect rather than two, and one ref
  // holding the value last read or written — two effects writing to each other would chase
  // one round trip behind and reopen a ticket the reader had just left.
  const urlTicket = params.get("ticket");
  const openDialog = company.ticketDialog;
  const dialogTicket =
    openDialog !== null && openDialog.projectId === projectId && openDialog.orgId === orgId
      ? openDialog.ticketId
      : null;
  const syncedTicket = useRef<string | null>(null);
  const { openTicket: openTicketInShell } = company;
  const routedPath = location.pathname;
  useEffect(() => {
    // The browser has already left this page: a click that closes the dialog and navigates
    // (opening a ticket session) is rendered first with the dialog closed and this page still
    // mounted, since the router commits its new location in a transition. Writing the query now
    // would resolve against this page's stale location and replace the new history entry with
    // the board — the navigation would silently land back here.
    if (window.location.pathname !== routedPath) return;
    if (urlTicket !== syncedTicket.current) {
      syncedTicket.current = urlTicket;
      if (urlTicket !== null) {
        openTicketInShell(projectId, orgId, urlTicket);
        return;
      }
    }
    if (dialogTicket === urlTicket) return;
    syncedTicket.current = dialogTicket;
    setParams(
      (prev) => {
        const next = new URLSearchParams(prev);
        if (dialogTicket === null) next.delete("ticket");
        else next.set("ticket", dialogTicket);
        return next;
      },
      { replace: true },
    );
  }, [urlTicket, dialogTicket, projectId, orgId, openTicketInShell, setParams, routedPath]);

  const confirmMove = async (reason: string) => {
    if (move === null) return;
    setBusy(true);
    try {
      await api.moveOrgTicket(projectId, orgId, move.ticket.ticketId, {
        status: move.to,
        ...(moveNeedsReason(move.to) ? { reason: reason.trim() } : {}),
      });
      toastSuccess(S.company.tickets.moved);
      // The card goes with its own move landing, never before: a refusal has to stay readable
      // next to the button that retries it.
      setMove(null);
      setMoveRefusal(null);
      // One signal for a ticket written here: this board, the open dialog and the
      // organization summaries all refetch off it.
      company.ticketsChanged();
    } catch (e) {
      setMoveRefusal(apiErrorText(e));
    } finally {
      setBusy(false);
    }
  };

  /** A card's face: the title with its priority first, then what decides its urgency, then where it hangs and who holds it. */
  const cardBody = (t: OrgTicketItem) => {
    const overdue = isOverdue(t.due, todayKey) && t.status !== "done" && t.status !== "rejected";
    return (
      <>
        <span className="flex items-start gap-1.5">
          <span className="line-clamp-2 min-w-0 flex-1 text-sm font-medium leading-snug text-gray-900 dark:text-gray-100">
            {t.title}
          </span>
          {/* The priority reads with the title and shares its line, a size under it; the line
              below carries what is time-bound — the due date and the blocked mark. */}
          <span className="mt-px shrink-0">
            <PriorityBadge priority={t.priority} />
          </span>
          {t.invalid !== undefined && (
            <span className={`mt-0.5 shrink-0 ${toneInk.danger}`} data-tooltip={t.invalid}>
              <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />
              <span className="sr-only">{S.company.tickets.invalid}</span>
            </span>
          )}
        </span>
        {/* The time-bound line, drawn only when there is something on it: the priority has
            moved up to the title and an empty row would leave a gap under it. */}
        {(t.due !== undefined || isBlocked(t)) && (
          <span className="mt-2 flex flex-wrap items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
            {t.due !== undefined && (
              <span
                className={`inline-flex items-center gap-1 font-mono tabular-nums ${overdue ? toneInk.danger : ""}`}
                data-tooltip={
                  overdue ? `${S.company.tickets.overdue} · ${t.due}` : S.company.tickets.due
                }
                data-tooltip-extra={overdue}
              >
                <GlyphIcon d={ICONS.clockCompact} size={ICON_SIZE.inlineGlyph} />
                {t.due}
                {overdue && <span className="sr-only">{S.company.tickets.overdue}</span>}
              </span>
            )}
            {isBlocked(t) && (
              <span className="ml-auto">
                <BlockedBadge
                  reason={t.blocked ?? ""}
                  {...(t.blockedBy !== undefined ? { by: t.blockedBy } : {})}
                />
              </span>
            )}
          </span>
        )}
        {t.parent !== undefined && (
          <span
            className="mt-2 block truncate text-xs text-gray-400 dark:text-gray-500"
            data-tooltip={t.parent}
            data-tooltip-content="text"
          >
            {S.company.tickets.parentLine(titles.get(t.parent) ?? t.parent)}
          </span>
        )}
        <span className="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
          <span
            className="flex min-w-0 text-gray-700 dark:text-gray-200"
            data-tooltip={`${S.company.tickets.owner} ${principalLabel(t.owner, names)}`}
          >
            <PrincipalChip principal={t.owner} names={names} size={ICON_SIZE.rowLead} />
          </span>
        </span>
      </>
    );
  };

  /** The card's frame: a hairline box, danger-edged when the server flagged the ticket. */
  const cardFrame = (t: OrgTicketItem) =>
    `block w-full rounded-md border bg-white p-3 text-left text-xs dark:bg-gray-900 ${
      t.invalid !== undefined
        ? "border-red-300 dark:border-red-800"
        : "border-gray-200 dark:border-gray-800"
    }`;

  /**
   * A card: one button over the whole face. Unselectable and without the platform's long-press
   * callout, so dragging it never selects its words and holding it on a touch screen never raises
   * a menu; dimmed in place while its ghost is being carried.
   */
  const card = (t: OrgTicketItem) => (
    <button
      key={t.ticketId}
      type="button"
      data-ticket-card={t.ticketId}
      data-tooltip={`${t.title} · ${t.ticketId} · ${S.company.tickets.dragHint}`}
      {...drag.cardProps(t)}
      className={`${cardFrame(t)} cursor-pointer select-none transition-[border-color,opacity] duration-150 [-webkit-touch-callout:none] hover:border-gray-300 dark:hover:border-gray-600 ${
        lifted?.ticket.ticketId === t.ticketId ? "opacity-40" : ""
      }`}
    >
      {cardBody(t)}
    </button>
  );

  const columns = board === null ? null : boardColumns(board, { blockedOnly, query, names });
  const narrowed = blockedOnly || query.trim() !== "";
  const invalids = board === null ? [] : invalidTickets(board);

  return (
    <OrgPage
      title={S.nav.org.tickets}
      info={S.company.tickets.info}
      wide
      actions={
        <>
          <SearchInput
            size="sm"
            className="w-44"
            aria-label={S.company.tickets.searchPlaceholder}
            placeholder={S.company.tickets.searchPlaceholder}
            value={query}
            onChange={setQuery}
          />
          <label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
            {S.company.tickets.blockedOnly}
            <Switch
              checked={blockedOnly}
              onChange={(v) => {
                setBlockedOnly(v);
                setQueryParams({ blocked: v ? "1" : null });
              }}
            />
          </label>
          <Button variant="primary" size="sm" onClick={() => setCreateOpen(true)}>
            {S.company.tickets.create}
          </Button>
        </>
      }
    >
      {error !== null && (
        <Notice
          tone="danger"
          role="alert"
          className="mb-3"
          retry={{ label: S.common.retry, onClick: () => void load() }}
        >
          {S.company.tickets.loadFailed(error)}
        </Notice>
      )}

      {board !== null &&
        allTickets(board).length === 0 &&
        board.invalidFiles.length === 0 &&
        !hintDismissed && (
          <Notice
            tone="neutral"
            className="mb-3"
            dismiss={{
              ariaLabel: S.company.tickets.dismissHint,
              onClick: () => {
                dismissHint(emptyHintKey);
                setHintDismissed(true);
              },
            }}
          >
            {S.company.tickets.emptyHint}
          </Notice>
        )}

      <div ref={drag.boardRef} className="overflow-x-auto pb-2">
        <div className="grid min-w-[50rem] grid-cols-5 gap-3">
          {columns === null
            ? TICKET_COLUMNS.map((status) => <ColumnSkeleton key={status} status={status} />)
            : columns.map((col) => (
                <div
                  key={col.status}
                  role="group"
                  aria-label={`${S.company.tickets.columns[col.status] ?? col.status} · ${col.tickets.length}`}
                  {...{ [TICKET_COLUMN_ATTR]: col.status }}
                  className={`${columnClass} ${
                    dropOver === col.status
                      ? "border-accent ring-1 ring-accent"
                      : highlightColumn === col.status && isTicketStatus(highlightColumn)
                        ? "border-gray-400 dark:border-gray-600"
                        : ""
                  }`}
                >
                  <div className={`h-1 rounded-t-md ${COLUMN_BAR[col.status]}`} />
                  <div className="flex items-center justify-between gap-2 px-2.5 py-2">
                    <span className="text-xs font-semibold text-gray-700 dark:text-gray-200">
                      {S.company.tickets.columns[col.status] ?? col.status}
                    </span>
                    <Count n={col.tickets.length} />
                  </div>
                  <div className="flex flex-1 flex-col gap-2 px-2 pb-2">
                    {col.tickets.map(card)}
                    {col.tickets.length === 0 && (
                      <div
                        className={`flex min-h-20 flex-1 items-center justify-center rounded-md border border-dashed px-2 text-center text-xs ${
                          dropOver === col.status
                            ? "border-accent text-gray-600 dark:text-gray-300"
                            : "border-gray-300 text-gray-400 dark:border-gray-700 dark:text-gray-500"
                        }`}
                      >
                        {lifted !== null && canMove(lifted.ticket.status, col.status)
                          ? S.company.tickets.dropHere
                          : narrowed
                            ? S.company.tickets.searchNoMatch
                            : S.company.tickets.columnEmpty}
                      </div>
                    )}
                  </div>
                </div>
              ))}
        </div>
      </div>

      {(invalids.length > 0 || (board !== null && board.invalidFiles.length > 0)) && (
        <Notice tone="danger" className="mt-2">
          {invalids.length > 0 && (
            <>
              <p className="mb-1 flex items-center gap-1.5 font-medium">
                <span data-slot="icon" className="shrink-0">
                  <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />
                </span>
                {S.company.tickets.invalidTickets}
              </p>
              <ul className="mb-2 space-y-1">
                {invalids.map((t) => (
                  <li key={t.ticketId} className="flex items-baseline">
                    <TitleButton
                      title={S.company.tickets.openTicket}
                      className="shrink-0 font-mono"
                      onClick={() => openTicket(t.ticketId)}
                    >
                      {t.ticketId}
                    </TitleButton>
                    <span className="min-w-0">: {t.invalid}</span>
                  </li>
                ))}
              </ul>
            </>
          )}
          {board !== null && board.invalidFiles.length > 0 && (
            <>
              <p className="mb-1 flex items-center gap-1.5 font-medium">
                <span data-slot="icon" className="shrink-0">
                  <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />
                </span>
                {S.company.tickets.invalidFiles}
              </p>
              <ul className="space-y-1 font-mono">
                {board.invalidFiles.map((f) => (
                  <li key={f.path}>
                    {f.path}: {f.error}
                  </li>
                ))}
              </ul>
            </>
          )}
        </Notice>
      )}

      {/* The lifted card's ghost: the card's own face at its own width, following the
          pointer above everything else and never under it — the column hit test reads through
          it. The pointer's moves write its position straight to the element. */}
      {lifted !== null &&
        createPortal(
          <div
            ref={drag.ghostRef}
            aria-hidden
            style={{ width: lifted.width, transform: drag.ghostTransform() }}
            className="pointer-events-none fixed left-0 top-0 z-[60]"
          >
            <div className={`${cardFrame(lifted.ticket)} rotate-1 shadow-lg ring-1 ring-accent`}>
              {cardBody(lifted.ticket)}
            </div>
          </div>,
          document.body,
        )}

      {/* Move confirmation: the target column, and a reason when the target is rejected —
          the same dialog the detail's own move goes through. */}
      <MoveTicketConfirm
        move={move === null ? null : { title: move.ticket.title, to: move.to }}
        busy={busy}
        onClose={() => (busy ? undefined : setMove(null))}
        onConfirm={(reason) => void confirmMove(reason)}
        {...(moveRefusal !== null ? { refusal: S.common.refused(moveRefusal) } : {})}
      />

      <CreateTicketDialog
        open={createOpen}
        projectId={projectId}
        orgId={orgId}
        employees={employees.map((e) => ({ agentId: e.agentId, name: e.name }))}
        tickets={board === null ? [] : allTickets(board)}
        onClose={() => setCreateOpen(false)}
        onCreated={(ticketId) => {
          setCreateOpen(false);
          company.ticketsChanged();
          openTicket(ticketId);
        }}
      />
    </OrgPage>
  );
}

/** A column while the first fetch is out: the bar and header in place, two card-shaped placeholders. */
function ColumnSkeleton({ status }: { status: OrgTicketStatus }) {
  return (
    <div className={columnClass}>
      <div className={`h-1 rounded-t-md ${COLUMN_BAR[status]}`} />
      <div className="flex items-center justify-between gap-2 px-2.5 py-2">
        <span className="text-xs font-semibold text-gray-700 dark:text-gray-200">
          {S.company.tickets.columns[status] ?? status}
        </span>
        <Skeleton className="h-4 w-6 rounded-full" />
      </div>
      <div className="flex flex-col gap-2 px-2 pb-2">
        {Array.from(
          { length: status === "proposed" || status === "in_progress" ? 2 : 1 },
          (_, i) => (
            <div
              key={i}
              className="space-y-2 rounded-md border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900"
            >
              <Skeleton className="h-3.5 w-4/5" />
              <Skeleton className="h-3 w-2/5" />
              <Skeleton className="h-3 w-3/5" />
            </div>
          ),
        )}
      </div>
    </div>
  );
}

function CreateTicketDialog({
  open,
  projectId,
  orgId,
  employees,
  tickets,
  onClose,
  onCreated,
}: {
  open: boolean;
  projectId: string;
  orgId: string;
  employees: ReadonlyArray<{ agentId: string; name: string }>;
  tickets: readonly OrgTicketItem[];
  onClose: () => void;
  onCreated: (ticketId: string) => void;
}) {
  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState("");
  const [goal, setGoal] = useState("");
  const [acceptance, setAcceptance] = useState("");
  const [owner, setOwner] = useState("");
  const [parent, setParent] = useState("");
  const [notify, setNotify] = useState("");
  const [priority, setPriority] = useState<OrgTicketPriority>("P1");
  const [due, setDue] = useState("");
  const [titleError, setTitleError] = useState<string | undefined>(undefined);
  const [slugError, setSlugError] = useState<string | undefined>(undefined);
  const [refusal, setRefusal] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!open) return;
    setTitle("");
    setSlug("");
    setGoal("");
    setAcceptance("");
    setOwner("");
    setParent("");
    setNotify("");
    setPriority("P1");
    setDue("");
    setTitleError(undefined);
    setSlugError(undefined);
    // A new ticket, not the refused one: the previous refusal is not its answer.
    setRefusal(null);
  }, [open]);

  const submit = async () => {
    if (!title.trim()) {
      setTitleError(S.common.requiredField);
      return;
    }
    if (slug.trim() !== "" && !isTicketSlug(slug.trim())) {
      setSlugError(S.company.tickets.slugInvalid);
      return;
    }
    setBusy(true);
    try {
      const detail = await api.createOrgTicket(projectId, orgId, {
        title: title.trim(),
        ...(slug.trim() ? { slug: slug.trim() } : {}),
        ...(goal.trim() ? { goal: goal.trim() } : {}),
        ...(acceptance.trim() ? { acceptanceCriteria: acceptance.trim() } : {}),
        ...(owner ? { owner } : {}),
        ...(parent ? { parent } : {}),
        ...(notify.trim() ? { notify: splitPrincipalList(notify) } : {}),
        priority,
        ...(due ? { due } : {}),
      });
      toastSuccess(S.company.tickets.created);
      onCreated(detail.ticketId);
    } catch (e) {
      // The dialog stays: it is the form that asked, so the reason belongs above its fields
      // rather than in a toast that dismisses itself while the reader is still typing.
      setRefusal(apiErrorText(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal
      open={open}
      title={S.company.tickets.createTitle}
      // A write in flight is the dialog's: closing it would take away the form the answer is
      // about (the cancel button is already disabled; this is the second door).
      onClose={() => (busy ? undefined : onClose())}
      widthClass="sm:max-w-lg"
      footer={
        <>
          <Button size="sm" onClick={onClose} disabled={busy}>
            {S.common.cancel}
          </Button>
          <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
            {S.common.create}
          </Button>
        </>
      }
    >
      <div className="space-y-3">
        {refusal !== null && (
          // The form's own words: a refusal is about what the reader just typed, so it reads
          // above the fields that still hold it, not as page-level news.
          <NoticeStrip tone="danger" role="alert" className="rounded-md border px-2.5 py-2 text-xs">
            <span data-slot="body">{S.common.refused(refusal)}</span>
          </NoticeStrip>
        )}
        <Input
          size="sm"
          label={S.company.tickets.ticketTitle}
          required
          value={title}
          error={titleError}
          autoFocus
          onChange={(e) => {
            setTitle(e.target.value);
            setTitleError(undefined);
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.nativeEvent.isComposing) {
              e.preventDefault();
              void submit();
            }
          }}
        />
        <Input
          size="sm"
          label={S.company.tickets.slug}
          value={slug}
          hint={S.company.tickets.slugHint}
          error={slugError}
          className="font-mono"
          onChange={(e) => {
            const next = e.target.value;
            setSlug(next);
            // The rule is short and the box is small: say so while it is typed, not on submit.
            setSlugError(
              next.trim() === "" || isTicketSlug(next.trim())
                ? undefined
                : S.company.tickets.slugInvalid,
            );
          }}
        />
        <Textarea
          size="sm"
          label={S.company.tickets.goal}
          rows={3}
          value={goal}
          hint={S.company.tickets.goalHint}
          onChange={(e) => setGoal(e.target.value)}
        />
        <Textarea
          size="sm"
          label={S.company.tickets.acceptance}
          rows={3}
          value={acceptance}
          hint={S.company.tickets.acceptanceHint}
          onChange={(e) => setAcceptance(e.target.value)}
        />
        <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
          <Select
            size="sm"
            label={S.company.tickets.owner}
            value={owner}
            hint={S.company.tickets.ownerSelfHint}
            onChange={(e) => setOwner(e.target.value)}
          >
            <option value="">{S.company.tickets.ownerSelf}</option>
            {employees.map((e) => (
              <option key={e.agentId} value={agentPrincipal(e.agentId)}>
                {e.name}
              </option>
            ))}
          </Select>
          <Select
            size="sm"
            label={S.company.tickets.parent}
            value={parent}
            onChange={(e) => setParent(e.target.value)}
          >
            <option value="">{S.company.tickets.noParent}</option>
            {tickets.map((t) => (
              <option key={t.ticketId} value={t.ticketId}>
                {t.title}
              </option>
            ))}
          </Select>
          <div>
            <FieldLabel>{S.company.tickets.priority}</FieldLabel>
            <Segmented
              options={PRIORITIES.map((p) => ({ value: p, label: p }))}
              value={priority}
              onChange={setPriority}
              cols={3}
            />
          </div>
          <Input
            size="sm"
            label={S.company.tickets.due}
            type="date"
            value={due}
            className="font-mono"
            onChange={(e) => setDue(e.target.value)}
          />
        </div>
        <Input
          size="sm"
          label={S.company.tickets.notify}
          value={notify}
          hint={S.company.tickets.notifyHint}
          className="font-mono"
          onChange={(e) => setNotify(e.target.value)}
        />
      </div>
    </Modal>
  );
}