{
  "$schema": "https://zoblocks.design/schema/registry-item.json",
  "name": "clinical-note",
  "type": "zoblocks:component",
  "title": "Clinical Note",
  "description": "LOINC-coded sections, per-range provenance across six origins, a composable sign gate with three severities, and deterministic FHIR, XHTML and plain-text output. The engine ships as an npm package with no DOM; this item is the Tailwind skin over it.",
  "categories": [
    "clinical",
    "documentation"
  ],
  "dependencies": [
    "clsx",
    "tailwind-merge",
    "@zoblocks/clinical-note-core",
    "prosemirror-view",
    "prosemirror-state",
    "prosemirror-model",
    "prosemirror-keymap",
    "prosemirror-history",
    "prosemirror-commands"
  ],
  "registryDependencies": [
    "utils",
    "tokens",
    "clinical-note-core"
  ],
  "files": [
    {
      "path": "registry/zoblocks/clinical-note/clinical-note.tsx",
      "type": "zoblocks:component",
      "target": "components/zoblocks/clinical-note.tsx",
      "content": "\"use client\";\n\n/**\n * ClinicalNote — a note editor that knows who wrote every character.\n *\n * A rich text editor is a solved problem; a clinical note is not. Every\n * character in one has an origin: the clinician typed it, dictated it, a\n * template fired it, it was pulled from a lab result, it was copied forward\n * from a note about a different admission, or a model wrote it. In every EHR\n * shipping today all of that collapses into identical black text the moment it\n * lands on screen — and the clinician signs, attesting to all of it equally.\n *\n * Three well-documented problems fall out of that one missing structure. A 2022\n * analysis of over 100 million notes found 50.1% of note text duplicated from\n * prior documentation on the same patient. Copy-and-paste has been implicated\n * in roughly a third of errors in ambulatory patient-safety analyses. And CMS's\n * July 2025 signature guidance treats an AI scribe exactly as it treats a human\n * one: the clinician signs, and owns every word, whether or not the tool is\n * named.\n *\n * Storing origin per range does not solve any of those. It makes all three\n * *visible*, which is the prerequisite — and it is what turns \"I reviewed it\"\n * from an unfalsifiable claim into something the sign button can check.\n *\n * The engine is `@zoblocks/clinical-note-core`: schema, provenance,\n * gate rules and serializers, with no DOM and no React. This file is the skin.\n */\n\nimport * as React from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  DEFAULT_RULES,\n  ORIGINS,\n  NODES,\n  emptyNote,\n  formatDuration,\n  sectionAttrs,\n  sections,\n  toText,\n  type Finding,\n  type GateContext,\n  type GateRule,\n  type NoteTypeDef,\n  type NoteTypeName,\n  type Origin,\n  type Phrase,\n} from \"@zoblocks/clinical-note-core\";\nimport type { Node as PMNode } from \"prosemirror-model\";\nimport { ORIGIN_LABEL, useClinicalNote, type ClinicalNoteApi } from \"@/lib/zoblocks-clinical-note\";\n\nexport {\n  ORIGIN_LABEL,\n  useClinicalNote,\n  mixed,\n  noteDoc,\n  noteSection,\n  para,\n} from \"@/lib/zoblocks-clinical-note\";\n\n/* ------------------------------------------------------------------ */\n/* Glyphs                                                              */\n/* ------------------------------------------------------------------ */\n\n/**\n * Inline, on a 24px grid with a 2px stroke — Lucide's geometry.\n *\n * Inline rather than a dependency because a registry component is copied into\n * a customer's repository, and adding an icon package to their bundle for six\n * glyphs is a decision that should be theirs.\n */\nfunction Icon({ path, className }: { path: React.ReactNode; className?: string }) {\n  return (\n    <svg\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={2}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={cn(\"size-4 shrink-0\", className)}\n      aria-hidden=\"true\"\n      focusable=\"false\"\n    >\n      {path}\n    </svg>\n  );\n}\n\nconst UndoIcon = () => (\n  <Icon\n    path={\n      <>\n        <path d=\"M9 14 4 9l5-5\" />\n        <path d=\"M4 9h10.5a5.5 5.5 0 0 1 0 11H11\" />\n      </>\n    }\n  />\n);\nconst RedoIcon = () => (\n  <Icon\n    path={\n      <>\n        <path d=\"m15 14 5-5-5-5\" />\n        <path d=\"M20 9H9.5a5.5 5.5 0 0 0 0 11H13\" />\n      </>\n    }\n  />\n);\nconst BoldIcon = () => (\n  <Icon path={<path d=\"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8\" />} />\n);\nconst ItalicIcon = () => (\n  <Icon\n    path={\n      <>\n        <path d=\"M19 4h-9\" />\n        <path d=\"M14 20H5\" />\n        <path d=\"m15 4-6 16\" />\n      </>\n    }\n  />\n);\nconst OriginsIcon = () => (\n  <Icon\n    path={\n      <>\n        <circle cx=\"12\" cy=\"12\" r=\"10\" />\n        <path d=\"M12 18a6 6 0 0 0 0-12z\" fill=\"currentColor\" stroke=\"none\" />\n      </>\n    }\n  />\n);\nconst BlockIcon = () => (\n  <Icon\n    path={\n      <>\n        <circle cx=\"12\" cy=\"12\" r=\"10\" />\n        <path d=\"m15 9-6 6\" />\n        <path d=\"m9 9 6 6\" />\n      </>\n    }\n  />\n);\nconst WarnIcon = () => (\n  <Icon\n    path={\n      <>\n        <path d=\"m21.7 18-8-14a2 2 0 0 0-3.4 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3\" />\n        <path d=\"M12 9v4\" />\n        <path d=\"M12 17h.01\" />\n      </>\n    }\n  />\n);\nconst PassIcon = () => (\n  <Icon\n    path={\n      <>\n        <circle cx=\"12\" cy=\"12\" r=\"10\" />\n        <path d=\"m9 12 2 2 4-4\" />\n      </>\n    }\n  />\n);\nconst ShieldIcon = () => (\n  <Icon\n    path={\n      <>\n        <path d=\"M20 13c0 5-3.5 7.5-7.7 9a1 1 0 0 1-.7 0C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.2-2.7a1.2 1.2 0 0 1 1.5 0C14.5 3.8 17 5 19 5a1 1 0 0 1 1 1z\" />\n        <path d=\"m9 12 2 2 4-4\" />\n      </>\n    }\n  />\n);\n\n/* ------------------------------------------------------------------ */\n/* Props                                                               */\n/* ------------------------------------------------------------------ */\n\n/** Who the note is about. Two independent identifiers, minimum. */\nexport interface NoteSubject {\n  /** FHIR reference, e.g. `Patient/4471902`. */\n  reference: string;\n  /** Family-name-first, as a chart banner shows it. */\n  display: string;\n  /** Medical record number, or whatever your deployment's second identifier is. */\n  identifier?: string;\n  /** Rendered verbatim. Ambiguity in a date of birth is a wrong-patient event. */\n  birthDate?: string;\n  /** Free text: \"30y M\", \"Bed 4E-12\". */\n  detail?: string;\n}\n\n/** Who is writing, and whether someone else has to countersign. */\nexport interface NoteAuthor {\n  display: string;\n  /** \"Resident\", \"Attending\", \"Scribe\" — shown beside the name. */\n  role?: string;\n  requiresCosign?: boolean;\n}\n\n/** What the host is doing with the draft, said honestly. */\nexport type SaveState =\n  | { kind: \"saved\"; at: string }\n  | { kind: \"saving\" }\n  | { kind: \"offline\"; pending: number }\n  | { kind: \"failed\"; reason?: string };\n\nexport type CommitKind = \"draft\" | \"sign\" | \"addend\";\n\nexport interface ClinicalNoteProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  /** Who the note is about. Never optional — it is the wrong-patient mitigation. */\n  subject: NoteSubject;\n  /**\n   * Who is writing. Distinct from `recordedBy` on the signature: the person composing and the\n   * person attesting are not always the same.\n   */\n  author: NoteAuthor;\n  /** Decides which sections exist and which of them block a signature. */\n  noteType: NoteTypeName | NoteTypeDef;\n  /** The document. Defaults to an empty note of `noteType`. */\n  value?: PMNode;\n  /** Fired as the note is edited, with the origin of the edit preserved. */\n  onChange?: (doc: PMNode) => void;\n  /**\n   * The instant the gate is evaluated against, from the host's clock.\n   *\n   * Required, and there is no default. A browser clock on a ward workstation\n   * is not evidence, and 42 CFR 482.24(c)(1) wants entries dated, timed and\n   * authenticated. Passing `new Date()` is a decision the host makes, not one\n   * this component makes silently on their behalf.\n   */\n  now: Date;\n  /** Extra gate rules, appended to the defaults. */\n  rules?: readonly GateRule[];\n  /** Overrides for the default gate context — thresholds, mostly. */\n  gateOptions?: Partial<Omit<GateContext, \"noteType\" | \"now\" | \"subject\">>;\n  /** Dot phrases. None ship in the package; a phrase library is yours. */\n  phrases?: readonly Phrase[];\n  /** Draft state, shown in the status strip. Never a silent spinner. */\n  saveState?: SaveState;\n  /**\n   * Fired for each of the three commits.\n   *\n   * Three verbs with three legal meanings, never one blue Save: `draft` is\n   * reversible, `sign` is not, and `addend` is the only legal operation on a\n   * note that has already been signed.\n   */\n  onCommit?: (kind: CommitKind, doc: PMNode, acknowledged: string[]) => void;\n  /** Renders the signed reader instead of the editor. */\n  readOnly?: boolean;\n  /** The attestation sentence. Wording is a legal and organisational decision. */\n  attestation?: string;\n  /** Absolute, with offset — the created/edited line under the document. */\n  timestampLine?: string;\n  /**\n   * Accessible name for the editable region. Defaults to \"Note body\".\n   *\n   * User-visible text, so it is a prop: a deployment in another language needs\n   * to be able to change it.\n   */\n  editorLabel?: string;\n}\n\n/* ------------------------------------------------------------------ */\n/* Pieces                                                              */\n/* ------------------------------------------------------------------ */\n\nfunction Banner({ subject, status }: { subject: NoteSubject; status: React.ReactNode }) {\n  return (\n    <div className=\"flex items-start justify-between gap-3 border-b border-[var(--zb-border)] px-5 py-3\">\n      <div className=\"min-w-0\">\n        <div className=\"flex flex-wrap items-center gap-2\">\n          <span className=\"truncate text-sm font-semibold text-[var(--zb-text)]\">\n            {subject.display}\n          </span>\n          {status}\n        </div>\n        <div className=\"mt-0.5 flex flex-wrap gap-x-2 text-xs tabular-nums text-[var(--zb-text-muted)]\">\n          {subject.identifier ? <span>MRN {subject.identifier}</span> : null}\n          {subject.birthDate ? <span>· DOB {subject.birthDate}</span> : null}\n          {subject.detail ? <span>· {subject.detail}</span> : null}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction ToolButton({\n  label,\n  onClick,\n  disabled,\n  pressed,\n  children,\n}: {\n  label: string;\n  onClick?: () => void;\n  disabled?: boolean;\n  pressed?: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      // A toolbar is one tab stop, not fifteen. Arrow keys move within it; the\n      // roving tabindex is managed by the toolbar below.\n      tabIndex={-1}\n      aria-label={label}\n      aria-pressed={pressed}\n      disabled={disabled}\n      onClick={onClick}\n      className={cn(\n        \"inline-flex h-7 min-w-7 items-center justify-center gap-1.5 rounded-md px-1.5\",\n        \"text-[var(--zb-text-muted)] transition-colors\",\n        \"hover:bg-[var(--zb-surface-raised)] hover:text-[var(--zb-text)]\",\n        \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\",\n        \"disabled:pointer-events-none disabled:opacity-40\",\n        pressed && \"bg-[var(--zb-accent-subtle)] text-[var(--zb-accent-hover)]\",\n      )}\n    >\n      {children}\n    </button>\n  );\n}\n\n/**\n * The toolbar, as one tab stop with arrow-key movement.\n *\n * The WAI-ARIA toolbar pattern, and it is not decoration: fifteen individually\n * focusable buttons means fifteen Tab presses between the document and the\n * sign button, every single time, for anyone who does not use a mouse.\n */\nfunction Toolbar({ children, label }: { children: React.ReactNode; label: string }) {\n  const ref = React.useRef<HTMLDivElement>(null);\n  const [active, setActive] = React.useState(0);\n\n  const buttons = React.useCallback(\n    () =>\n      Array.from(ref.current?.querySelectorAll<HTMLButtonElement>(\"button:not([disabled])\") ?? []),\n    [],\n  );\n\n  React.useEffect(() => {\n    const all = buttons();\n    all.forEach((button, i) => (button.tabIndex = i === active ? 0 : -1));\n  });\n\n  function onKeyDown(event: React.KeyboardEvent) {\n    const all = buttons();\n    if (all.length === 0) return;\n\n    // One decision, one place. The previous shape computed the target twice —\n    // once to decide whether the key was ours, once to act on it — which is\n    // how the two got to disagree about Home and End.\n    const target = ((): number | null => {\n      switch (event.key) {\n        case \"ArrowRight\":\n          return (active + 1) % all.length;\n        case \"ArrowLeft\":\n          return (active - 1 + all.length) % all.length;\n        case \"Home\":\n          return 0;\n        case \"End\":\n          return all.length - 1;\n        default:\n          // Anything else belongs to the host, or to type-ahead.\n          return null;\n      }\n    })();\n\n    if (target === null) return;\n    event.preventDefault();\n    setActive(target);\n    all[target]?.focus();\n  }\n\n  return (\n    <div\n      ref={ref}\n      role=\"toolbar\"\n      aria-label={label}\n      aria-orientation=\"horizontal\"\n      onKeyDown={onKeyDown}\n      className=\"flex flex-wrap items-center gap-1 border-b border-[var(--zb-border)] px-4 py-1.5\"\n    >\n      {children}\n    </div>\n  );\n}\n\nfunction Cluster({ children }: { children: React.ReactNode }) {\n  return (\n    <span className=\"inline-flex items-center gap-0.5 rounded-lg bg-[var(--zb-bg-subtle)] p-0.5\">\n      {children}\n    </span>\n  );\n}\n\n/** The 100%-stacked bar. Five swatch rows is a legend; this is the data. */\nfunction OriginBar({ ratio }: { ratio: Record<Origin, number> }) {\n  const present = ORIGINS.filter((origin) => ratio[origin] > 0);\n  return (\n    <div\n      className=\"flex h-2 overflow-hidden rounded-full ring-1 ring-inset ring-[var(--zb-border)]\"\n      role=\"img\"\n      aria-label={present\n        .map((origin) => `${ORIGIN_LABEL[origin]} ${Math.round(ratio[origin] * 100)}%`)\n        .join(\", \")}\n    >\n      {present.map((origin) => (\n        <span\n          key={origin}\n          data-origin={origin}\n          className=\"zb-note-bar block h-full\"\n          style={{ width: `${ratio[origin] * 100}%` }}\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction SeverityIcon({ severity }: { severity: Finding[\"severity\"] }) {\n  if (severity === \"block\") return <BlockIcon />;\n  if (severity === \"warn\") return <WarnIcon />;\n  return <PassIcon />;\n}\n\n/**\n * The sign gate.\n *\n * Three severities and only one of them stops you. A gate that blocks on\n * everything is routed around within a week; one that blocks on nothing is\n * decoration. Warnings are shown, counted, and handed to `onCommit` so the\n * host can record them — a signature over a note with five acknowledged\n * warnings is a different artifact from one with none.\n */\nexport function SignGate({\n  findings,\n  canSign,\n  attestation,\n  author,\n  onSign,\n  onCancel,\n  onNavigate,\n}: {\n  /**\n   * What is standing between this note and a signature, each with a severity.\n   *\n   * Rendered in full rather than summarised: \"3 issues\" tells an author to\n   * hunt, and the point of the gate is that it already knows.\n   */\n  findings: readonly Finding[];\n  /** Whether policy permits this author to sign at all. Separate from whether the findings currently allow it. */\n  canSign: boolean;\n  /** The sentence being signed. Shown before the control, never after the decision. */\n  attestation?: string;\n  /** Who is signing, and in what capacity. */\n  author: NoteAuthor;\n  /** Fired with the ids of every finding the author acknowledged on the way through. Acknowledgement is part of the record, not a dismissal. */\n  onSign?: (acknowledged: string[]) => void;\n  /** Fired when the author backs out of signing. The draft is untouched. */\n  onCancel?: () => void;\n  /** Fired when the author jumps to the passage a finding is about. Without it a finding names a problem and offers no way to reach it. */\n  onNavigate?: (finding: Finding) => void;\n}) {\n  const [attested, setAttested] = React.useState(false);\n  const blocking = findings.filter((f) => f.severity === \"block\");\n  const warnings = findings.filter((f) => f.severity === \"warn\");\n  const passed = findings.filter((f) => f.severity === \"pass\");\n\n  return (\n    <div className=\"flex flex-col gap-4\" data-testid=\"sign-gate\">\n      <div\n        role=\"status\"\n        className={cn(\n          \"flex items-center gap-2 rounded-md px-3 py-2 text-sm\",\n          blocking.length > 0\n            ? \"bg-[var(--zb-status-critical-bg)] text-[var(--zb-status-critical)]\"\n            : \"bg-[var(--zb-status-normal-bg)] text-[var(--zb-status-normal)]\",\n        )}\n      >\n        <SeverityIcon severity={blocking.length > 0 ? \"block\" : \"pass\"} />\n        <span>\n          <strong className=\"font-semibold\">{blocking.length} blocking</strong> · {warnings.length}{\" \"}\n          {warnings.length === 1 ? \"warning\" : \"warnings\"} · {passed.length} passed\n        </span>\n      </div>\n\n      <ul className=\"divide-y divide-[var(--zb-border)] overflow-hidden rounded-lg border border-[var(--zb-border)]\">\n        {findings.map((finding) => (\n          <li\n            key={finding.id}\n            className={cn(\n              \"grid grid-cols-[auto_1fr_auto] items-start gap-3 px-3 py-2.5 text-sm\",\n              finding.severity === \"block\" &&\n                \"bg-[color-mix(in_oklab,var(--zb-status-critical-bg)_30%,transparent)]\",\n            )}\n          >\n            <span\n              className={cn(\n                \"mt-0.5\",\n                finding.severity === \"block\" && \"text-[var(--zb-status-critical)]\",\n                finding.severity === \"warn\" && \"text-[var(--zb-status-high)]\",\n                finding.severity === \"pass\" && \"text-[var(--zb-status-normal)]\",\n              )}\n            >\n              <SeverityIcon severity={finding.severity} />\n            </span>\n            <span className=\"min-w-0\">\n              <span className=\"text-[var(--zb-text)]\">{finding.title}</span>\n              {finding.detail ? (\n                <span className=\"mt-0.5 block text-xs text-[var(--zb-text-muted)]\">\n                  {finding.detail}{\" \"}\n                  {finding.at && onNavigate ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => onNavigate(finding)}\n                      className=\"text-[var(--zb-accent)] underline underline-offset-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\"\n                    >\n                      Go to it\n                    </button>\n                  ) : null}\n                </span>\n              ) : null}\n            </span>\n            <span\n              className={cn(\n                \"rounded-full px-2 py-0.5 font-mono text-[10px] uppercase tracking-wider\",\n                finding.severity === \"block\" &&\n                  \"bg-[var(--zb-status-critical-bg)] text-[var(--zb-status-critical)]\",\n                finding.severity === \"warn\" &&\n                  \"bg-[var(--zb-status-high-bg)] text-[var(--zb-status-high)]\",\n                finding.severity === \"pass\" &&\n                  \"bg-[var(--zb-status-normal-bg)] text-[var(--zb-status-normal)]\",\n              )}\n            >\n              {finding.severity === \"block\"\n                ? \"Blocks\"\n                : finding.severity === \"warn\"\n                  ? \"Warns\"\n                  : \"Pass\"}\n            </span>\n          </li>\n        ))}\n      </ul>\n\n      {attestation ? (\n        <label className=\"flex items-start gap-2 border-t border-[var(--zb-border)] pt-4 text-sm\">\n          <input\n            type=\"checkbox\"\n            checked={attested}\n            onChange={(event) => setAttested(event.target.checked)}\n            className=\"mt-0.5 size-4 accent-[var(--zb-accent)]\"\n          />\n          <span>\n            <span className=\"text-[var(--zb-text)]\">{attestation}</span>\n            <span className=\"mt-1 block text-xs text-[var(--zb-text-muted)]\">\n              Signing as <strong className=\"font-medium\">{author.display}</strong>\n              {author.role ? ` · ${author.role}` : null}\n              {author.requiresCosign ? \" · a countersignature will be requested\" : null}\n            </span>\n          </span>\n        </label>\n      ) : null}\n\n      <div className=\"flex justify-end gap-2\">\n        <button\n          type=\"button\"\n          onClick={onCancel}\n          className=\"h-9 rounded-md px-3 text-sm text-[var(--zb-text-muted)] hover:bg-[var(--zb-surface-raised)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\"\n        >\n          Back to note\n        </button>\n        <button\n          type=\"button\"\n          disabled={!canSign || (Boolean(attestation) && !attested)}\n          onClick={() => onSign?.(warnings.map((warning) => warning.id))}\n          className={cn(\n            \"inline-flex h-9 items-center gap-2 rounded-md px-4 text-sm font-medium\",\n            \"bg-[var(--zb-accent)] text-[var(--zb-text-on-accent)]\",\n            \"hover:bg-[var(--zb-accent-hover)]\",\n            \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\",\n            \"disabled:pointer-events-none disabled:opacity-45\",\n          )}\n        >\n          <ShieldIcon />\n          Sign\n        </button>\n      </div>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* Reader                                                              */\n/* ------------------------------------------------------------------ */\n\nexport interface Attestation {\n  who: string;\n  role?: string;\n  /** Absolute, with offset. \"Today, 14:38\" is not a record. */\n  when: string;\n  statement?: string;\n}\n\nexport interface Addendum {\n  author: string;\n  when: string;\n  text: string;\n}\n\n/**\n * A signed note, read-only, with its addenda.\n *\n * Separate from the editor on purpose: most people who open a note never edit\n * one, and this path loads no ProseMirror view at all.\n *\n * The original text is never shown as corrected — it is shown as superseded.\n * Both statements stand, in order, with their own authors and times. That is\n * the difference between a record and a document, and it is what makes the\n * chart admissible.\n */\nexport function ClinicalNoteReader({\n  subject,\n  title,\n  doc,\n  attestations = [],\n  addenda = [],\n  className,\n  ...rest\n}: {\n  /** Who the note is about. Rendered so a reader can check the chart before believing the note. */\n  subject: NoteSubject;\n  /** The note's heading, and the article's accessible name. */\n  title: string;\n  /** The signed document. Read-only by construction — this component has no editing path at all. */\n  doc: PMNode;\n  /**\n   * Signatures on the note, in order.\n   *\n   * A countersignature is another attestation rather than a second copy of the\n   * first, so each carries its own signer, capacity and time.\n   */\n  attestations?: readonly Attestation[];\n  /**\n   * Addenda appended after signing.\n   *\n   * Never merged into the body: an addendum is a separate authored act, and\n   * folding it into the original text would rewrite what somebody signed.\n   */\n  addenda?: readonly Addendum[];\n} & React.HTMLAttributes<HTMLElement>) {\n  return (\n    <article\n      className={cn(\n        \"overflow-hidden rounded-xl border border-[var(--zb-border)] bg-[var(--zb-surface)]\",\n        className,\n      )}\n      aria-label={`${title}, signed`}\n      // A signed note is read in the same chart, at the same density, as the\n      // editor that produced it.\n      data-zb-density=\"clinical\"\n      {...rest}\n    >\n      <Banner\n        subject={subject}\n        status={\n          <span className=\"inline-flex items-center gap-1 rounded-full bg-[var(--zb-status-normal-bg)] px-2 py-0.5 text-xs font-medium text-[var(--zb-status-normal)]\">\n            <ShieldIcon />\n            Signed\n          </span>\n        }\n      />\n\n      <div className=\"space-y-5 px-5 py-4\">\n        <dl className=\"overflow-hidden rounded-lg border border-[var(--zb-border)] text-sm\">\n          {attestations.map((attestation) => (\n            <div\n              key={`${attestation.who}-${attestation.when}`}\n              className=\"grid grid-cols-[minmax(7rem,10rem)_1fr] border-b border-[var(--zb-border)] last:border-b-0\"\n            >\n              <dt className=\"bg-[var(--zb-bg-subtle)] px-3 py-2 text-[var(--zb-text-muted)]\">\n                {attestation.statement ? \"Attestation\" : \"Signed by\"}\n              </dt>\n              <dd className=\"px-3 py-2\">\n                <span className=\"text-[var(--zb-text)]\">\n                  {attestation.who}\n                  {attestation.role ? ` · ${attestation.role}` : null}\n                </span>\n                <span className=\"mt-0.5 block text-xs tabular-nums text-[var(--zb-text-muted)]\">\n                  {attestation.when}\n                </span>\n                {attestation.statement ? (\n                  <span className=\"mt-1 block text-[var(--zb-text-muted)]\">\n                    “{attestation.statement}”\n                  </span>\n                ) : null}\n              </dd>\n            </div>\n          ))}\n        </dl>\n\n        <div className=\"zb-note-doc zb-note-read max-w-[74ch]\">\n          {sections(doc).map(({ node }) => {\n            const { code, title } = sectionAttrs(node);\n            // One section at a time through the same serializer the export\n            // uses, so the reader can never drift from the transmitted text.\n            const lines = toText(NODES.doc.create(null, [node]))\n              .trim()\n              .split(\"\\n\")\n              .slice(1);\n            if (lines.length === 0) return null;\n            return (\n              <section key={code}>\n                <h3>{title}</h3>\n                {lines.map((line, i) => (\n                  <p key={i}>{line}</p>\n                ))}\n              </section>\n            );\n          })}\n        </div>\n\n        {addenda.map((addendum, i) => (\n          <div key={i} className=\"overflow-hidden rounded-lg border border-[var(--zb-border)]\">\n            <div className=\"flex flex-wrap items-center justify-between gap-2 bg-[var(--zb-bg-subtle)] px-3 py-2 text-xs tabular-nums text-[var(--zb-text-muted)]\">\n              <span>\n                <strong className=\"font-semibold text-[var(--zb-text)]\">Addendum {i + 1}</strong> ·{\" \"}\n                {addendum.author} · {addendum.when}\n              </span>\n            </div>\n            <p className=\"px-3 py-3 text-sm text-[var(--zb-text)]\">{addendum.text}</p>\n          </div>\n        ))}\n\n        <p className=\"rounded-md bg-[var(--zb-status-low-bg)] px-3 py-2 text-sm text-[var(--zb-text-muted)]\">\n          The signed note above cannot be edited. Corrections are made by adding a further addendum.\n        </p>\n      </div>\n    </article>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* The editor                                                          */\n/* ------------------------------------------------------------------ */\n\nfunction SaveStateLine({ state }: { state?: SaveState }) {\n  if (!state) return null;\n  const tone =\n    state.kind === \"failed\" ? \"danger\" : state.kind === \"offline\" ? \"warning\" : \"success\";\n  const text =\n    state.kind === \"saved\"\n      ? `Saved ${state.at}`\n      : state.kind === \"saving\"\n        ? \"Saving…\"\n        : state.kind === \"offline\"\n          ? `Offline — ${state.pending} change${state.pending === 1 ? \"\" : \"s\"} held locally`\n          : `Not saved${state.reason ? ` — ${state.reason}` : \"\"}`;\n\n  return (\n    // Polite for ordinary transitions; a failed save is the one a clinician has\n    // to hear about, because the alternative is losing twenty minutes of work.\n    <span\n      className=\"inline-flex items-center gap-1.5\"\n      role=\"status\"\n      aria-live={state.kind === \"failed\" ? \"assertive\" : \"polite\"}\n    >\n      <span\n        className={cn(\n          \"size-1.5 rounded-full\",\n          tone === \"success\" && \"bg-[var(--zb-status-normal)]\",\n          tone === \"warning\" && \"bg-[var(--zb-status-high)]\",\n          tone === \"danger\" && \"bg-[var(--zb-status-critical)]\",\n        )}\n      />\n      <span className=\"tabular-nums\">{text}</span>\n    </span>\n  );\n}\n\nexport function ClinicalNote({\n  subject,\n  author,\n  noteType,\n  value,\n  onChange,\n  now,\n  rules,\n  gateOptions,\n  phrases,\n  saveState,\n  onCommit,\n  readOnly = false,\n  attestation,\n  timestampLine,\n  editorLabel = \"Note body\",\n  className,\n  ...rest\n}: ClinicalNoteProps) {\n  const initial = React.useMemo(() => value ?? emptyNote(noteType), [value, noteType]);\n\n  const allRules = React.useMemo<readonly GateRule[]>(\n    () => (rules ? [...DEFAULT_RULES, ...rules] : DEFAULT_RULES),\n    [rules],\n  );\n  const gateContext = React.useMemo<GateContext>(\n    () => ({ ...gateOptions, noteType, now, subject: subject.reference }),\n    [gateOptions, noteType, now, subject.reference],\n  );\n\n  const api: ClinicalNoteApi = useClinicalNote({\n    value: initial,\n    onChange,\n    rules: allRules,\n    gateContext,\n    phrases,\n    readOnly,\n    label: editorLabel,\n  });\n\n  const [gateOpen, setGateOpen] = React.useState(false);\n  // Scoped per instance: a fixed id cross-wires two notes on one page.\n  const blockedId = `${React.useId()}-blocked`;\n  const noteSections = React.useMemo(() => sections(api.doc), [api.doc]);\n  const copied = Math.round(api.composition.ratio.copied * 100);\n  const unreviewed = api.gate.findings.find(\n    (f: Finding) => f.id === \"unreviewed-ai\" && f.severity === \"block\",\n  );\n\n  return (\n    <div\n      className={cn(\n        \"zb-note flex flex-col overflow-hidden rounded-xl border border-[var(--zb-border)] bg-[var(--zb-surface)]\",\n        className,\n      )}\n      data-zb-density=\"clinical\"\n      {...rest}\n    >\n      <Banner\n        subject={subject}\n        status={\n          <span className=\"rounded-full bg-[var(--zb-status-low-bg)] px-2 py-0.5 text-xs font-medium text-[var(--zb-status-low)]\">\n            Draft\n          </span>\n        }\n      />\n\n      <Toolbar label=\"Note formatting and insertion\">\n        <Cluster>\n          <ToolButton label=\"Undo\" onClick={api.cmd.undo} disabled={!api.canUndo}>\n            <UndoIcon />\n          </ToolButton>\n          <ToolButton label=\"Redo\" onClick={api.cmd.redo} disabled={!api.canRedo}>\n            <RedoIcon />\n          </ToolButton>\n        </Cluster>\n        <Cluster>\n          <ToolButton label=\"Bold\" onClick={api.cmd.bold}>\n            <BoldIcon />\n          </ToolButton>\n          <ToolButton label=\"Italic\" onClick={api.cmd.italic}>\n            <ItalicIcon />\n          </ToolButton>\n        </Cluster>\n        {api.blankCount > 0 ? (\n          <ToolButton\n            label={`Go to next blank, ${api.blankCount} remaining`}\n            onClick={api.cmd.nextBlank}\n          >\n            <span className=\"font-mono text-[11px]\">✳ {api.blankCount}</span>\n            <kbd className=\"rounded border border-[var(--zb-border)] px-1 font-mono text-[10px] text-[var(--zb-text-muted)]\">\n              F2\n            </kbd>\n          </ToolButton>\n        ) : null}\n        <span className=\"flex-1\" />\n        <ToolButton\n          label=\"Show where each passage came from\"\n          pressed={api.showOrigins}\n          onClick={() => api.setShowOrigins(!api.showOrigins)}\n        >\n          <OriginsIcon />\n          <span className=\"text-xs\">Origins</span>\n        </ToolButton>\n      </Toolbar>\n\n      <div className=\"flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-[var(--zb-border)] bg-[var(--zb-bg-subtle)] px-4 py-1.5 text-xs text-[var(--zb-text-muted)]\">\n        <SaveStateLine state={saveState} />\n        <span>\n          <strong className=\"font-semibold text-[var(--zb-text)]\">{author.display}</strong>\n          {author.role ? ` · ${author.role}` : null}\n          {author.requiresCosign ? \" · cosign required\" : null}\n        </span>\n        <span className=\"flex-1\" />\n        {copied > 0 ? (\n          <span className=\"rounded-full bg-[var(--zb-status-high-bg)] px-2 py-0.5 tabular-nums text-[var(--zb-status-high)]\">\n            {copied}% copied forward\n          </span>\n        ) : null}\n        {unreviewed ? (\n          <span className=\"rounded-full bg-[var(--zb-status-normal-bg)] px-2 py-0.5 text-[var(--zb-status-normal)]\">\n            {unreviewed.title}\n          </span>\n        ) : null}\n      </div>\n\n      <div className=\"flex min-h-[20rem] flex-col sm:flex-row\">\n        <nav\n          aria-label=\"Sections\"\n          className=\"shrink-0 border-b border-[var(--zb-border)] px-2 py-3 sm:w-56 sm:border-b-0 sm:border-e\"\n        >\n          <p className=\"px-2 pb-2 text-[10px] font-medium uppercase tracking-wider text-[var(--zb-text-muted)]\">\n            {noteSections.length} sections\n          </p>\n          <ul>\n            {noteSections.map(({ node }) => {\n              const { code, title, required } = sectionAttrs(node);\n              const empty = node.textContent.trim() === \"\";\n              return (\n                <li key={code}>\n                  <button\n                    type=\"button\"\n                    onClick={() => api.cmd.goToSection(code)}\n                    aria-current={api.activeSection === code ? \"true\" : undefined}\n                    className={cn(\n                      \"relative flex w-full items-center justify-between gap-2 rounded-md py-1.5 ps-3 pe-2 text-start text-[13px]\",\n                      \"text-[var(--zb-text-muted)] hover:bg-[var(--zb-surface-raised)]\",\n                      \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\",\n                      api.activeSection === code &&\n                        \"bg-[var(--zb-accent-subtle)] font-medium text-[var(--zb-accent-hover)] before:absolute before:inset-y-1.5 before:start-0 before:w-0.5 before:rounded before:bg-[var(--zb-accent)]\",\n                    )}\n                  >\n                    <span className=\"truncate\">{title}</span>\n                    {required && empty ? (\n                      <span className=\"shrink-0 rounded-full bg-[var(--zb-status-critical-bg)] px-1.5 text-[10px] text-[var(--zb-status-critical)]\">\n                        required\n                      </span>\n                    ) : null}\n                  </button>\n                </li>\n              );\n            })}\n          </ul>\n\n          {api.composition.total > 0 ? (\n            <div className=\"mt-4 border-t border-[var(--zb-border)] px-2 pt-3\">\n              <p className=\"pb-2 text-[10px] font-medium uppercase tracking-wider text-[var(--zb-text-muted)]\">\n                Origins\n              </p>\n              <OriginBar ratio={api.composition.ratio} />\n              <ul className=\"mt-2 space-y-1 text-[11px] tabular-nums text-[var(--zb-text-muted)]\">\n                {ORIGINS.filter((origin) => api.composition.ratio[origin] > 0).map((origin) => (\n                  <li key={origin} className=\"flex items-center gap-2\">\n                    <span data-origin={origin} className=\"zb-note-bar size-2 rounded-sm\" />\n                    <span className=\"flex-1\">{ORIGIN_LABEL[origin]}</span>\n                    <span>{Math.round(api.composition.ratio[origin] * 100)}%</span>\n                  </li>\n                ))}\n              </ul>\n            </div>\n          ) : null}\n        </nav>\n\n        <div className=\"min-w-0 flex-1 px-6 py-5\">\n          <div ref={api.ref} className=\"max-w-[74ch]\" />\n        </div>\n      </div>\n\n      <div className=\"flex flex-wrap items-center justify-between gap-3 border-t border-[var(--zb-border)] px-5 py-3\">\n        <p className=\"text-xs tabular-nums text-[var(--zb-text-muted)]\">{timestampLine}</p>\n        <div className=\"flex gap-2\">\n          <button\n            type=\"button\"\n            onClick={() => onCommit?.(\"draft\", api.doc, [])}\n            className=\"h-9 rounded-md border border-[var(--zb-border)] px-3 text-sm text-[var(--zb-text)] hover:bg-[var(--zb-surface-raised)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\"\n          >\n            Save draft\n          </button>\n          <button\n            type=\"button\"\n            onClick={() => setGateOpen(true)}\n            aria-describedby={api.gate.canSign ? undefined : blockedId}\n            className={cn(\n              \"inline-flex h-9 items-center gap-2 rounded-md px-4 text-sm font-medium\",\n              \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--zb-focus-ring)]\",\n              // Outlined rather than faded while blocked: the button still opens the gate, so\n              // its label has to keep full contrast — opacity took it below 3:1.\n              api.gate.canSign\n                ? \"bg-[var(--zb-accent)] text-[var(--zb-text-on-accent)] hover:bg-[var(--zb-accent-hover)]\"\n                : \"border border-[var(--zb-border-strong)] bg-[var(--zb-surface)] text-[var(--zb-text)] hover:bg-[var(--zb-bg-subtle)]\",\n            )}\n          >\n            <ShieldIcon />\n            Sign &amp; file\n          </button>\n          {!api.gate.canSign ? (\n            <span id={blockedId} className=\"sr-only\">\n              {api.gate.blocking.length} item\n              {api.gate.blocking.length === 1 ? \"\" : \"s\"} must be resolved before this note can be\n              signed.\n            </span>\n          ) : null}\n        </div>\n      </div>\n\n      {gateOpen ? (\n        <div className=\"border-t border-[var(--zb-border)] bg-[var(--zb-bg-subtle)] px-5 py-4\">\n          <SignGate\n            findings={api.gate.findings}\n            canSign={api.gate.canSign}\n            attestation={attestation}\n            author={author}\n            onCancel={() => setGateOpen(false)}\n            onNavigate={(finding) => {\n              setGateOpen(false);\n              if (finding.id === \"unreviewed-ai\") api.cmd.acceptAllAi();\n            }}\n            onSign={(acknowledged) => {\n              setGateOpen(false);\n              onCommit?.(\"sign\", api.doc, acknowledged);\n            }}\n          />\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\nClinicalNote.Reader = ClinicalNoteReader;\nClinicalNote.SignGate = SignGate;\n\nexport { formatDuration };\n"
    }
  ]
}
