# Article editor

An article the user and the agent write together beside the chat: a help article, a blog post, release notes. Headings, lists, callouts and links, with a format toolbar and markdown shortcuts. The agent rewrites the parts the user asks for, in place, and marks what it changed.

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

An article the user and the agent write together beside the chat: a help article, a blog post, release notes. Headings, lists, callouts and links, with a format toolbar and markdown shortcuts. The agent rewrites the parts the user asks for, in place, and marks what it changed.

## When to use it

**Use it when:** The user and the agent write one article together over several turns: a help article, a blog post, release notes, an announcement. The user writes and formats in the canvas, and asks the agent to draft, shorten or rewrite parts of it.

**Use something else when:** A one-line reply or a short answer (the chat). Structured fields with rules (form canvas). Text the agent writes once and the user never edits (a chat card). Mobile: the canvas isn't available; use the preview card (mountMobile).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `canvas.setState(patch)` | `Canvas state` | 600 ms after the user stops writing, and on blur. Only the fields that changed (title, subtitle, blocks), and publishedAt and url after Publish. |
| `canvas.setTitle(title)` | `Canvas title` | When the title changes: “Help article: &lt;title&gt;”. |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Mobile preview card: as soon as it shows. |

## States

Besides its data, the template draws these as itself: `mountState()` on the canvas, `mountMobileState()` in the mobile card. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | The canvas opens with only a title while the agent writes the first draft into its state. The editor takes over when the draft arrives. |
| Error | A saved article didn't load when the canvas reopened. Try again loads it in place; the article itself is still saved. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
mountMobileState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### ContentState

| Field | Type | Notes |
| --- | --- | --- |
| `canvasTitle` (optional) | `string` | The canvas header (setTitle, up to 80 characters). Default: "&lt;kind&gt;: &lt;title&gt;". |
| `kind` (optional) | `string` | What is being written, on the badge: "Help article", "Blog post". |
| `collection` (optional) | `string` | Where it lives, as a breadcrumb: "Help center / Reports". Display only. |
| `title` | `string` | The headline. |
| `subtitle` (optional) | `string` | One or two sentences under the headline: the summary readers see in search and lists. |
| `author` (optional) | `string` | The byline. Display only. |
| `tags` (optional) | `string[]` | Shown under the byline. Display only: the user asks the agent to change them. |
| `blocks` | `ContentBlock[]` |  |
| `publishedAt` (optional) | `string` | When the user last published it (ISO time). The editor sets it, so the agent knows. |
| `url` (optional) | `string` | The published article's address, from your app's publish(). |

### ContentBlock

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | Stable id. The agent keeps it when it rewrites a block, so the editor can show what it changed. |
| `type` | `ContentBlockType` | p (paragraph), h2 (heading), h3 (subheading), ul or ol (lists), quote or callout. |
| `text` (optional) | `string` | The text of every type but lists. Inline markdown: **bold**, *italic*, `code`, [label](https://…). |
| `items` (optional) | `string[]` | A list's items (ul, ol), each with the same inline markdown. |

### ContentActions

| Field | Type | Notes |
| --- | --- | --- |
| `onChange()` (optional) | `(state: ContentState) => void` | Called each time the draft is shared with the agent (debounced). Keep a copy in your app here if you need one. |
| `publish()` (optional) | `(state: ContentState) => Promise<{ url?: string } \| void>` | Publishes (or updates) the article in your app. With it the toolbar shows Publish. Resolve with its address; throw to show the error. |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/content-canvas.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/content-canvas.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/content-canvas.canvas.ts), [JavaScript](/ui-catalog/files/js/usage/content-canvas.canvas.js)
- content-canvas: [TypeScript](/ui-catalog/files/ts/content-canvas.ts), [JavaScript](/ui-catalog/files/js/content-canvas.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/draft_help_article/index.ts"
// agent/actions/draft_help_article/index.ts: a hosted canvas action (desktop).
// Copy the template (content-canvas.ts) and fs-kit.ts into agent/ui/.

type Result = ContentState | { error: string; articleId: string };

const NEW = (topic?: string): ContentState => ({
  kind: "Help article", collection: "Help center", title: topic ?? "", blocks: [{ id: "b1", type: "p", text: "" }],
});

// A new article (the agent writes the blocks on its next turn, in the state, not the chat), or a saved one.
// A failure goes back as data: the agent explains it, and the canvas shows it.
export async function execute(args: { topic?: string; articleId?: string }, ctx: ActionContext): Promise<Result> {
  if (!args.articleId) return NEW(args.topic);
  return loadArticle(ctx, args.articleId);
}

async function loadArticle(ctx: ActionContext, articleId: string): Promise<Result> {
  const res = await ctx.fetch(`/api/articles/${encodeURIComponent(articleId)}`);
  if (!res.ok) return { error: `Your saved article didn't load (${res.status}). It's still saved, so nothing is lost.`, articleId };
  return { ...(await res.json()), error: null };
}

const hasText = (st: Record<string, any>): boolean =>
  Boolean(st.blocks?.some((b: { text?: string; items?: string[] }) => (b.text ?? (b.items ?? []).join("")).trim()));

export function renderCanvas(ctx: CanvasActionContext) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  canvas.setType("CONTENT_EDITOR");
  canvas.setStatus("EDIT_MODE"); // the user and the agent both write
  const at = { root: canvas.root, head: canvas.head, canvas, eyebrow: "Help article" };
  // Publish: your app's help center. READ_MODE while it sends, so the agent doesn't edit mid-publish.
  const actions = {
    publish: async (article: ContentState) => {
      canvas.setStatus("READ_MODE");
      try {
        const res = await ctx.fetch("/api/articles", { method: "PUT", body: JSON.stringify(article), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error(`The help center answered ${res.status}.`);
        return { url: (await res.json()).url };
      } finally {
        canvas.setStatus("EDIT_MODE");
      }
    },
  };
  let cleanup: Cleanup = () => {};
  const st = canvas.state;

  if (st.error) {
    // A saved article didn't load. Try again: bones while it loads, then the editor, or the error again.
    const failed = (text: string): void => {
      cleanup = mountState({ ...at, title: "Your article", state: { kind: "error", title: "Couldn't open your article", text, retry: async () => {
        cleanup();
        cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the article…" } });
        const next = await loadArticle(ctx, st.articleId);
        cleanup();
        if ("error" in next && next.error) return failed(next.error);
        canvas.setState({ ...next, error: null }); // the agent reads the article from the canvas state
        cleanup = mount({ ...at, actions });
      } } });
    };
    failed(st.error);
  } else if (!hasText(st)) {
    // The agent is writing the first draft: bones in the editor's shape until its text arrives.
    const shown = mountState({ ...at, title: st.title, subtitle: st.collection, state: { kind: "loading", label: "The agent is writing…" } });
    const stop = canvas.onStateChange((next) => {
      if (!hasText(next)) return;
      stop(); shown();
      cleanup = mount({ ...at, actions });
    });
    cleanup = () => { stop(); shown(); };
  } else {
    cleanup = mount({ ...at, actions });
  }
  return () => cleanup();
}
```

```js title="agent/actions/draft_help_article/index.js"
// agent/actions/draft_help_article/index.js: a hosted canvas action (desktop).
// Copy the template (content-canvas.ts) and fs-kit.ts into agent/ui/.

const NEW = (topic) => ({
  kind: "Help article", collection: "Help center", title: topic ?? "", blocks: [{ id: "b1", type: "p", text: "" }],
});

// A new article (the agent writes the blocks on its next turn, in the state, not the chat), or a saved one.
// A failure goes back as data: the agent explains it, and the canvas shows it.
export async function execute(args, ctx) {
  if (!args.articleId) return NEW(args.topic);
  return loadArticle(ctx, args.articleId);
}

async function loadArticle(ctx, articleId) {
  const res = await ctx.fetch(`/api/articles/${encodeURIComponent(articleId)}`);
  if (!res.ok) return { error: `Your saved article didn't load (${res.status}). It's still saved, so nothing is lost.`, articleId };
  return { ...(await res.json()), error: null };
}

const hasText = (st) =>
  Boolean(st.blocks?.some((b) => (b.text ?? (b.items ?? []).join("")).trim()));

export function renderCanvas(ctx) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  canvas.setType("CONTENT_EDITOR");
  canvas.setStatus("EDIT_MODE"); // the user and the agent both write
  const at = { root: canvas.root, head: canvas.head, canvas, eyebrow: "Help article" };
  // Publish: your app's help center. READ_MODE while it sends, so the agent doesn't edit mid-publish.
  const actions = {
    publish: async (article) => {
      canvas.setStatus("READ_MODE");
      try {
        const res = await ctx.fetch("/api/articles", { method: "PUT", body: JSON.stringify(article), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error(`The help center answered ${res.status}.`);
        return { url: (await res.json()).url };
      } finally {
        canvas.setStatus("EDIT_MODE");
      }
    },
  };
  let cleanup = () => {};
  const st = canvas.state;

  if (st.error) {
    // A saved article didn't load. Try again: bones while it loads, then the editor, or the error again.
    const failed = (text) => {
      cleanup = mountState({ ...at, title: "Your article", state: { kind: "error", title: "Couldn't open your article", text, retry: async () => {
        cleanup();
        cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the article…" } });
        const next = await loadArticle(ctx, st.articleId);
        cleanup();
        if ("error" in next && next.error) return failed(next.error);
        canvas.setState({ ...next, error: null }); // the agent reads the article from the canvas state
        cleanup = mount({ ...at, actions });
      } } });
    };
    failed(st.error);
  } else if (!hasText(st)) {
    // The agent is writing the first draft: bones in the editor's shape until its text arrives.
    const shown = mountState({ ...at, title: st.title, subtitle: st.collection, state: { kind: "loading", label: "The agent is writing…" } });
    const stop = canvas.onStateChange((next) => {
      if (!hasText(next)) return;
      stop(); shown();
      cleanup = mount({ ...at, actions });
    });
    cleanup = () => { stop(); shown(); };
  } else {
    cleanup = mount({ ...at, actions });
  }
  return () => cleanup();
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the preview card below.

type Result = ContentState | { error: string; articleId: string };

const COULDNT_OPEN = "Your saved article didn't load. It's still saved, so nothing is lost.";
// A new article, or a saved one. A failure goes back as data, so the agent can explain it.
const open = async ({ topic, articleId }: { topic?: string; articleId?: string }): Promise<Result> => {
  if (!articleId) return { kind: "Help article", collection: "Help center", title: topic ?? "", blocks: [{ id: "b1", type: "p", text: "" }] };
  return helpCenter.load(articleId).catch(() => ({ error: COULDNT_OPEN, articleId }));
};
const hasText = (st: Record<string, any>): boolean =>
  Boolean(st.blocks?.some((b: { text?: string; items?: string[] }) => (b.text ?? (b.items ?? []).join("")).trim()));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    draft_help_article: {
      // A new article: the agent writes blocks[] (in the state, not the chat) on its next turn.
      execute: async (args: { topic?: string; articleId?: string }): Promise<Result> => open(args),

      renderCanvas: (sdk: CanvasContext) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("CONTENT_EDITOR");
        ctx.setStatus("EDIT_MODE"); // the user and the agent both write, the first draft too
        const at = { root: ctx.host, head: ctx.header, canvas: ctx, eyebrow: "Help article" };
        let cleanup: Cleanup = () => {};
        const editor = (): void => {
          cleanup();
          cleanup = mount({ ...at, actions: {
            // The canvas forgets its state with the conversation: keep a copy in your app.
            onChange: (article) => helpCenter.saveDraft(article),
            // Publish: READ_MODE while it sends, so the agent doesn't edit mid-publish. Throw to show the error.
            publish: async (article) => {
              ctx.setStatus("READ_MODE");
              try { return await helpCenter.publish(article); } finally { ctx.setStatus("EDIT_MODE"); }
            },
          } });
        };
        const st = ctx.state;
        if (st.error) {
          // A saved article didn't load. Try again: bones while it loads, then the editor (or the error again).
          const failed = (text: string): void => {
            cleanup = mountState({ ...at, title: "Your article", state: { kind: "error", title: "Couldn't open your article", text, retry: async () => {
              cleanup();
              cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the article…" } });
              const next = await open({ articleId: st.articleId });
              if ("error" in next) { cleanup(); return failed("Still not loading. Try again in a minute."); }
              ctx.setState({ ...next, error: null }); // the agent reads the article from the canvas state
              editor();
            } } });
          };
          failed(st.error);
        } else if (!hasText(st)) {
          // The agent is writing the first draft: bones until its text arrives, then the editor.
          cleanup = mountState({ ...at, title: st.title, subtitle: st.collection, state: { kind: "loading", label: "The agent is writing…" } });
          const stop = ctx.onStateChange((next) => { if (hasText(next)) { stop(); editor(); } });
          const shown = cleanup;
          cleanup = () => { stop(); shown(); };
        } else editor();
        return () => cleanup();
      },
    },

    // Mobile: a read-only preview of the latest draft, or the error as a card.
    preview_help_article: {
      execute: async ({ articleId }: { articleId: string }): Promise<Result> => open({ articleId }),
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        if (!("error" in data)) return void mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } });
        mountMobileState({ root: host, head: header, eyebrow: "Help article", title: "Your article", state: { kind: "error", title: "Couldn't open your article", text: data.error } });
        readyState(data); // read-only: the agent goes on once it's shown
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the preview card below.

const COULDNT_OPEN = "Your saved article didn't load. It's still saved, so nothing is lost.";
// A new article, or a saved one. A failure goes back as data, so the agent can explain it.
const open = async ({ topic, articleId }) => {
  if (!articleId) return { kind: "Help article", collection: "Help center", title: topic ?? "", blocks: [{ id: "b1", type: "p", text: "" }] };
  return helpCenter.load(articleId).catch(() => ({ error: COULDNT_OPEN, articleId }));
};
const hasText = (st) =>
  Boolean(st.blocks?.some((b) => (b.text ?? (b.items ?? []).join("")).trim()));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    draft_help_article: {
      // A new article: the agent writes blocks[] (in the state, not the chat) on its next turn.
      execute: async (args) => open(args),

      renderCanvas: (sdk) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("CONTENT_EDITOR");
        ctx.setStatus("EDIT_MODE"); // the user and the agent both write, the first draft too
        const at = { root: ctx.host, head: ctx.header, canvas: ctx, eyebrow: "Help article" };
        let cleanup = () => {};
        const editor = () => {
          cleanup();
          cleanup = mount({ ...at, actions: {
            // The canvas forgets its state with the conversation: keep a copy in your app.
            onChange: (article) => helpCenter.saveDraft(article),
            // Publish: READ_MODE while it sends, so the agent doesn't edit mid-publish. Throw to show the error.
            publish: async (article) => {
              ctx.setStatus("READ_MODE");
              try { return await helpCenter.publish(article); } finally { ctx.setStatus("EDIT_MODE"); }
            },
          } });
        };
        const st = ctx.state;
        if (st.error) {
          // A saved article didn't load. Try again: bones while it loads, then the editor (or the error again).
          const failed = (text) => {
            cleanup = mountState({ ...at, title: "Your article", state: { kind: "error", title: "Couldn't open your article", text, retry: async () => {
              cleanup();
              cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the article…" } });
              const next = await open({ articleId: st.articleId });
              if ("error" in next) { cleanup(); return failed("Still not loading. Try again in a minute."); }
              ctx.setState({ ...next, error: null }); // the agent reads the article from the canvas state
              editor();
            } } });
          };
          failed(st.error);
        } else if (!hasText(st)) {
          // The agent is writing the first draft: bones until its text arrives, then the editor.
          cleanup = mountState({ ...at, title: st.title, subtitle: st.collection, state: { kind: "loading", label: "The agent is writing…" } });
          const stop = ctx.onStateChange((next) => { if (hasText(next)) { stop(); editor(); } });
          const shown = cleanup;
          cleanup = () => { stop(); shown(); };
        } else editor();
        return () => cleanup();
      },
    },

    // Mobile: a read-only preview of the latest draft, or the error as a card.
    preview_help_article: {
      execute: async ({ articleId }) => open({ articleId }),
      renderComponent: ({ data, host, header, readyState }) => {
        if (!("error" in data)) return void mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } });
        mountMobileState({ root: host, head: header, eyebrow: "Help article", title: "Your article", state: { kind: "error", title: "Couldn't open your article", text: data.error } });
        readyState(data); // read-only: the agent goes on once it's shown
      },
    },
  });
});
```

### content-canvas

```ts title="agent/ui/content-canvas.ts"
// Template: content-canvas. A CONTENT_EDITOR canvas where the user and the agent write one article together: a help article, a blog post, release notes.

export type ContentBlockType = "p" | "h2" | "h3" | "ul" | "ol" | "quote" | "callout";

export interface ContentBlock {
  /** Stable id. The agent keeps it when it rewrites a block, so the editor can show what it changed. */
  id: string;
  /** p (paragraph), h2 (heading), h3 (subheading), ul or ol (lists), quote or callout. */
  type: ContentBlockType;
  /** The text of every type but lists. Inline markdown: **bold**, *italic*, `code`, [label](https://…). */
  text?: string;
  /** A list's items (ul, ol), each with the same inline markdown. */
  items?: string[];
}

/** What the agent reads and edits. About 450 words fit in what the agent gets whole (about 3 KB). */
export interface ContentState {
  /** The canvas header (setTitle, up to 80 characters). Default: "<kind>: <title>". */
  canvasTitle?: string;
  /** What is being written, on the badge: "Help article", "Blog post". */
  kind?: string;
  /** Where it lives, as a breadcrumb: "Help center / Reports". Display only. */
  collection?: string;
  /** The headline. */
  title: string;
  /** One or two sentences under the headline: the summary readers see in search and lists. */
  subtitle?: string;
  /** The byline. Display only. */
  author?: string;
  /** Shown under the byline. Display only: the user asks the agent to change them. */
  tags?: string[];
  blocks: ContentBlock[];
  /** When the user last published it (ISO time). The editor sets it, so the agent knows. */
  publishedAt?: string;
  /** The published article's address, from your app's publish(). */
  url?: string;
}

export interface ContentActions {
  /** Called each time the draft is shared with the agent (debounced). Keep a copy in your app here if you need one. */
  onChange?(state: ContentState): void;
  /** Publishes (or updates) the article in your app. With it the toolbar shows Publish. Resolve with its address; throw to show the error. */
  publish?(state: ContentState): Promise<{ url?: string } | void>;
}

export const meta = {
  id: "content-canvas",
  title: "Article editor",
  surface: "canvas",
  canvasType: "CONTENT_EDITOR",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "The user and the agent write one article together over several turns: a help article, a blog post, release notes, an announcement. The user writes and formats in the canvas, and asks the agent to draft, shorten or rewrite parts of it.",
  whenNotToUse: "A one-line reply or a short answer (the chat). Structured fields with rules (form canvas). Text the agent writes once and the user never edits (a chat card). Mobile: the canvas isn't available; use the preview card (mountMobile).",
};

const CSS = `
.fsk-ce { min-height: 100%; background: var(--k-paper); container: fsk-ce / inline-size; }

/* Toolbar */
.fsk-ce-bar {
  position: sticky; top: 0; z-index: 3; border-bottom: 1px solid var(--k-divider);
  background: color-mix(in srgb, var(--k-paper) 92%, transparent);
  -webkit-backdrop-filter: saturate(1.4) blur(10px); backdrop-filter: saturate(1.4) blur(10px);
}
.fsk-ce-bar-in { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; min-height: 48px; padding: 7px 16px; font-size: .86em; color: var(--k-text-2); }
.fsk-ce-fmt { position: relative; display: flex; align-items: center; gap: 2px; }
.fsk-ce-type {
  appearance: none; height: 30px; padding: 0 26px 0 10px; margin-right: 4px; border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  background: var(--k-paper) no-repeat right 8px center / 10px; color: var(--k-text); font: inherit; font-weight: 500; cursor: pointer;
  background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(-45deg, transparent 50%, currentColor 50%);
  background-size: 4px 4px, 4px 4px; background-position: right 13px center, right 9px center;
}
.fsk-ce-type:disabled { color: var(--k-text-2); cursor: default; opacity: .6; }
.fsk-ce-tool {
  appearance: none; display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0;
  border-radius: var(--k-r-md); background: transparent; color: var(--k-text-2); cursor: pointer;
}
.fsk-ce-tool:hover:not(:disabled) { background: var(--k-hover); color: var(--k-text); }
.fsk-ce-tool[aria-pressed="true"] { background: var(--k-tint); color: var(--k-primary); }
.fsk-ce-tool:disabled { opacity: .4; cursor: default; }
.fsk-ce-vsep { width: 1px; height: 18px; margin: 0 4px; background: var(--k-divider); }
.fsk-ce-right { display: flex; align-items: center; gap: 10px; margin-left: auto; white-space: nowrap; }
.fsk-ce-note {
  appearance: none; display: inline-flex; align-items: center; gap: 5px; padding: 3px 10px 3px 8px; border: 0; border-radius: calc(var(--k-r) * 100);
  background: var(--k-tint); color: var(--k-primary); font: inherit; font-weight: 600; cursor: pointer; animation: fsk-in .25s var(--k-ease) both;
}
.fsk-ce-note:hover { background: var(--k-tint-2); }
.fsk-ce-status { display: inline-flex; align-items: center; gap: 6px; }
.fsk-ce-status[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-ce-status[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-ce-status[data-s="error"] { color: var(--k-error); }
.fsk-ce-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--k-primary); animation: fsk-ce-pulse 1.1s ease-in-out infinite; }
.fsk-ce-publish { min-height: 32px; padding: 0 14px; }
.fsk-ce-publish .fsk-ce-spin { width: 13px; height: 13px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: fsk-spin .7s linear infinite; }
.fsk-ce-alert {
  display: flex; align-items: center; gap: 8px; padding: 8px 16px; border-top: 1px solid var(--k-divider);
  background: color-mix(in srgb, var(--k-error) 8%, var(--k-paper)); color: var(--k-text); font-size: .86em;
}
.fsk-ce-alert > .fsk-icon { flex: none; color: var(--k-error); }
.fsk-ce-alert > span { flex: 1; }

/* Link box */
.fsk-ce-linkbox {
  position: absolute; top: calc(100% + 8px); left: 0; z-index: 4; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; width: 340px; max-width: calc(100cqw - 32px);
  padding: 8px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); animation: fsk-in .18s var(--k-ease) both;
}
.fsk-ce-linkbox input {
  flex: 1; min-width: 0; height: 32px; padding: 0 10px; border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  background: var(--k-paper); color: var(--k-text); font: inherit; outline: none;
}
.fsk-ce-linkbox input:focus { border-color: var(--k-primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 14%, transparent); }
.fsk-ce-linkbox .fsk-btn { min-height: 32px; padding: 0 10px; }
.fsk-ce-linkerr { flex-basis: 100%; margin: 0; color: var(--k-error); font-size: .93em; }

/* Page */
.fsk-ce-wrap { display: flex; justify-content: center; gap: 48px; padding: 0 36px; }
.fsk-ce-doc { flex: 1; min-width: 0; max-width: 720px; padding: 30px 0 72px; }
.fsk-ce-top { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin-bottom: 18px; font-size: .86em; color: var(--k-text-2); }
.fsk-ce-crumbs { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 2px; }
.fsk-ce-crumbs .fsk-icon { opacity: .6; }
.fsk-ce-state { margin-left: auto; }
.fsk-ce-field {
  display: block; width: 100%; min-height: 1lh; margin: 0; padding: 0; border: 0; outline: none; background: transparent;
  color: inherit; font: inherit; letter-spacing: inherit; resize: none; overflow: hidden; field-sizing: content;
}
.fsk-ce-field::placeholder { color: var(--k-text-2); opacity: .7; }
.fsk-ce-title { font-size: 2.15em; font-weight: 700; letter-spacing: -0.028em; line-height: 1.18; }
.fsk-ce-dek { margin-top: 10px; font-size: 1.22em; line-height: 1.5; color: var(--k-text-2); }
.fsk-ce-by { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin-top: 18px; font-size: .93em; color: var(--k-text-2); }
.fsk-ce-by b { font-weight: 600; color: var(--k-text); }
.fsk-ce-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-left: auto; }
.fsk-ce-tag { padding: 1px 9px; border: 1px solid var(--k-border); border-radius: calc(var(--k-r) * 100); font-size: .86em; white-space: nowrap; }
.fsk-ce-rule { height: 1px; margin: 26px 0 18px; background: var(--k-divider); border: 0; }

/* Blocks */
.fsk-ce-body { font-size: 1.07em; line-height: 1.72; }
.fsk-ce-block { position: relative; border-radius: var(--k-r-md); transition: background-color .3s; }
.fsk-ce-block + .fsk-ce-block { margin-top: .8em; }
.fsk-ce-block[data-type="h2"]:not(:first-child) { margin-top: 1.7em; }
.fsk-ce-block[data-type="h3"]:not(:first-child) { margin-top: 1.3em; }
.fsk-ce-block[data-type="h2"] + .fsk-ce-block, .fsk-ce-block[data-type="h3"] + .fsk-ce-block { margin-top: .45em; }
.fsk-ce-edit { margin: 0; min-height: 1lh; outline: none; overflow-wrap: anywhere; white-space: pre-wrap; caret-color: var(--k-primary); }
.fsk-ce-edit:empty::before { content: attr(data-ph); color: var(--k-text-2); opacity: 0; pointer-events: none; }
.fsk-ce-edit:focus:empty::before, .fsk-ce-body[data-blank] .fsk-ce-edit:empty::before { opacity: .7; }
h2.fsk-ce-edit { font-size: 1.42em; font-weight: 680; letter-spacing: -0.018em; line-height: 1.3; }
h3.fsk-ce-edit { font-size: 1.14em; font-weight: 650; letter-spacing: -0.01em; line-height: 1.4; }
ul.fsk-ce-edit, ol.fsk-ce-edit { padding-left: 1.5em; }
.fsk-ce-edit li { padding-left: .25em; min-height: 1lh; }
.fsk-ce-edit li + li { margin-top: .3em; }
.fsk-ce-edit li::marker { color: var(--k-text-2); font-variant-numeric: tabular-nums; }
blockquote.fsk-ce-edit { padding: 2px 0 2px 18px; border-left: 3px solid var(--k-border); font-size: 1.08em; font-style: italic; color: color-mix(in srgb, var(--k-text) 82%, var(--k-paper)); }
.fsk-ce-callout { display: flex; gap: 12px; padding: 14px 16px; border-radius: var(--k-r-lg); background: var(--k-tint); }
.fsk-ce-callout > .fsk-icon { flex: none; margin-top: .3em; color: var(--k-primary); }
.fsk-ce-callout > .fsk-ce-edit { flex: 1; min-width: 0; }
.fsk-ce-edit strong, .fsk-ce-edit b { font-weight: 650; }
.fsk-ce-edit a, .fsk-cec a { color: var(--k-primary); text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px; }
.fsk-ce-edit code, .fsk-cec code { padding: .1em .35em; border-radius: calc(var(--k-r-md) - 2px); background: var(--k-sunken); font: .88em var(--k-mono); }

/* The agent's edits */
.fsk-ce-block::before { content: ""; position: absolute; left: -16px; top: .3em; bottom: .3em; width: 3px; border-radius: 3px; background: var(--k-primary); opacity: 0; transition: opacity .2s; }
.fsk-ce-block[data-agent]::before { opacity: 1; }
.fsk-ce-flash { animation: fsk-ce-flash 2.6s var(--k-ease); }
.fsk-ce-mark {
  position: absolute; right: 0; top: -1.15em; z-index: 1; display: none; align-items: center; gap: 4px; padding: 1px 8px 1px 6px;
  border-radius: calc(var(--k-r) * 100); font-size: .68em; font-style: normal; font-weight: 600; line-height: 1.6; white-space: nowrap;
  color: var(--k-primary); background: var(--k-tint); box-shadow: 0 0 0 2px var(--k-paper);
}
.fsk-ce-block[data-agent] > .fsk-ce-mark { display: inline-flex; animation: fsk-in .3s var(--k-ease) both; }

.fsk-ce-add {
  appearance: none; display: inline-flex; align-items: center; gap: 6px; margin-top: 22px; padding: 6px 12px;
  border: 1px dashed var(--k-border); border-radius: var(--k-r-md); background: none; color: var(--k-text-2); font: inherit; font-size: .86em; cursor: pointer;
}
.fsk-ce-add:hover { border-style: solid; color: var(--k-text); background: var(--k-hover); }
.fsk-ce-hint { display: flex; align-items: flex-start; gap: 7px; margin: 18px 0 0; font-size: .86em; line-height: 1.5; color: var(--k-text-2); }
.fsk-ce-hint .fsk-icon { flex: none; margin-top: .15em; }
.fsk-ce-hint kbd { padding: 0 5px; border: 1px solid var(--k-border); border-radius: 4px; font: .93em var(--k-mono); }
.fsk-ce-tool:focus-visible, .fsk-ce-add:focus-visible, .fsk-ce-note:focus-visible, .fsk-ce-type:focus-visible, .fsk-ce-toc a:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

/* Outline: on a wide canvas */
.fsk-ce-toc { display: none; flex: none; width: 190px; align-self: flex-start; position: sticky; top: 72px; padding-top: 34px; font-size: .86em; }
.fsk-ce-toc p { margin: 0 0 8px; font-size: .86em; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--k-text-2); }
.fsk-ce-toc a { display: block; padding: 4px 0 4px 12px; border-left: 2px solid var(--k-divider); color: var(--k-text-2); text-decoration: none; line-height: 1.35; }
.fsk-ce-toc a[data-l="3"] { padding-left: 24px; }
.fsk-ce-toc a:hover { color: var(--k-text); border-left-color: var(--k-text-2); }
@container fsk-ce (min-width: 1000px) { .fsk-ce-toc:not(:empty) { display: block; } }
@container fsk-ce (max-width: 720px) { .fsk-ce-words, .fsk-ce-long { display: none; } }
@container fsk-ce (max-width: 560px) {
  .fsk-ce-bar-in { padding: 6px 12px; }
  .fsk-ce-wrap { padding: 0 18px; }
  .fsk-ce-doc { padding-top: 22px; }
  .fsk-ce-title { font-size: 1.7em; }
  .fsk-ce-dek { font-size: 1.1em; }
  .fsk-ce-block::before { left: -11px; }
}
@keyframes fsk-ce-flash { 0%, 25% { background-color: var(--k-tint-2); } }
@keyframes fsk-ce-pulse { 50% { opacity: .35; transform: scale(.75); } }
@media (prefers-reduced-motion: reduce) { .fsk-ce-block[data-agent] { background: var(--k-tint); } .fsk-ce-dot, .fsk-ce-publish .fsk-ce-spin { animation: none; } }

/* Mobile preview card */
.fsk-cec .fsk-cec-dek { margin: -4px 0 10px; color: var(--k-text-2); line-height: 1.45; }
.fsk-cec .fsk-cec-doc { position: relative; max-height: 250px; overflow: hidden; padding: 12px 14px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; line-height: 1.55; }
.fsk-cec .fsk-cec-doc::after { content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 56px; background: linear-gradient(to bottom, transparent, var(--k-sunken)); }
.fsk-cec h4 { margin: 12px 0 4px; font-size: 1.02em; font-weight: 650; }
.fsk-cec h4:first-child, .fsk-cec p:first-child { margin-top: 0; }
.fsk-cec p, .fsk-cec ul, .fsk-cec ol { margin: 0 0 8px; }
.fsk-cec ul, .fsk-cec ol { padding-left: 1.3em; }
.fsk-cec .fsk-cec-callout { padding: 8px 10px; border-radius: var(--k-r-md); background: var(--k-tint); }
.fsk-cec blockquote { margin: 0 0 8px; padding-left: 10px; border-left: 3px solid var(--k-border); font-style: italic; }
.fsk-cec .fsk-cec-foot { display: flex; align-items: center; gap: 6px; margin: 12px 0 0; font-size: .79em; color: var(--k-text-2); }

/* States (mountState): the editor's own page, with a skeleton in its shape or a centered block */
.fsk-ce-st { display: flex; flex-direction: column; }
.fsk-ce-st > .fsk-ce-wrap { flex: 1; }
.fsk-ce-st .fsk-ce-doc { display: flex; flex-direction: column; }
.fsk-ce-st h2.fsk-ce-title { margin: 0; }
.fsk-ce-st .fsk-ce-title .fsk-bone { margin: 8px 0; }
.fsk-ce-sk-pill { border-radius: calc(var(--k-r) * 100); }
.fsk-ce-st .fsk-ce-fmt { gap: 6px; }
.fsk-ce-sk-round { border-radius: 50%; }
.fsk-ce-sk-lines { display: flex; flex-direction: column; gap: 12px; padding: 6px 0; }
.fsk-ce-sk-h { margin: 20px 0 6px; }
.fsk-ce-sk-li { display: flex; align-items: center; gap: 12px; }
.fsk-ce-sk-callout { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; padding: 16px; border-radius: var(--k-r-lg); background: var(--k-tint); }
.fsk-ce-st-box { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 0 12%; }
.fsk-ce-st-panel { width: 100%; max-width: 460px; animation: fsk-in .32s var(--k-ease) both; }
.fsk-ce-st-panel > .fsk-error { padding: 20px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); }
.fsk-ce-st-panel > .fsk-empty { padding: 8px 0; }
.fsk-cec .fsk-cec-doc .fsk-bone { background: color-mix(in srgb, var(--k-text) 9%, var(--k-sunken)); }
.fsk-cec .fsk-cec-doc.fsk-sk-lines { max-height: none; }
`;

const SHARE_DELAY_MS = 600;
const TYPES: ContentBlockType[] = ["p", "h2", "h3", "ul", "ol", "quote", "callout"];
const TYPE_LABEL: Record<ContentBlockType, string> = { p: "Text", h2: "Heading", h3: "Subheading", ul: "Bulleted list", ol: "Numbered list", quote: "Quote", callout: "Callout" };
const PLACEHOLDER: Record<ContentBlockType, string> = {
  p: "Write, or type ## for a heading, - for a list", h2: "Heading", h3: "Subheading", ul: "List item", ol: "List item", quote: "Quote", callout: "Something readers shouldn't miss",
};
/** Typed at the start of a paragraph, followed by a space: the block becomes this type. */
const SHORTCUTS: [RegExp, ContentBlockType][] = [[/^###[  ]/, "h3"], [/^##[  ]/, "h2"], [/^[-*][  ]/, "ul"], [/^1\.[  ]/, "ol"], [/^>[  ]/, "quote"]];
let seq = 0;

type Status = "saved" | "pending" | "partial" | "error";
interface Block {
  id: string;
  type: ContentBlockType;
  /** The block's row (the agent's mark lives here). */
  el: HTMLElement;
  /** The contenteditable element. */
  edit: HTMLElement;
}

const isList = (t: ContentBlockType): boolean => t === "ul" || t === "ol";
const newId = (): string => `b${Date.now().toString(36)}${(++seq).toString(36)}`;
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);

// ---------- inline markdown: **bold**, *italic*, `code`, [label](url) ----------

/** Links the editor keeps: web, mail and your app's own paths. Anything else stays text. */
function safeHref(raw: string | null | undefined): string | null {
  const v = (raw ?? "").trim();
  return /^(https?:\/\/|mailto:|\/(?!\/))/i.test(v) ? v : null;
}

function findClose(md: string, mark: string, from: number): number {
  for (let j = from; j < md.length; j++) {
    if (md[j] === "\\") { j++; continue; }
    if (mark === "*" && md.startsWith("**", j)) { j++; continue; }
    if (md.startsWith(mark, j)) return j;
  }
  return -1;
}

/** Inline markdown to DOM nodes. Text nodes only, never HTML, so the agent's text can't inject markup. */
function inline(md: string): Node[] {
  const out: Node[] = [];
  let i = 0;
  let buf = "";
  const flush = (): void => { if (buf) { out.push(document.createTextNode(buf)); buf = ""; } };
  while (i < md.length) {
    const c = md[i];
    if (c === "\\" && i + 1 < md.length) { buf += md[i + 1]; i += 2; continue; }
    if (c === "\n") { flush(); out.push(h("br")); i++; continue; }
    if (c === "`") {
      const end = md.indexOf("`", i + 1);
      if (end > i + 1) { flush(); out.push(h("code", {}, md.slice(i + 1, end))); i = end + 1; continue; }
    }
    if (md.startsWith("**", i)) {
      const end = findClose(md, "**", i + 2);
      if (end > i + 2) { flush(); out.push(h("strong", {}, inline(md.slice(i + 2, end)))); i = end + 2; continue; }
    }
    if (c === "*") {
      const end = findClose(md, "*", i + 1);
      if (end > i + 1) { flush(); out.push(h("em", {}, inline(md.slice(i + 1, end)))); i = end + 1; continue; }
    }
    if (c === "[") {
      const m = /^\[([^\]\n]+)\]\(([^)\s]+)\)/.exec(md.slice(i));
      if (m) {
        const href = safeHref(m[2]);
        flush();
        out.push(...(href ? [h("a", { href, rel: "noopener noreferrer", target: "_blank" }, inline(m[1]))] : inline(m[1])));
        i += m[0].length;
        continue;
      }
    }
    buf += c;
    i++;
  }
  flush();
  return out;
}

/** Moves the spaces around a span outside its markers: "** bold**" isn't markdown, " **bold**" is. */
function wrap(mark: string, s: string): string {
  const m = /^(\s*)([\s\S]*?)(\s*)$/.exec(s);
  return m && m[2] ? `${m[1]}${mark}${m[2]}${mark}${m[3]}` : s;
}

/** The DOM the user edited, back to inline markdown. Reads what browsers write for bold and italic (b, strong, styles). */
function toMd(node: Node): string {
  let out = "";
  node.childNodes.forEach((n) => {
    if (n.nodeType === Node.TEXT_NODE) { out += (n.nodeValue ?? "").replace(/ /g, " ").replace(/([\\`*[\]])/g, "\\$1"); return; }
    if (n.nodeType !== Node.ELEMENT_NODE) return;
    const el = n as HTMLElement;
    const tag = el.tagName;
    if (tag === "BR") { out += "\n"; return; }
    if (tag === "CODE") { out += wrap("`", (el.textContent ?? "").replace(/`/g, "")); return; }
    if ((tag === "DIV" || tag === "P") && out && !out.endsWith("\n")) out += "\n";
    let s = toMd(el);
    if (tag === "A") { const href = safeHref(el.getAttribute("href")); out += href && s.trim() ? `[${s}](${href})` : s; return; }
    const weight = el.style.fontWeight;
    if (tag === "I" || tag === "EM" || el.style.fontStyle === "italic") s = wrap("*", s);
    if (tag === "B" || tag === "STRONG" || weight === "bold" || Number(weight) >= 600) s = wrap("**", s);
    out += s;
  });
  return out;
}

const tidy = (md: string): string => md.replace(/\n+$/, "");
/** Markdown to plain text, for counting words and the outline. */
const plain = (md: string): string => md.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\\(.)/g, "$1").replace(/[*`]/g, "");

/** Fills the gaps the agent may leave (no id, an unknown type, text where items belong) so the editor never breaks. */
function normalize(raw: unknown): ContentState {
  const s = (raw ?? {}) as Partial<ContentState>;
  const list = Array.isArray(s.blocks) ? s.blocks : [];
  const blocks = list.map((x, i): ContentBlock => {
    const type: ContentBlockType = TYPES.includes(x?.type) ? x.type : "p";
    const id = String(x?.id ?? `b${i + 1}`);
    if (isList(type)) {
      const items = Array.isArray(x?.items) ? x.items.map((t) => String(t ?? "")) : String(x?.text ?? "").split("\n");
      return { id, type, items: items.length ? items : [""] };
    }
    return { id, type, text: x?.text != null ? String(x.text) : Array.isArray(x?.items) ? x.items.join("\n") : "" };
  });
  return { ...s, title: String(s.title ?? ""), subtitle: s.subtitle == null ? undefined : String(s.subtitle), blocks: blocks.length ? blocks : [{ id: "b1", type: "p", text: "" }] };
}

/** A block with another type: text becomes list items line by line, and back. */
function retype(b: ContentBlock, type: ContentBlockType): ContentBlock {
  if (isList(type)) return { id: b.id, type, items: b.items ?? (b.text ?? "").split("\n") };
  return { id: b.id, type, text: b.text ?? (b.items ?? []).join("\n") };
}

const words = (s: ContentState): number =>
  [s.title, s.subtitle ?? "", ...s.blocks.flatMap((b) => [b.text ?? "", ...(b.items ?? [])])].map(plain).join(" ").match(/\S+/g)?.length ?? 0;
const readTime = (n: number): string => `${Math.max(1, Math.round(n / 230))} min read`;
const kindIcon = (kind?: string): IconName => (/mail/i.test(kind ?? "") ? "mail" : "doc");

/** Writes a field without moving the caret: text before it stays put, text after it shifts with the change. */
function setValue(el: HTMLTextAreaElement, value: string, active: Element | null): void {
  if (el.value === value) return;
  if (el !== active) { el.value = value; return; }
  const [start, end] = remap(el.value, value, el.selectionStart, el.selectionEnd);
  const dir = el.selectionDirection;
  el.value = value;
  el.setSelectionRange(start, end, dir);
}

/** Where a caret at `start..end` in `old` lands in `next`: the common start and end of the two texts stay anchored. */
function remap(old: string, next: string, start: number, end: number): [number, number] {
  let p = 0;
  while (p < old.length && p < next.length && old[p] === next[p]) p++;
  let q = 0;
  while (q < old.length - p && q < next.length - p && old[old.length - 1 - q] === next[next.length - 1 - q]) q++;
  const map = (c: number): number => (c <= p ? c : c >= old.length - q ? next.length - (old.length - c) : next.length - q);
  return [map(start), map(end)];
}

/** Draws a block's contents from its markdown. */
function fillBlock(edit: HTMLElement, b: ContentBlock): void {
  if (isList(b.type)) edit.replaceChildren(...(b.items?.length ? b.items : [""]).map((t) => h("li", {}, t ? inline(t) : h("br"))));
  else edit.replaceChildren(...inline(b.text ?? ""));
}

/** One block, read-only: the mobile card. */
function staticBlock(b: ContentBlock): HTMLElement {
  if (isList(b.type)) return h(b.type, {}, (b.items ?? []).map((t) => h("li", {}, inline(t))));
  if (b.type === "h2" || b.type === "h3") return h("h4", {}, inline(b.text ?? ""));
  if (b.type === "quote") return h("blockquote", {}, inline(b.text ?? ""));
  return h("p", { class: b.type === "callout" ? "fsk-cec-callout" : null }, inline(b.text ?? ""));
}

export interface ContentCanvasProps {
  root: HTMLElement;
  head: StyleHost;
  /** The canvas: the in-page renderCanvas ctx or a hosted ctx.canvas. Its state wins over data. */
  canvas?: CanvasApi;
  data?: ContentState;
  actions?: ContentActions;
}

export interface ContentCardProps {
  root: HTMLElement;
  head: StyleHost;
  data: ContentState;
  api?: CardApi;
}

/**
 * Desktop canvas, EDIT_MODE. The user's writing is shared 600 ms after they stop and on blur.
 * The agent's edits arrive through onStateChange and are written in place, keeping the caret.
 */
export function mount({ root, head, canvas, data, actions }: ContentCanvasProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const native = !!win.CSS?.supports?.("field-sizing", "content");
  const rootNode = root.getRootNode();
  const shadow = rootNode instanceof win.ShadowRoot ? rootNode : null;
  let shared = normalize(structuredClone(canvas?.state ?? data)); // what the agent has
  let model = structuredClone(shared); // what the user sees, with writing not shared yet
  let blocks: Block[] = [];
  let timer = 0;
  let status: Status | null = null;
  let lastResult: Status = "saved";
  let lastTitle = "";
  let current: Block | null = null; // the block the toolbar acts on
  let caret: [number, number] | null = null; // the caret in it, kept while the toolbar has focus
  let publishing = false;
  let editedSincePublish = false;
  let linkRange: Range | null = null;
  const activeEl = (): Element | null => (shadow ?? doc).activeElement;

  // ---------- selection (works inside a shadow root too) ----------
  function selection(): Selection | null {
    // Chrome and Firefox read a selection inside a shadow root from the root itself; Safari from the document.
    const fromRoot: unknown = shadow && Reflect.get(shadow, "getSelection");
    const own = typeof fromRoot === "function" ? (fromRoot.call(shadow) as Selection | null) : null;
    return own ?? doc.getSelection();
  }
  function range(): Range | null {
    const sel = selection();
    if (!sel) return null;
    const inside = sel.rangeCount > 0 && root.contains(sel.getRangeAt(0).startContainer);
    if (!inside && shadow && typeof sel.getComposedRanges === "function") {
      const [r] = sel.getComposedRanges({ shadowRoots: [shadow] });
      if (!r || !root.contains(r.startContainer)) return null;
      const out = doc.createRange();
      out.setStart(r.startContainer, r.startOffset);
      out.setEnd(r.endContainer, r.endOffset);
      return out;
    }
    return inside ? sel.getRangeAt(0) : null;
  }
  function offsetOf(el: HTMLElement, node: Node, offset: number): number {
    const r = doc.createRange();
    r.selectNodeContents(el);
    try { r.setEnd(node, offset); } catch { return 0; }
    return r.toString().length;
  }
  function caretIn(el: HTMLElement): [number, number] | null {
    const r = range();
    if (!r || !el.contains(r.startContainer)) return null;
    return [offsetOf(el, r.startContainer, r.startOffset), offsetOf(el, r.endContainer, r.endOffset)];
  }
  function pointAt(el: HTMLElement, at: number): [Node, number] {
    const walker = doc.createTreeWalker(el, NodeFilter.SHOW_TEXT);
    let left = at;
    let last: Node | null = null;
    for (let n = walker.nextNode(); n; n = walker.nextNode()) {
      const len = n.nodeValue?.length ?? 0;
      if (left <= len) return [n, left];
      left -= len;
      last = n;
    }
    if (last) return [last, last.nodeValue?.length ?? 0];
    const li = el.querySelector("li");
    return li ? [li, 0] : [el, 0];
  }
  function placeCaret(el: HTMLElement, start: number, end = start): void {
    el.focus({ preventScroll: true });
    const [a, ao] = pointAt(el, start);
    const [b, bo] = pointAt(el, end);
    try { selection()?.setBaseAndExtent(a, ao, b, bo); } catch { /* the block moved: the caret stays where the browser put it */ }
  }
  const textLen = (el: HTMLElement): number => (el.textContent ?? "").length;

  // ---------- title and summary (one line each) ----------
  function field(cls: string, label: string, placeholder: string, value: string): HTMLTextAreaElement {
    const ta = h<HTMLTextAreaElement>("textarea", { class: `fsk-ce-field ${cls}`, rows: 1, "aria-label": label, placeholder, spellcheck: "true" });
    ta.value = value;
    return ta;
  }
  /** Auto-grow where field-sizing isn't supported. */
  function fit(ta: HTMLTextAreaElement): void {
    if (native || !ta.isConnected) return;
    ta.style.height = "auto";
    ta.style.height = `${ta.scrollHeight}px`;
  }
  const mark = (): HTMLElement => h("span", { class: "fsk-ce-mark", "aria-hidden": "true" }, icon("sparkle", 11), "Edited by the agent");
  const titleEl = field("fsk-ce-title", "Title", "Untitled", model.title);
  const dekEl = field("fsk-ce-dek", "Summary", "Add a one-line summary", model.subtitle ?? "");
  const titleBlock = h("div", { class: "fsk-ce-block fsk-ce-block--title" }, mark(), titleEl);
  const dekBlock = h("div", { class: "fsk-ce-block fsk-ce-block--dek" }, mark(), dekEl);

  // ---------- blocks ----------
  function makeBlock(b: ContentBlock): Block {
    const tag = isList(b.type) ? b.type : b.type === "h2" || b.type === "h3" ? b.type : b.type === "quote" ? "blockquote" : "div";
    const edit = h(tag, {
      class: "fsk-ce-edit", contenteditable: "true", role: "textbox", "aria-multiline": "true", spellcheck: "true", "data-ph": PLACEHOLDER[b.type],
    });
    fillBlock(edit, b);
    const inner: Child = b.type === "callout" ? h("div", { class: "fsk-ce-callout" }, icon("info", 18), edit) : edit;
    const el = h("div", { class: "fsk-ce-block", "data-id": b.id, "data-type": b.type }, mark(), inner);
    return { id: b.id, type: b.type, el, edit };
  }
  function readBlock(b: Block): ContentBlock {
    if (isList(b.type)) {
      const items = Array.from(b.edit.children).filter((e) => e.tagName === "LI").map((li) => tidy(toMd(li)));
      return { id: b.id, type: b.type, items: items.length ? items : [""] };
    }
    return { id: b.id, type: b.type, text: tidy(toMd(b.edit)) };
  }
  function relabel(): void {
    blocks.forEach((b, i) => b.edit.setAttribute("aria-label", `${TYPE_LABEL[b.type]}, block ${i + 1} of ${blocks.length}`));
    bodyEl.toggleAttribute("data-blank", blocks.length === 1 && !textLen(blocks[0].edit));
  }
  function insertBlock(b: ContentBlock, at: number): Block {
    const nb = makeBlock(b);
    model.blocks.splice(at, 0, b);
    blocks.splice(at, 0, nb);
    bodyEl.insertBefore(nb.el, blocks[at + 1]?.el ?? null);
    relabel();
    return nb;
  }
  function removeBlock(i: number): void {
    const [gone] = blocks.splice(i, 1);
    model.blocks.splice(i, 1);
    gone.el.remove();
    if (current === gone) current = null;
    relabel();
  }
  /** Replaces a block with the same text as another type, keeping the caret. */
  function convert(b: Block, type: ContentBlockType, at: [number, number] | null): void {
    const i = blocks.indexOf(b);
    if (i < 0 || b.type === type) return;
    const next = retype(readBlock(b), type);
    const nb = makeBlock(next);
    b.el.replaceWith(nb.el);
    blocks[i] = nb;
    model.blocks[i] = next;
    current = nb;
    relabel();
    const len = textLen(nb.edit);
    placeCaret(nb.edit, Math.min(at?.[0] ?? len, len), Math.min(at?.[1] ?? len, len));
    sync(nb);
  }
  const blockOf = (node: Node | null): Block | undefined => (node ? blocks.find((b) => b.edit === node || b.edit.contains(node)) : undefined);

  // ---------- toolbar ----------
  const typeSel = h<HTMLSelectElement>("select", { class: "fsk-ce-type", "aria-label": "Block type", disabled: true },
    TYPES.map((t) => h("option", { value: t }, TYPE_LABEL[t])));
  // Toolbar buttons keep the selection in the text: mousedown doesn't take focus.
  const keep = (e: Event): void => e.preventDefault();
  const tool = (ic: IconName, label: string, onclick: () => void, keys?: string): HTMLButtonElement =>
    h<HTMLButtonElement>("button", { class: "fsk-ce-tool", type: "button", "aria-label": label, title: keys ? `${label} (${keys})` : label, "aria-pressed": "false", disabled: true, onmousedown: keep, onclick }, icon(ic, 16));
  const boldBtn = tool("bold", "Bold", () => format("bold"), "⌘B");
  const italicBtn = tool("italic", "Italic", () => format("italic"), "⌘I");
  const linkBtn = tool("link", "Link", () => openLink(), "⌘K");
  linkBtn.removeAttribute("aria-pressed");
  linkBtn.setAttribute("aria-haspopup", "dialog");
  const fmt = h("div", { class: "fsk-ce-fmt", role: "toolbar", "aria-label": "Formatting" }, typeSel, boldBtn, italicBtn, linkBtn);
  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const statusEl = h("span", { class: "fsk-ce-status" });
  const wordsEl = h("span", { class: "fsk-ce-words fsk-num" });
  const note = h<HTMLButtonElement>("button", { class: "fsk-ce-note", type: "button", hidden: true, onclick: () => showFirstEdit() });
  const publishBtn = actions?.publish ? h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary fsk-ce-publish", type: "button", onclick: () => void publish() }) : null;
  const alertEl = h("div", { class: "fsk-ce-alert", role: "alert", hidden: true });
  const statePill = h("span", { class: "fsk-ce-state" });
  const readEl = h("span", { class: "fsk-num" });
  const bylineEl = h("div", { class: "fsk-ce-by" });
  const topEl = h("div", { class: "fsk-ce-top" });
  const toc = h("nav", { class: "fsk-ce-toc", "aria-label": "Outline" });
  const bodyEl = h("div", { class: "fsk-ce-body" });

  function setStatus(s: Status): void {
    if (status === s) return;
    status = s;
    statusEl.dataset.s = s;
    statusEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-ce-dot", "aria-hidden": "true" }), "Saving…"]
      : s === "partial" ? [icon("alert", 14), "Too long: the agent sees part of it"]
      : s === "error" ? [icon("alert", 14), "Not shared. Keep writing to retry."]
      : [icon("check", 14), h("span", {}, "Saved", h("span", { class: "fsk-ce-long" }, " for the agent"))]));
  }
  function updateCounts(): void {
    const n = words(model);
    wordsEl.textContent = `${n.toLocaleString()} ${n === 1 ? "word" : "words"}`;
    readEl.textContent = readTime(n);
  }
  function updateHeader(): void {
    const tone: Tone = !model.publishedAt ? "neutral" : editedSincePublish ? "warning" : "success";
    statePill.replaceChildren(pill(!model.publishedAt ? "Draft" : editedSincePublish ? "Unpublished changes" : "Published", tone));
    topEl.replaceChildren(h("span", { class: "fsk-badge fsk-badge--agent" }, icon(kindIcon(model.kind), 12), model.kind ?? "Draft"));
    const crumbs = crumbsOf(model.collection);
    if (crumbs) topEl.append(crumbs);
    topEl.append(statePill);
    bylineEl.replaceChildren();
    if (model.author) bylineEl.append(avatar(model.author, { size: 26 }), h("b", {}, model.author), h("span", { "aria-hidden": "true" }, "·"));
    bylineEl.append(readEl);
    if (model.tags?.length) bylineEl.append(h("span", { class: "fsk-ce-tags" }, model.tags.map((t) => h("span", { class: "fsk-ce-tag" }, t))));
    if (publishBtn) {
      publishBtn.disabled = publishing || !model.title.trim();
      publishBtn.replaceChildren(...(publishing ? [h("span", { class: "fsk-ce-spin", "aria-hidden": "true" }), model.publishedAt ? "Updating…" : "Publishing…"]
        : [model.publishedAt ? "Update" : "Publish"]));
    }
  }
  function updateToc(): void {
    const heads = blocks.filter((b) => (b.type === "h2" || b.type === "h3") && textLen(b.edit));
    toc.replaceChildren(...(heads.length > 1 ? [h("p", {}, "On this page"), ...heads.map((b) => h("a", {
      href: `#${b.id}`, "data-l": b.type === "h3" ? "3" : "2",
      onclick: (e: Event) => { e.preventDefault(); b.el.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "start" }); placeCaret(b.edit, textLen(b.edit)); },
    }, b.edit.textContent ?? ""))] : []));
  }
  function syncTitle(): void {
    const t = (model.canvasTitle ?? `${model.kind ?? "Draft"}: ${model.title.trim() || "Untitled"}`).replace(/\s+/g, " ").slice(0, 80);
    if (t !== lastTitle) { lastTitle = t; canvas?.setTitle?.(t); }
  }
  function updateNote(text?: string): void {
    if (!root.querySelector("[data-agent]")) { note.hidden = true; return; }
    if (text) { note.replaceChildren(icon("sparkle", 12), text); note.hidden = false; }
  }
  function showFirstEdit(): void {
    const el = root.querySelector<HTMLElement>("[data-agent]");
    if (!el) return;
    el.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "center" });
    const target = el.querySelector<HTMLElement>(".fsk-ce-edit, .fsk-ce-field");
    if (target instanceof win.HTMLTextAreaElement) target.focus({ preventScroll: true });
    else if (target) placeCaret(target, textLen(target));
  }
  /** Bold and italic state, and the block type, follow the caret. */
  function updateTools(): void {
    const on = !!current && current.edit.isConnected && !publishing;
    typeSel.disabled = !on;
    boldBtn.disabled = italicBtn.disabled = linkBtn.disabled = !on;
    if (current) typeSel.value = current.type;
    const state = (cmd: string): boolean => { try { return on && doc.queryCommandState(cmd); } catch { return false; } };
    boldBtn.setAttribute("aria-pressed", String(state("bold")));
    italicBtn.setAttribute("aria-pressed", String(state("italic")));
  }

  // ---------- sharing with the agent ----------
  function sync(b: Block): void {
    const i = blocks.indexOf(b);
    if (i >= 0) model.blocks[i] = readBlock(b);
    b.el.removeAttribute("data-agent");
    changed();
  }
  function changed(): void {
    if (model.publishedAt) editedSincePublish = true;
    updateCounts();
    updateHeader();
    updateNote();
    relabel();
    updateToc();
    setStatus("pending");
    win.clearTimeout(timer);
    timer = win.setTimeout(flush, SHARE_DELAY_MS);
  }
  function flush(): void {
    win.clearTimeout(timer);
    timer = 0;
    const patch: Partial<ContentState> = {};
    if (model.title !== shared.title) patch.title = model.title;
    if ((model.subtitle ?? "") !== (shared.subtitle ?? "")) patch.subtitle = model.subtitle;
    if (!same(model.blocks, shared.blocks)) patch.blocks = model.blocks;
    if (model.publishedAt !== shared.publishedAt) patch.publishedAt = model.publishedAt;
    if (model.url !== shared.url) patch.url = model.url;
    if (!Object.keys(patch).length) { setStatus(lastResult); return; }
    const before = shared;
    shared = { ...shared, ...structuredClone(patch) };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas?.setState?.(structuredClone(patch)), (res) => {
      if (res?.ok === false) { shared = before; setStatus("error"); return; }
      lastResult = res?.notSent?.length ? "partial" : "saved";
      setStatus(lastResult);
    });
    syncTitle();
    actions?.onChange?.(structuredClone(model));
  }

  /** The agent's edit. A three-way merge: what the agent changed wins; what only the user changed (not shared yet) stays. */
  function applyRemote(next: Record<string, any>): void {
    const remote = normalize(structuredClone(next));
    const base = shared;
    const active = activeEl();
    const edited: string[] = [];
    const titleChanged = remote.title !== base.title;
    const dekChanged = (remote.subtitle ?? "") !== (base.subtitle ?? "");
    let list = model.blocks;
    if (!same(remote.blocks, base.blocks)) {
      const baseById = new Map(base.blocks.map((x) => [x.id, x]));
      const localById = new Map(model.blocks.map((x) => [x.id, x]));
      const remoteIds = new Set(remote.blocks.map((x) => x.id));
      const merged: ContentBlock[] = [];
      for (const r of remote.blocks) {
        const b = baseById.get(r.id);
        const l = localById.get(r.id);
        if (!b || !same(r, b)) { edited.push(r.id); merged.push(r); } else if (l) merged.push(l);
        // else: the user removed it and the agent didn't touch it, so it stays removed
      }
      // Blocks the user added since the last share stay, after the block they followed.
      model.blocks.forEach((l, i) => {
        if (baseById.has(l.id) || remoteIds.has(l.id)) return;
        const prev = model.blocks[i - 1];
        merged.splice(prev ? merged.findIndex((x) => x.id === prev.id) + 1 : 0, 0, l);
      });
      list = merged;
    }
    model = structuredClone({ ...remote, title: titleChanged ? remote.title : model.title, subtitle: dekChanged ? remote.subtitle : model.subtitle, blocks: list });
    shared = remote;
    syncDom(active, new Set(edited));
    if (edited.length || titleChanged || dekChanged) { if (model.publishedAt) editedSincePublish = true; }
    updateCounts();
    updateHeader();
    updateToc();
    syncTitle();
    showAgentEdits(edited, titleChanged, dekChanged);
    if (model.title !== shared.title || (model.subtitle ?? "") !== (shared.subtitle ?? "") || !same(model.blocks, shared.blocks)) changed(); // share the user's unsent writing on top
    else { win.clearTimeout(timer); timer = 0; setStatus(lastResult); }
  }

  function syncDom(active: Element | null, edited: Set<string>): void {
    setValue(titleEl, model.title, active);
    setValue(dekEl, model.subtitle ?? "", active);
    const byId = new Map(blocks.map((b) => [b.id, b]));
    const focused = blockOf(active);
    const at = focused ? caretIn(focused.edit) : null;
    const before = focused ? focused.edit.textContent ?? "" : "";
    const next = model.blocks.map((data) => {
      const old = byId.get(data.id);
      byId.delete(data.id);
      if (!old || old.type !== data.type) {
        const nb = makeBlock(data);
        old?.el.replaceWith(nb.el);
        return nb;
      }
      if (edited.has(data.id)) fillBlock(old.edit, data);
      return old;
    });
    byId.forEach((b) => b.el.remove());
    next.forEach((b, i) => { const atEl = bodyEl.children[i]; if (atEl !== b.el) bodyEl.insertBefore(b.el, atEl ?? null); });
    blocks = next;
    if (current && !blocks.includes(current)) current = blocks.find((b) => b.id === current?.id) ?? null;
    relabel();
    fit(titleEl);
    fit(dekEl);
    // The caret stays where the user was writing, even when the agent rewrote that block.
    if (focused) {
      const now = blocks.find((b) => b.id === focused.id);
      if (now && at) {
        const [s, e] = remap(before, now.edit.textContent ?? "", at[0], at[1]);
        placeCaret(now.edit, s, e);
      }
    }
  }

  function showAgentEdits(ids: string[], title: boolean, dek: boolean): void {
    root.querySelectorAll("[data-agent]").forEach((e) => e.removeAttribute("data-agent"));
    const els = [title ? titleBlock : null, dek ? dekBlock : null, ...ids.map((id) => blocks.find((b) => b.id === id)?.el ?? null)]
      .filter((e): e is HTMLElement => !!e);
    for (const el of els) {
      el.setAttribute("data-agent", "");
      el.classList.remove("fsk-ce-flash");
      void el.offsetWidth; // restart the fade
      el.classList.add("fsk-ce-flash");
    }
    if (!els.length) { updateNote(); return; }
    const parts = [title && "the title", dek && "the summary", ids.length > 0 && `${ids.length} ${ids.length === 1 ? "block" : "blocks"}`].filter(Boolean);
    const what = parts.join(" and ");
    live.textContent = `The agent edited ${what}.`;
    updateNote(`The agent edited ${what}`);
  }

  // ---------- formatting ----------
  function format(cmd: "bold" | "italic"): void {
    if (!current) return;
    try { doc.execCommand(cmd); } catch { return; }
    sync(current);
    updateTools();
  }

  let linkBox: HTMLElement | null = null;
  function closeLink(restore: boolean): void {
    if (!linkBox) return;
    linkBox.remove();
    linkBox = null;
    linkBtn.setAttribute("aria-expanded", "false");
    if (restore && current && linkRange) {
      current.edit.focus({ preventScroll: true });
      selection()?.setBaseAndExtent(linkRange.startContainer, linkRange.startOffset, linkRange.endContainer, linkRange.endOffset);
    }
  }
  function openLink(): void {
    if (!current) return;
    if (linkBox) { closeLink(true); return; }
    const r = range();
    if (!r || !current.edit.contains(r.startContainer)) return;
    linkRange = r.cloneRange();
    const anchor = (r.startContainer.nodeType === Node.ELEMENT_NODE ? (r.startContainer as Element) : r.startContainer.parentElement)?.closest("a");
    const existing = anchor && current.edit.contains(anchor) ? anchor : null;
    const input = h<HTMLInputElement>("input", { type: "url", placeholder: "https://… or /help/…", "aria-label": "Link address", value: existing?.getAttribute("href") ?? "" });
    const err = h("p", { class: "fsk-ce-linkerr", role: "alert", hidden: true });
    const apply = (): void => {
      let href = input.value.trim();
      if (href && !/^[a-z]+:|^\//i.test(href)) href = `https://${href}`;
      if (!safeHref(href)) { err.textContent = "Use a full address (https://…) or a path in your app (/…)."; err.hidden = false; input.focus(); return; }
      closeLink(true);
      const b = current;
      if (!b) return;
      if (existing) { existing.setAttribute("href", href); }
      else if (linkRange?.collapsed) { doc.execCommand("insertHTML", false, ""); linkRange.insertNode(h("a", { href, rel: "noopener noreferrer", target: "_blank" }, href)); }
      else doc.execCommand("createLink", false, href);
      sync(b);
    };
    const remove = (): void => {
      closeLink(true);
      const b = current;
      if (!existing || !b) return;
      existing.replaceWith(...Array.from(existing.childNodes));
      sync(b);
    };
    linkBox = h<HTMLElement>("div", {
      class: "fsk-ce-linkbox", role: "dialog", "aria-label": existing ? "Edit link" : "Add link",
      onkeydown: (e: KeyboardEvent) => {
        if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeLink(true); }
        if (e.key === "Enter") { e.preventDefault(); apply(); }
      },
    },
      input,
      h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: apply }, existing ? "Save" : "Add"),
      existing && h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: remove }, "Remove"),
      err);
    fmt.append(linkBox);
    linkBtn.setAttribute("aria-expanded", "true");
    input.focus();
  }

  // ---------- publish ----------
  async function publish(): Promise<void> {
    if (!actions?.publish || publishing) return;
    flush();
    publishing = true;
    alertEl.hidden = true;
    updateHeader();
    updateTools();
    bodyEl.querySelectorAll<HTMLElement>(".fsk-ce-edit").forEach((e) => e.setAttribute("contenteditable", "false"));
    titleEl.readOnly = dekEl.readOnly = true;
    try {
      const res = await actions.publish(structuredClone(model));
      model.publishedAt = new Date().toISOString();
      if (res && res.url) model.url = res.url;
      editedSincePublish = false;
      live.textContent = "Published.";
      flush();
    } catch (e) {
      const msg = e instanceof Error && e.message ? e.message : "Something went wrong.";
      alertEl.replaceChildren(icon("alert", 15), h("span", {}, `Couldn't publish: ${msg} Your draft is saved.`),
        h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => void publish() }, "Try again"));
      alertEl.hidden = false;
    } finally {
      publishing = false;
      if (root.isConnected) {
        bodyEl.querySelectorAll<HTMLElement>(".fsk-ce-edit").forEach((e) => e.setAttribute("contenteditable", "true"));
        titleEl.readOnly = dekEl.readOnly = false;
        updateHeader();
        updateTools();
      }
    }
  }

  // ---------- the user's writing ----------
  function onInput(e: Event): void {
    const t = e.target as HTMLElement;
    if (t === titleEl || t === dekEl) {
      const ta = t as HTMLTextAreaElement;
      if (ta.value.includes("\n")) { const pos = ta.selectionStart; ta.value = ta.value.replace(/\s*\n+\s*/g, " "); ta.setSelectionRange(pos, pos); }
      if (ta === titleEl) { model.title = ta.value; titleBlock.removeAttribute("data-agent"); }
      else { model.subtitle = ta.value; dekBlock.removeAttribute("data-agent"); }
      fit(ta);
      changed();
      return;
    }
    const b = blockOf(t);
    if (!b) return;
    // A browser leaves a <br> in a block it emptied: clear it so the placeholder shows.
    if (!isList(b.type) && !textLen(b.edit) && b.edit.querySelector("br") && !b.edit.querySelector("br + *")) b.edit.replaceChildren();
    if (isList(b.type) && !b.edit.querySelector("li")) { convert(b, "p", null); return; }
    if (b.type === "p") {
      const lead = b.edit.textContent ?? "";
      const hit = SHORTCUTS.find(([re]) => re.test(lead));
      if (hit) {
        const [re, type] = hit;
        const [first] = pointAt(b.edit, 0);
        const cut = (lead.match(re)?.[0] ?? "").length;
        if (first.nodeType === Node.TEXT_NODE) first.nodeValue = (first.nodeValue ?? "").slice(cut);
        convert(b, type, [0, 0]);
        return;
      }
    }
    sync(b);
  }

  function onKey(e: KeyboardEvent): void {
    if (e.isComposing) return;
    const t = e.target as HTMLElement;
    const mod = e.metaKey || e.ctrlKey;
    if (t === titleEl || t === dekEl) {
      const ta = t as HTMLTextAreaElement;
      const atEnd = ta.selectionStart === ta.value.length;
      if (e.key === "Enter" || (e.key === "ArrowDown" && atEnd && !mod && !e.altKey)) {
        e.preventDefault();
        if (ta === titleEl) { dekEl.focus(); dekEl.setSelectionRange(0, 0); } else if (blocks[0]) placeCaret(blocks[0].edit, 0);
      } else if (e.key === "ArrowUp" && !mod && !e.altKey && ta === dekEl && ta.selectionStart === 0) { e.preventDefault(); titleEl.focus(); titleEl.setSelectionRange(titleEl.value.length, titleEl.value.length); }
      return;
    }
    const b = blockOf(t);
    if (!b) return;
    const i = blocks.indexOf(b);
    if (mod && !e.altKey && (e.key === "b" || e.key === "i")) { e.preventDefault(); format(e.key === "b" ? "bold" : "italic"); return; }
    if (mod && !e.altKey && e.key === "k") { e.preventDefault(); current = b; openLink(); return; }
    const r = range();
    if (!r) return;
    const at = caretIn(b.edit) ?? [0, 0];
    const len = textLen(b.edit);

    if (e.key === "Enter" && !e.shiftKey) {
      if (isList(b.type)) {
        const li = (r.startContainer.nodeType === Node.ELEMENT_NODE ? (r.startContainer as Element) : r.startContainer.parentElement)?.closest("li");
        if (!li || li.textContent) return; // the browser adds the next item
        // Enter on an empty item leaves the list.
        e.preventDefault();
        li.remove();
        const nb = insertBlock({ id: newId(), type: "p", text: "" }, i + 1);
        if (!b.edit.querySelector("li")) { removeBlock(i); } else sync(b);
        placeCaret(nb.edit, 0);
        sync(nb);
        return;
      }
      e.preventDefault();
      if (!r.collapsed) r.deleteContents();
      if (at[0] === 0 && len > 0) {
        // At the start: a new paragraph above, the caret stays with this text.
        insertBlock({ id: newId(), type: "p", text: "" }, i);
        placeCaret(b.edit, 0);
        sync(b);
        return;
      }
      // Split at the caret: the rest of the text moves to a new paragraph.
      const tail = doc.createRange();
      tail.selectNodeContents(b.edit);
      tail.setStart(r.endContainer, r.endOffset);
      const holder = h("div", {}, tail.extractContents());
      const nb = insertBlock({ id: newId(), type: "p", text: tidy(toMd(holder)) }, i + 1);
      sync(b);
      placeCaret(nb.edit, 0);
      sync(nb);
      return;
    }

    if (e.key === "Backspace" && r.collapsed && at[0] === 0) {
      if (isList(b.type)) {
        const items = Array.from(b.edit.querySelectorAll(":scope > li"));
        if (!items[0]?.contains(r.startContainer) && items[0] !== r.startContainer) return;
        e.preventDefault();
        if (items.length === 1) { convert(b, "p", [0, 0]); return; }
        const first = readBlock(b).items?.[0] ?? "";
        items[0].remove();
        sync(b);
        const nb = insertBlock({ id: newId(), type: "p", text: first }, i);
        placeCaret(nb.edit, 0);
        sync(nb);
        return;
      }
      if (b.type !== "p") { e.preventDefault(); convert(b, "p", [0, 0]); return; }
      const prev = blocks[i - 1];
      if (!prev) return;
      e.preventDefault();
      if (!len) { removeBlock(i); placeCaret(prev.edit, textLen(prev.edit)); changed(); return; }
      if (isList(prev.type)) return;
      // Join this paragraph onto the one before it.
      const join = textLen(prev.edit);
      const md = readBlock(b).text ?? "";
      prev.edit.append(...inline(md));
      removeBlock(i);
      placeCaret(prev.edit, join);
      sync(prev);
      return;
    }

    if ((e.key === "ArrowUp" || e.key === "ArrowDown") && r.collapsed && !e.shiftKey && !mod && !e.altKey) {
      const up = e.key === "ArrowUp";
      if (!atEdge(b.edit, r, up, at[0], len)) return;
      const to = blocks[i + (up ? -1 : 1)];
      if (to) { e.preventDefault(); placeCaret(to.edit, up ? textLen(to.edit) : 0); }
      else if (up) { e.preventDefault(); dekEl.focus(); dekEl.setSelectionRange(dekEl.value.length, dekEl.value.length); }
    }
  }

  /** Is the caret on the block's first line (up) or last line (down)? */
  function atEdge(el: HTMLElement, r: Range, up: boolean, at: number, len: number): boolean {
    if (up ? at === 0 : at === len) return true;
    const rect = r.getClientRects()[0];
    if (!rect) return false;
    const box = el.getBoundingClientRect();
    const line = parseFloat(win.getComputedStyle(el).lineHeight) || 24;
    return up ? rect.top - box.top < line * 0.75 : box.bottom - rect.bottom < line * 0.75;
  }

  /** Paste as plain text. Several paragraphs become several blocks; in a list, several items. */
  function onPaste(e: ClipboardEvent): void {
    const text = e.clipboardData?.getData("text/plain");
    if (text == null) return;
    e.preventDefault();
    const t = e.target as HTMLElement;
    if (t === titleEl || t === dekEl) { doc.execCommand("insertText", false, text.replace(/\s*\n+\s*/g, " ")); return; }
    const b = blockOf(t);
    if (!b) return;
    const parts = text.replace(/\r/g, "").split(isList(b.type) ? /\n+/ : /\n\s*\n/).map((x) => x.trim()).filter(Boolean);
    if (!parts.length) return;
    doc.execCommand("insertText", false, isList(b.type) ? parts[0] : parts[0].replace(/\n/g, " "));
    if (isList(b.type)) {
      const r = range();
      const li = (r?.startContainer.nodeType === Node.ELEMENT_NODE ? (r.startContainer as Element) : r?.startContainer.parentElement)?.closest("li");
      let after: Element | null = li ?? null;
      for (const p of parts.slice(1)) { const item = h("li", {}, p); after?.after(item); after = item; }
      sync(b);
      return;
    }
    sync(b);
    let at = blocks.indexOf(b);
    let last: Block = b;
    for (const p of parts.slice(1)) last = insertBlock({ id: newId(), type: "p", text: p.replace(/\n/g, " ").replace(/([\\`*[\]])/g, "\\$1") }, ++at);
    if (last !== b) { placeCaret(last.edit, textLen(last.edit)); sync(last); }
  }

  function onFocusIn(e: FocusEvent): void {
    const b = blockOf(e.target as Node);
    if (b) current = b;
    else if (e.target === titleEl || e.target === dekEl) current = null;
    updateTools();
  }
  function onFocusOut(): void { if (timer) flush(); }
  function onSelection(): void {
    if (linkBox) return;
    const r = range();
    const b = r ? blockOf(r.startContainer) : undefined;
    if (b) { current = b; caret = caretIn(b.edit); }
    updateTools();
  }
  typeSel.addEventListener("change", () => {
    const b = current;
    if (b) convert(b, typeSel.value as ContentBlockType, caret);
  });

  function addParagraph(): void {
    const last = blocks[blocks.length - 1];
    if (last && last.type === "p" && !textLen(last.edit)) { placeCaret(last.edit, 0); return; }
    const nb = insertBlock({ id: newId(), type: "p", text: "" }, blocks.length);
    placeCaret(nb.edit, 0);
    sync(nb);
  }

  // ---------- draw ----------
  blocks = model.blocks.map(makeBlock);
  bodyEl.append(...blocks.map((b) => b.el));
  relabel();
  updateCounts();
  updateHeader();
  updateToc();
  setStatus("saved");
  syncTitle();
  const page = h("div", { class: "fsk-ce-doc", oninput: onInput, onkeydown: onKey, onpaste: onPaste, onfocusin: onFocusIn, onfocusout: onFocusOut },
    topEl,
    titleBlock,
    dekBlock,
    bylineEl,
    h("hr", { class: "fsk-ce-rule" }),
    bodyEl,
    h("button", { class: "fsk-ce-add", type: "button", onclick: addParagraph }, icon("plus", 14), "Add a paragraph"),
    h("p", { class: "fsk-ce-hint" }, icon("message", 14),
      h("span", {}, "Type ", h("kbd", {}, "##"), " for a heading, ", h("kbd", {}, "-"), " for a list, ", h("kbd", {}, ">"), " for a quote. I see your changes with your next message.")));
  root.replaceChildren(h("div", { class: "fsk fsk-ce" },
    h("div", { class: "fsk-ce-bar" },
      h("div", { class: "fsk-ce-bar-in" },
        fmt,
        h("div", { class: "fsk-ce-right" }, note, wordsEl, statusEl, publishBtn)),
      alertEl),
    h("div", { class: "fsk-ce-wrap" }, page, toc),
    live));
  fit(titleEl);
  fit(dekEl);
  doc.addEventListener("selectionchange", onSelection);
  const onOutside = (e: Event): void => { if (linkBox && !e.composedPath().includes(fmt)) closeLink(false); };
  doc.addEventListener("pointerdown", onOutside, true);
  const off = canvas?.onStateChange?.((next) => applyRemote(next));

  return () => {
    if (timer) flush(); // closing keeps the state: share what the user wrote last
    off?.();
    doc.removeEventListener("selectionchange", onSelection);
    doc.removeEventListener("pointerdown", onOutside, true);
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only preview card (a chat card action) of the article. */
export function mountMobile({ root, head, data, api }: ContentCardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const s = normalize(structuredClone(data));
  const n = words(s);
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-cec", "aria-label": `${s.kind ?? "Draft"}: ${s.title || "Untitled"}` },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(kindIcon(s.kind), 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title || "Untitled"), h("p", { class: "fsk-sub" }, `${s.kind ?? "Draft"} · ${readTime(n)}${s.publishedAt ? " · Published" : " · Draft"}`))),
    s.subtitle && h("p", { class: "fsk-cec-dek" }, s.subtitle),
    h("div", { class: "fsk-cec-doc" }, s.blocks.slice(0, 5).map(staticBlock)),
    h("p", { class: "fsk-cec-foot" }, icon("pencil", 12), "Read-only here. Edit it on desktop, where the editor opens beside the chat.")));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this editor draws besides its article. No empty state: an empty draft is the editor itself, with its placeholders. */
export const states: StateKind[] = ["loading", "error"];

/** mountState's props: the kit's StateProps for the canvas. Mobile uses mountMobileState. */
export interface ContentCanvasStateProps extends Omit<StateProps, "surface"> {
  /** The canvas: mountState sets its title. */
  canvas?: CanvasApi;
  /** The canvas header (setTitle, up to 80 characters). Default: "<eyebrow>: <title>". */
  canvasTitle?: string;
  /** What is being written, on the badge: "Help article", "Blog post". Default: "Draft". */
  eyebrow?: string;
}

/** The mobile card's props: the kit's StateProps, plus what is being written (its icon). */
export interface ContentMobileStateProps extends StateProps {
  eyebrow?: string;
}

/** "Help center / Reports" as a breadcrumb. */
const crumbsOf = (path?: string): HTMLElement | null => {
  const parts = (path ?? "").split("/").map((x) => x.trim()).filter(Boolean);
  return parts.length ? h<HTMLElement>("span", { class: "fsk-ce-crumbs" }, parts.map((c, i) => [i > 0 && icon("chevron", 12), c])) : null;
};

const loadingLabel = (s: CardState): string => (s.kind === "loading" ? s.label ?? "Loading the article…" : "");

/** The article as bones: summary, byline, then paragraphs, a heading, a numbered list and a callout. */
function articleSkeleton(title: string | undefined, subtitle: string | undefined): Child[] {
  const lines = (widths: number[], i: number): HTMLElement => h("div", { class: "fsk-ce-sk-lines" }, widths.map((w) => bone(`${w}%`, "12px", { i })));
  return [
    h("div", { class: "fsk-ce-top" }, bone("96px", "22px", { cls: "fsk-ce-sk-pill" }), crumbsOf(subtitle) ?? bone("120px", "12px", { i: 1 })),
    h("h2", { class: "fsk-ce-title" }, title || bone("68%", "30px")),
    h("div", { class: "fsk-ce-sk-lines", style: { marginTop: "12px" } }, bone("92%", "15px", { i: 1 }), bone("54%", "15px", { i: 1 })),
    h("div", { class: "fsk-ce-by" }, bone("26px", "26px", { cls: "fsk-ce-sk-round", i: 2 }), bone("140px", "12px", { i: 2 })),
    h("hr", { class: "fsk-ce-rule" }),
    lines([100, 97, 62], 2),
    h("div", { class: "fsk-ce-sk-h" }, bone("38%", "18px", { i: 3 })),
    [86, 74, 80].map((w, i) => h("div", { class: "fsk-ce-sk-li", style: { marginTop: "12px" } }, bone("14px", "12px", { i: 3 + i }), bone(`${w}%`, "12px", { i: 3 + i }))),
    h("div", { class: "fsk-ce-sk-callout" }, bone("90%", "12px", { i: 5 }), bone("48%", "12px", { i: 5 })),
  ];
}

/**
 * Desktop canvas in a state: the editor's page with the article as bones while it loads or the agent writes it,
 * or a centered error block under the title. It doesn't change the canvas status: the agent writes the first draft in EDIT_MODE.
 */
export function mountState({ root, head, state, title, subtitle, canvas, canvasTitle, eyebrow }: ContentCanvasStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const kind = eyebrow ?? "Draft";
  canvas?.setTitle?.((canvasTitle ?? `${kind}: ${title?.trim() || "Untitled"}`).replace(/\s+/g, " ").slice(0, 80));
  const loading = state.kind === "loading";
  let dispose = (): void => {};
  let body: Child;
  if (state.kind === "loading") body = h("div", { "aria-hidden": "true" }, articleSkeleton(title, subtitle));
  else {
    let block: HTMLElement;
    if (state.kind === "empty") block = emptyBlock(state);
    else { const e = errorBlock(state); dispose = e.dispose; block = e.el; }
    body = [
      h("div", { class: "fsk-ce-top" }, h("span", { class: "fsk-badge fsk-badge--agent" }, icon(kindIcon(kind), 12), kind), crumbsOf(subtitle)),
      h("h2", { class: "fsk-ce-title" }, title || "Untitled"),
      h("div", { class: "fsk-ce-st-box" }, h("div", { class: "fsk-ce-st-panel" }, block)),
    ];
  }
  root.replaceChildren(h("div", {
    class: "fsk fsk-ce fsk-ce-st", "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, loadingLabel(state)),
    loading && h("div", { class: "fsk-ce-bar", "aria-hidden": "true" },
      h("div", { class: "fsk-ce-bar-in" },
        h("div", { class: "fsk-ce-fmt" }, bone("96px", "30px"), bone("30px", "30px", { i: 1 }), bone("30px", "30px", { i: 1 }), bone("30px", "30px", { i: 1 })),
        h("div", { class: "fsk-ce-right" }, h("span", { class: "fsk-ce-status" }, h("span", { class: "fsk-ce-dot" }), loadingLabel(state))))),
    h("div", { class: "fsk-ce-wrap" }, h("div", { class: "fsk-ce-doc" }, body))));
  return () => { dispose(); root.replaceChildren(); };
}

/** Mobile preview card in a state: its header above paragraph bones, or an error block. Read-only: report displayed() yourself. */
export function mountMobileState({ root, head, state, title, subtitle, eyebrow, surface = "mobile" }: ContentMobileStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const card = stateCard({
    state: state.kind === "loading" ? { ...state, label: loadingLabel(state) } : state, cls: "fsk-cec", icon: kindIcon(eyebrow), title, subtitle, surface,
    skeleton: () => h("div", { class: "fsk-cec-doc fsk-sk-lines" }, [100, 94, 98, 60, 0, 42, 100, 88].map((w, i) => (w ? bone(`${w}%`, "10px", { i }) : h("span", { style: { height: "4px" } })))),
  });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, ContentState> = {
  default: {
    kind: "Help article",
    collection: "Help center / Reports",
    title: "Schedule a report",
    subtitle: "Send any report to your team's inbox every day, week or month, without exporting it by hand.",
    author: "Dana Ortiz",
    tags: ["Reports", "Email"],
    blocks: [
      { id: "intro", type: "p", text: "A scheduled report arrives as a PDF with a link to the live report, so everyone sees the same numbers without opening the app." },
      { id: "h-setup", type: "h2", text: "Set up a schedule" },
      { id: "steps", type: "ol", items: ["Open the report and choose **Schedule**.", "Pick who gets it: people, teams or any email address.", "Choose how often and at what time, then select **Save**."] },
      { id: "tz", type: "callout", text: "Schedules use the time zone in your **workspace settings**, not each person's own." },
      { id: "h-change", type: "h2", text: "Change or pause a schedule" },
      { id: "change", type: "p", text: "Go to [Settings › Reports](/settings/reports) to see every schedule in your workspace. Pause one to stop sending without losing it, or change who gets it at any time." },
      { id: "h-who", type: "h3", text: "Who can create schedules" },
      { id: "who", type: "p", text: "Scheduled reports are on the *Business* and *Enterprise* plans. Admins choose who may create them on the Permissions page." },
      { id: "h-help", type: "h2", text: "If a report doesn't arrive" },
      { id: "help", type: "ul", items: ["Check the recipient's spam folder.", "Make sure the schedule isn't paused.", "An empty PDF means the report had no data for that period."] },
    ],
  },
};
```

```js title="agent/ui/content-canvas.js"
// Template: content-canvas. A CONTENT_EDITOR canvas where the user and the agent write one article together: a help article, a blog post, release notes.

export const meta = {
  id: "content-canvas",
  title: "Article editor",
  surface: "canvas",
  canvasType: "CONTENT_EDITOR",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "The user and the agent write one article together over several turns: a help article, a blog post, release notes, an announcement. The user writes and formats in the canvas, and asks the agent to draft, shorten or rewrite parts of it.",
  whenNotToUse: "A one-line reply or a short answer (the chat). Structured fields with rules (form canvas). Text the agent writes once and the user never edits (a chat card). Mobile: the canvas isn't available; use the preview card (mountMobile).",
};

const CSS = `
.fsk-ce { min-height: 100%; background: var(--k-paper); container: fsk-ce / inline-size; }

/* Toolbar */
.fsk-ce-bar {
  position: sticky; top: 0; z-index: 3; border-bottom: 1px solid var(--k-divider);
  background: color-mix(in srgb, var(--k-paper) 92%, transparent);
  -webkit-backdrop-filter: saturate(1.4) blur(10px); backdrop-filter: saturate(1.4) blur(10px);
}
.fsk-ce-bar-in { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; min-height: 48px; padding: 7px 16px; font-size: .86em; color: var(--k-text-2); }
.fsk-ce-fmt { position: relative; display: flex; align-items: center; gap: 2px; }
.fsk-ce-type {
  appearance: none; height: 30px; padding: 0 26px 0 10px; margin-right: 4px; border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  background: var(--k-paper) no-repeat right 8px center / 10px; color: var(--k-text); font: inherit; font-weight: 500; cursor: pointer;
  background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(-45deg, transparent 50%, currentColor 50%);
  background-size: 4px 4px, 4px 4px; background-position: right 13px center, right 9px center;
}
.fsk-ce-type:disabled { color: var(--k-text-2); cursor: default; opacity: .6; }
.fsk-ce-tool {
  appearance: none; display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0;
  border-radius: var(--k-r-md); background: transparent; color: var(--k-text-2); cursor: pointer;
}
.fsk-ce-tool:hover:not(:disabled) { background: var(--k-hover); color: var(--k-text); }
.fsk-ce-tool[aria-pressed="true"] { background: var(--k-tint); color: var(--k-primary); }
.fsk-ce-tool:disabled { opacity: .4; cursor: default; }
.fsk-ce-vsep { width: 1px; height: 18px; margin: 0 4px; background: var(--k-divider); }
.fsk-ce-right { display: flex; align-items: center; gap: 10px; margin-left: auto; white-space: nowrap; }
.fsk-ce-note {
  appearance: none; display: inline-flex; align-items: center; gap: 5px; padding: 3px 10px 3px 8px; border: 0; border-radius: calc(var(--k-r) * 100);
  background: var(--k-tint); color: var(--k-primary); font: inherit; font-weight: 600; cursor: pointer; animation: fsk-in .25s var(--k-ease) both;
}
.fsk-ce-note:hover { background: var(--k-tint-2); }
.fsk-ce-status { display: inline-flex; align-items: center; gap: 6px; }
.fsk-ce-status[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-ce-status[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-ce-status[data-s="error"] { color: var(--k-error); }
.fsk-ce-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--k-primary); animation: fsk-ce-pulse 1.1s ease-in-out infinite; }
.fsk-ce-publish { min-height: 32px; padding: 0 14px; }
.fsk-ce-publish .fsk-ce-spin { width: 13px; height: 13px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: fsk-spin .7s linear infinite; }
.fsk-ce-alert {
  display: flex; align-items: center; gap: 8px; padding: 8px 16px; border-top: 1px solid var(--k-divider);
  background: color-mix(in srgb, var(--k-error) 8%, var(--k-paper)); color: var(--k-text); font-size: .86em;
}
.fsk-ce-alert > .fsk-icon { flex: none; color: var(--k-error); }
.fsk-ce-alert > span { flex: 1; }

/* Link box */
.fsk-ce-linkbox {
  position: absolute; top: calc(100% + 8px); left: 0; z-index: 4; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; width: 340px; max-width: calc(100cqw - 32px);
  padding: 8px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); animation: fsk-in .18s var(--k-ease) both;
}
.fsk-ce-linkbox input {
  flex: 1; min-width: 0; height: 32px; padding: 0 10px; border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  background: var(--k-paper); color: var(--k-text); font: inherit; outline: none;
}
.fsk-ce-linkbox input:focus { border-color: var(--k-primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 14%, transparent); }
.fsk-ce-linkbox .fsk-btn { min-height: 32px; padding: 0 10px; }
.fsk-ce-linkerr { flex-basis: 100%; margin: 0; color: var(--k-error); font-size: .93em; }

/* Page */
.fsk-ce-wrap { display: flex; justify-content: center; gap: 48px; padding: 0 36px; }
.fsk-ce-doc { flex: 1; min-width: 0; max-width: 720px; padding: 30px 0 72px; }
.fsk-ce-top { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin-bottom: 18px; font-size: .86em; color: var(--k-text-2); }
.fsk-ce-crumbs { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 2px; }
.fsk-ce-crumbs .fsk-icon { opacity: .6; }
.fsk-ce-state { margin-left: auto; }
.fsk-ce-field {
  display: block; width: 100%; min-height: 1lh; margin: 0; padding: 0; border: 0; outline: none; background: transparent;
  color: inherit; font: inherit; letter-spacing: inherit; resize: none; overflow: hidden; field-sizing: content;
}
.fsk-ce-field::placeholder { color: var(--k-text-2); opacity: .7; }
.fsk-ce-title { font-size: 2.15em; font-weight: 700; letter-spacing: -0.028em; line-height: 1.18; }
.fsk-ce-dek { margin-top: 10px; font-size: 1.22em; line-height: 1.5; color: var(--k-text-2); }
.fsk-ce-by { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin-top: 18px; font-size: .93em; color: var(--k-text-2); }
.fsk-ce-by b { font-weight: 600; color: var(--k-text); }
.fsk-ce-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-left: auto; }
.fsk-ce-tag { padding: 1px 9px; border: 1px solid var(--k-border); border-radius: calc(var(--k-r) * 100); font-size: .86em; white-space: nowrap; }
.fsk-ce-rule { height: 1px; margin: 26px 0 18px; background: var(--k-divider); border: 0; }

/* Blocks */
.fsk-ce-body { font-size: 1.07em; line-height: 1.72; }
.fsk-ce-block { position: relative; border-radius: var(--k-r-md); transition: background-color .3s; }
.fsk-ce-block + .fsk-ce-block { margin-top: .8em; }
.fsk-ce-block[data-type="h2"]:not(:first-child) { margin-top: 1.7em; }
.fsk-ce-block[data-type="h3"]:not(:first-child) { margin-top: 1.3em; }
.fsk-ce-block[data-type="h2"] + .fsk-ce-block, .fsk-ce-block[data-type="h3"] + .fsk-ce-block { margin-top: .45em; }
.fsk-ce-edit { margin: 0; min-height: 1lh; outline: none; overflow-wrap: anywhere; white-space: pre-wrap; caret-color: var(--k-primary); }
.fsk-ce-edit:empty::before { content: attr(data-ph); color: var(--k-text-2); opacity: 0; pointer-events: none; }
.fsk-ce-edit:focus:empty::before, .fsk-ce-body[data-blank] .fsk-ce-edit:empty::before { opacity: .7; }
h2.fsk-ce-edit { font-size: 1.42em; font-weight: 680; letter-spacing: -0.018em; line-height: 1.3; }
h3.fsk-ce-edit { font-size: 1.14em; font-weight: 650; letter-spacing: -0.01em; line-height: 1.4; }
ul.fsk-ce-edit, ol.fsk-ce-edit { padding-left: 1.5em; }
.fsk-ce-edit li { padding-left: .25em; min-height: 1lh; }
.fsk-ce-edit li + li { margin-top: .3em; }
.fsk-ce-edit li::marker { color: var(--k-text-2); font-variant-numeric: tabular-nums; }
blockquote.fsk-ce-edit { padding: 2px 0 2px 18px; border-left: 3px solid var(--k-border); font-size: 1.08em; font-style: italic; color: color-mix(in srgb, var(--k-text) 82%, var(--k-paper)); }
.fsk-ce-callout { display: flex; gap: 12px; padding: 14px 16px; border-radius: var(--k-r-lg); background: var(--k-tint); }
.fsk-ce-callout > .fsk-icon { flex: none; margin-top: .3em; color: var(--k-primary); }
.fsk-ce-callout > .fsk-ce-edit { flex: 1; min-width: 0; }
.fsk-ce-edit strong, .fsk-ce-edit b { font-weight: 650; }
.fsk-ce-edit a, .fsk-cec a { color: var(--k-primary); text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px; }
.fsk-ce-edit code, .fsk-cec code { padding: .1em .35em; border-radius: calc(var(--k-r-md) - 2px); background: var(--k-sunken); font: .88em var(--k-mono); }

/* The agent's edits */
.fsk-ce-block::before { content: ""; position: absolute; left: -16px; top: .3em; bottom: .3em; width: 3px; border-radius: 3px; background: var(--k-primary); opacity: 0; transition: opacity .2s; }
.fsk-ce-block[data-agent]::before { opacity: 1; }
.fsk-ce-flash { animation: fsk-ce-flash 2.6s var(--k-ease); }
.fsk-ce-mark {
  position: absolute; right: 0; top: -1.15em; z-index: 1; display: none; align-items: center; gap: 4px; padding: 1px 8px 1px 6px;
  border-radius: calc(var(--k-r) * 100); font-size: .68em; font-style: normal; font-weight: 600; line-height: 1.6; white-space: nowrap;
  color: var(--k-primary); background: var(--k-tint); box-shadow: 0 0 0 2px var(--k-paper);
}
.fsk-ce-block[data-agent] > .fsk-ce-mark { display: inline-flex; animation: fsk-in .3s var(--k-ease) both; }

.fsk-ce-add {
  appearance: none; display: inline-flex; align-items: center; gap: 6px; margin-top: 22px; padding: 6px 12px;
  border: 1px dashed var(--k-border); border-radius: var(--k-r-md); background: none; color: var(--k-text-2); font: inherit; font-size: .86em; cursor: pointer;
}
.fsk-ce-add:hover { border-style: solid; color: var(--k-text); background: var(--k-hover); }
.fsk-ce-hint { display: flex; align-items: flex-start; gap: 7px; margin: 18px 0 0; font-size: .86em; line-height: 1.5; color: var(--k-text-2); }
.fsk-ce-hint .fsk-icon { flex: none; margin-top: .15em; }
.fsk-ce-hint kbd { padding: 0 5px; border: 1px solid var(--k-border); border-radius: 4px; font: .93em var(--k-mono); }
.fsk-ce-tool:focus-visible, .fsk-ce-add:focus-visible, .fsk-ce-note:focus-visible, .fsk-ce-type:focus-visible, .fsk-ce-toc a:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

/* Outline: on a wide canvas */
.fsk-ce-toc { display: none; flex: none; width: 190px; align-self: flex-start; position: sticky; top: 72px; padding-top: 34px; font-size: .86em; }
.fsk-ce-toc p { margin: 0 0 8px; font-size: .86em; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--k-text-2); }
.fsk-ce-toc a { display: block; padding: 4px 0 4px 12px; border-left: 2px solid var(--k-divider); color: var(--k-text-2); text-decoration: none; line-height: 1.35; }
.fsk-ce-toc a[data-l="3"] { padding-left: 24px; }
.fsk-ce-toc a:hover { color: var(--k-text); border-left-color: var(--k-text-2); }
@container fsk-ce (min-width: 1000px) { .fsk-ce-toc:not(:empty) { display: block; } }
@container fsk-ce (max-width: 720px) { .fsk-ce-words, .fsk-ce-long { display: none; } }
@container fsk-ce (max-width: 560px) {
  .fsk-ce-bar-in { padding: 6px 12px; }
  .fsk-ce-wrap { padding: 0 18px; }
  .fsk-ce-doc { padding-top: 22px; }
  .fsk-ce-title { font-size: 1.7em; }
  .fsk-ce-dek { font-size: 1.1em; }
  .fsk-ce-block::before { left: -11px; }
}
@keyframes fsk-ce-flash { 0%, 25% { background-color: var(--k-tint-2); } }
@keyframes fsk-ce-pulse { 50% { opacity: .35; transform: scale(.75); } }
@media (prefers-reduced-motion: reduce) { .fsk-ce-block[data-agent] { background: var(--k-tint); } .fsk-ce-dot, .fsk-ce-publish .fsk-ce-spin { animation: none; } }

/* Mobile preview card */
.fsk-cec .fsk-cec-dek { margin: -4px 0 10px; color: var(--k-text-2); line-height: 1.45; }
.fsk-cec .fsk-cec-doc { position: relative; max-height: 250px; overflow: hidden; padding: 12px 14px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; line-height: 1.55; }
.fsk-cec .fsk-cec-doc::after { content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 56px; background: linear-gradient(to bottom, transparent, var(--k-sunken)); }
.fsk-cec h4 { margin: 12px 0 4px; font-size: 1.02em; font-weight: 650; }
.fsk-cec h4:first-child, .fsk-cec p:first-child { margin-top: 0; }
.fsk-cec p, .fsk-cec ul, .fsk-cec ol { margin: 0 0 8px; }
.fsk-cec ul, .fsk-cec ol { padding-left: 1.3em; }
.fsk-cec .fsk-cec-callout { padding: 8px 10px; border-radius: var(--k-r-md); background: var(--k-tint); }
.fsk-cec blockquote { margin: 0 0 8px; padding-left: 10px; border-left: 3px solid var(--k-border); font-style: italic; }
.fsk-cec .fsk-cec-foot { display: flex; align-items: center; gap: 6px; margin: 12px 0 0; font-size: .79em; color: var(--k-text-2); }

/* States (mountState): the editor's own page, with a skeleton in its shape or a centered block */
.fsk-ce-st { display: flex; flex-direction: column; }
.fsk-ce-st > .fsk-ce-wrap { flex: 1; }
.fsk-ce-st .fsk-ce-doc { display: flex; flex-direction: column; }
.fsk-ce-st h2.fsk-ce-title { margin: 0; }
.fsk-ce-st .fsk-ce-title .fsk-bone { margin: 8px 0; }
.fsk-ce-sk-pill { border-radius: calc(var(--k-r) * 100); }
.fsk-ce-st .fsk-ce-fmt { gap: 6px; }
.fsk-ce-sk-round { border-radius: 50%; }
.fsk-ce-sk-lines { display: flex; flex-direction: column; gap: 12px; padding: 6px 0; }
.fsk-ce-sk-h { margin: 20px 0 6px; }
.fsk-ce-sk-li { display: flex; align-items: center; gap: 12px; }
.fsk-ce-sk-callout { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; padding: 16px; border-radius: var(--k-r-lg); background: var(--k-tint); }
.fsk-ce-st-box { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 0 12%; }
.fsk-ce-st-panel { width: 100%; max-width: 460px; animation: fsk-in .32s var(--k-ease) both; }
.fsk-ce-st-panel > .fsk-error { padding: 20px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); }
.fsk-ce-st-panel > .fsk-empty { padding: 8px 0; }
.fsk-cec .fsk-cec-doc .fsk-bone { background: color-mix(in srgb, var(--k-text) 9%, var(--k-sunken)); }
.fsk-cec .fsk-cec-doc.fsk-sk-lines { max-height: none; }
`;

const SHARE_DELAY_MS = 600;
const TYPES = ["p", "h2", "h3", "ul", "ol", "quote", "callout"];
const TYPE_LABEL = { p: "Text", h2: "Heading", h3: "Subheading", ul: "Bulleted list", ol: "Numbered list", quote: "Quote", callout: "Callout" };
const PLACEHOLDER = {
  p: "Write, or type ## for a heading, - for a list", h2: "Heading", h3: "Subheading", ul: "List item", ol: "List item", quote: "Quote", callout: "Something readers shouldn't miss",
};
/** Typed at the start of a paragraph, followed by a space: the block becomes this type. */
const SHORTCUTS = [[/^###[  ]/, "h3"], [/^##[  ]/, "h2"], [/^[-*][  ]/, "ul"], [/^1\.[  ]/, "ol"], [/^>[  ]/, "quote"]];
let seq = 0;

const isList = (t) => t === "ul" || t === "ol";
const newId = () => `b${Date.now().toString(36)}${(++seq).toString(36)}`;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);

// ---------- inline markdown: **bold**, *italic*, `code`, [label](url) ----------

/** Links the editor keeps: web, mail and your app's own paths. Anything else stays text. */
function safeHref(raw) {
  const v = (raw ?? "").trim();
  return /^(https?:\/\/|mailto:|\/(?!\/))/i.test(v) ? v : null;
}

function findClose(md, mark, from) {
  for (let j = from; j < md.length; j++) {
    if (md[j] === "\\") { j++; continue; }
    if (mark === "*" && md.startsWith("**", j)) { j++; continue; }
    if (md.startsWith(mark, j)) return j;
  }
  return -1;
}

/** Inline markdown to DOM nodes. Text nodes only, never HTML, so the agent's text can't inject markup. */
function inline(md) {
  const out = [];
  let i = 0;
  let buf = "";
  const flush = () => { if (buf) { out.push(document.createTextNode(buf)); buf = ""; } };
  while (i < md.length) {
    const c = md[i];
    if (c === "\\" && i + 1 < md.length) { buf += md[i + 1]; i += 2; continue; }
    if (c === "\n") { flush(); out.push(h("br")); i++; continue; }
    if (c === "`") {
      const end = md.indexOf("`", i + 1);
      if (end > i + 1) { flush(); out.push(h("code", {}, md.slice(i + 1, end))); i = end + 1; continue; }
    }
    if (md.startsWith("**", i)) {
      const end = findClose(md, "**", i + 2);
      if (end > i + 2) { flush(); out.push(h("strong", {}, inline(md.slice(i + 2, end)))); i = end + 2; continue; }
    }
    if (c === "*") {
      const end = findClose(md, "*", i + 1);
      if (end > i + 1) { flush(); out.push(h("em", {}, inline(md.slice(i + 1, end)))); i = end + 1; continue; }
    }
    if (c === "[") {
      const m = /^\[([^\]\n]+)\]\(([^)\s]+)\)/.exec(md.slice(i));
      if (m) {
        const href = safeHref(m[2]);
        flush();
        out.push(...(href ? [h("a", { href, rel: "noopener noreferrer", target: "_blank" }, inline(m[1]))] : inline(m[1])));
        i += m[0].length;
        continue;
      }
    }
    buf += c;
    i++;
  }
  flush();
  return out;
}

/** Moves the spaces around a span outside its markers: "** bold**" isn't markdown, " **bold**" is. */
function wrap(mark, s) {
  const m = /^(\s*)([\s\S]*?)(\s*)$/.exec(s);
  return m && m[2] ? `${m[1]}${mark}${m[2]}${mark}${m[3]}` : s;
}

/** The DOM the user edited, back to inline markdown. Reads what browsers write for bold and italic (b, strong, styles). */
function toMd(node) {
  let out = "";
  node.childNodes.forEach((n) => {
    if (n.nodeType === Node.TEXT_NODE) { out += (n.nodeValue ?? "").replace(/ /g, " ").replace(/([\\`*[\]])/g, "\\$1"); return; }
    if (n.nodeType !== Node.ELEMENT_NODE) return;
    const el = n;
    const tag = el.tagName;
    if (tag === "BR") { out += "\n"; return; }
    if (tag === "CODE") { out += wrap("`", (el.textContent ?? "").replace(/`/g, "")); return; }
    if ((tag === "DIV" || tag === "P") && out && !out.endsWith("\n")) out += "\n";
    let s = toMd(el);
    if (tag === "A") { const href = safeHref(el.getAttribute("href")); out += href && s.trim() ? `[${s}](${href})` : s; return; }
    const weight = el.style.fontWeight;
    if (tag === "I" || tag === "EM" || el.style.fontStyle === "italic") s = wrap("*", s);
    if (tag === "B" || tag === "STRONG" || weight === "bold" || Number(weight) >= 600) s = wrap("**", s);
    out += s;
  });
  return out;
}

const tidy = (md) => md.replace(/\n+$/, "");
/** Markdown to plain text, for counting words and the outline. */
const plain = (md) => md.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\\(.)/g, "$1").replace(/[*`]/g, "");

/** Fills the gaps the agent may leave (no id, an unknown type, text where items belong) so the editor never breaks. */
function normalize(raw) {
  const s = (raw ?? {});
  const list = Array.isArray(s.blocks) ? s.blocks : [];
  const blocks = list.map((x, i) => {
    const type = TYPES.includes(x?.type) ? x.type : "p";
    const id = String(x?.id ?? `b${i + 1}`);
    if (isList(type)) {
      const items = Array.isArray(x?.items) ? x.items.map((t) => String(t ?? "")) : String(x?.text ?? "").split("\n");
      return { id, type, items: items.length ? items : [""] };
    }
    return { id, type, text: x?.text != null ? String(x.text) : Array.isArray(x?.items) ? x.items.join("\n") : "" };
  });
  return { ...s, title: String(s.title ?? ""), subtitle: s.subtitle == null ? undefined : String(s.subtitle), blocks: blocks.length ? blocks : [{ id: "b1", type: "p", text: "" }] };
}

/** A block with another type: text becomes list items line by line, and back. */
function retype(b, type) {
  if (isList(type)) return { id: b.id, type, items: b.items ?? (b.text ?? "").split("\n") };
  return { id: b.id, type, text: b.text ?? (b.items ?? []).join("\n") };
}

const words = (s) =>
  [s.title, s.subtitle ?? "", ...s.blocks.flatMap((b) => [b.text ?? "", ...(b.items ?? [])])].map(plain).join(" ").match(/\S+/g)?.length ?? 0;
const readTime = (n) => `${Math.max(1, Math.round(n / 230))} min read`;
const kindIcon = (kind) => (/mail/i.test(kind ?? "") ? "mail" : "doc");

/** Writes a field without moving the caret: text before it stays put, text after it shifts with the change. */
function setValue(el, value, active) {
  if (el.value === value) return;
  if (el !== active) { el.value = value; return; }
  const [start, end] = remap(el.value, value, el.selectionStart, el.selectionEnd);
  const dir = el.selectionDirection;
  el.value = value;
  el.setSelectionRange(start, end, dir);
}

/** Where a caret at `start..end` in `old` lands in `next`: the common start and end of the two texts stay anchored. */
function remap(old, next, start, end) {
  let p = 0;
  while (p < old.length && p < next.length && old[p] === next[p]) p++;
  let q = 0;
  while (q < old.length - p && q < next.length - p && old[old.length - 1 - q] === next[next.length - 1 - q]) q++;
  const map = (c) => (c <= p ? c : c >= old.length - q ? next.length - (old.length - c) : next.length - q);
  return [map(start), map(end)];
}

/** Draws a block's contents from its markdown. */
function fillBlock(edit, b) {
  if (isList(b.type)) edit.replaceChildren(...(b.items?.length ? b.items : [""]).map((t) => h("li", {}, t ? inline(t) : h("br"))));
  else edit.replaceChildren(...inline(b.text ?? ""));
}

/** One block, read-only: the mobile card. */
function staticBlock(b) {
  if (isList(b.type)) return h(b.type, {}, (b.items ?? []).map((t) => h("li", {}, inline(t))));
  if (b.type === "h2" || b.type === "h3") return h("h4", {}, inline(b.text ?? ""));
  if (b.type === "quote") return h("blockquote", {}, inline(b.text ?? ""));
  return h("p", { class: b.type === "callout" ? "fsk-cec-callout" : null }, inline(b.text ?? ""));
}

/**
 * Desktop canvas, EDIT_MODE. The user's writing is shared 600 ms after they stop and on blur.
 * The agent's edits arrive through onStateChange and are written in place, keeping the caret.
 */
export function mount({ root, head, canvas, data, actions }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const native = !!win.CSS?.supports?.("field-sizing", "content");
  const rootNode = root.getRootNode();
  const shadow = rootNode instanceof win.ShadowRoot ? rootNode : null;
  let shared = normalize(structuredClone(canvas?.state ?? data)); // what the agent has
  let model = structuredClone(shared); // what the user sees, with writing not shared yet
  let blocks = [];
  let timer = 0;
  let status = null;
  let lastResult = "saved";
  let lastTitle = "";
  let current = null; // the block the toolbar acts on
  let caret = null; // the caret in it, kept while the toolbar has focus
  let publishing = false;
  let editedSincePublish = false;
  let linkRange = null;
  const activeEl = () => (shadow ?? doc).activeElement;

  // ---------- selection (works inside a shadow root too) ----------
  function selection() {
    // Chrome and Firefox read a selection inside a shadow root from the root itself; Safari from the document.
    const fromRoot = shadow && Reflect.get(shadow, "getSelection");
    const own = typeof fromRoot === "function" ? (fromRoot.call(shadow)) : null;
    return own ?? doc.getSelection();
  }
  function range() {
    const sel = selection();
    if (!sel) return null;
    const inside = sel.rangeCount > 0 && root.contains(sel.getRangeAt(0).startContainer);
    if (!inside && shadow && typeof sel.getComposedRanges === "function") {
      const [r] = sel.getComposedRanges({ shadowRoots: [shadow] });
      if (!r || !root.contains(r.startContainer)) return null;
      const out = doc.createRange();
      out.setStart(r.startContainer, r.startOffset);
      out.setEnd(r.endContainer, r.endOffset);
      return out;
    }
    return inside ? sel.getRangeAt(0) : null;
  }
  function offsetOf(el, node, offset) {
    const r = doc.createRange();
    r.selectNodeContents(el);
    try { r.setEnd(node, offset); } catch { return 0; }
    return r.toString().length;
  }
  function caretIn(el) {
    const r = range();
    if (!r || !el.contains(r.startContainer)) return null;
    return [offsetOf(el, r.startContainer, r.startOffset), offsetOf(el, r.endContainer, r.endOffset)];
  }
  function pointAt(el, at) {
    const walker = doc.createTreeWalker(el, NodeFilter.SHOW_TEXT);
    let left = at;
    let last = null;
    for (let n = walker.nextNode(); n; n = walker.nextNode()) {
      const len = n.nodeValue?.length ?? 0;
      if (left <= len) return [n, left];
      left -= len;
      last = n;
    }
    if (last) return [last, last.nodeValue?.length ?? 0];
    const li = el.querySelector("li");
    return li ? [li, 0] : [el, 0];
  }
  function placeCaret(el, start, end = start) {
    el.focus({ preventScroll: true });
    const [a, ao] = pointAt(el, start);
    const [b, bo] = pointAt(el, end);
    try { selection()?.setBaseAndExtent(a, ao, b, bo); } catch { /* the block moved: the caret stays where the browser put it */ }
  }
  const textLen = (el) => (el.textContent ?? "").length;

  // ---------- title and summary (one line each) ----------
  function field(cls, label, placeholder, value) {
    const ta = h("textarea", { class: `fsk-ce-field ${cls}`, rows: 1, "aria-label": label, placeholder, spellcheck: "true" });
    ta.value = value;
    return ta;
  }
  /** Auto-grow where field-sizing isn't supported. */
  function fit(ta) {
    if (native || !ta.isConnected) return;
    ta.style.height = "auto";
    ta.style.height = `${ta.scrollHeight}px`;
  }
  const mark = () => h("span", { class: "fsk-ce-mark", "aria-hidden": "true" }, icon("sparkle", 11), "Edited by the agent");
  const titleEl = field("fsk-ce-title", "Title", "Untitled", model.title);
  const dekEl = field("fsk-ce-dek", "Summary", "Add a one-line summary", model.subtitle ?? "");
  const titleBlock = h("div", { class: "fsk-ce-block fsk-ce-block--title" }, mark(), titleEl);
  const dekBlock = h("div", { class: "fsk-ce-block fsk-ce-block--dek" }, mark(), dekEl);

  // ---------- blocks ----------
  function makeBlock(b) {
    const tag = isList(b.type) ? b.type : b.type === "h2" || b.type === "h3" ? b.type : b.type === "quote" ? "blockquote" : "div";
    const edit = h(tag, {
      class: "fsk-ce-edit", contenteditable: "true", role: "textbox", "aria-multiline": "true", spellcheck: "true", "data-ph": PLACEHOLDER[b.type],
    });
    fillBlock(edit, b);
    const inner = b.type === "callout" ? h("div", { class: "fsk-ce-callout" }, icon("info", 18), edit) : edit;
    const el = h("div", { class: "fsk-ce-block", "data-id": b.id, "data-type": b.type }, mark(), inner);
    return { id: b.id, type: b.type, el, edit };
  }
  function readBlock(b) {
    if (isList(b.type)) {
      const items = Array.from(b.edit.children).filter((e) => e.tagName === "LI").map((li) => tidy(toMd(li)));
      return { id: b.id, type: b.type, items: items.length ? items : [""] };
    }
    return { id: b.id, type: b.type, text: tidy(toMd(b.edit)) };
  }
  function relabel() {
    blocks.forEach((b, i) => b.edit.setAttribute("aria-label", `${TYPE_LABEL[b.type]}, block ${i + 1} of ${blocks.length}`));
    bodyEl.toggleAttribute("data-blank", blocks.length === 1 && !textLen(blocks[0].edit));
  }
  function insertBlock(b, at) {
    const nb = makeBlock(b);
    model.blocks.splice(at, 0, b);
    blocks.splice(at, 0, nb);
    bodyEl.insertBefore(nb.el, blocks[at + 1]?.el ?? null);
    relabel();
    return nb;
  }
  function removeBlock(i) {
    const [gone] = blocks.splice(i, 1);
    model.blocks.splice(i, 1);
    gone.el.remove();
    if (current === gone) current = null;
    relabel();
  }
  /** Replaces a block with the same text as another type, keeping the caret. */
  function convert(b, type, at) {
    const i = blocks.indexOf(b);
    if (i < 0 || b.type === type) return;
    const next = retype(readBlock(b), type);
    const nb = makeBlock(next);
    b.el.replaceWith(nb.el);
    blocks[i] = nb;
    model.blocks[i] = next;
    current = nb;
    relabel();
    const len = textLen(nb.edit);
    placeCaret(nb.edit, Math.min(at?.[0] ?? len, len), Math.min(at?.[1] ?? len, len));
    sync(nb);
  }
  const blockOf = (node) => (node ? blocks.find((b) => b.edit === node || b.edit.contains(node)) : undefined);

  // ---------- toolbar ----------
  const typeSel = h("select", { class: "fsk-ce-type", "aria-label": "Block type", disabled: true },
    TYPES.map((t) => h("option", { value: t }, TYPE_LABEL[t])));
  // Toolbar buttons keep the selection in the text: mousedown doesn't take focus.
  const keep = (e) => e.preventDefault();
  const tool = (ic, label, onclick, keys) =>
    h("button", { class: "fsk-ce-tool", type: "button", "aria-label": label, title: keys ? `${label} (${keys})` : label, "aria-pressed": "false", disabled: true, onmousedown: keep, onclick }, icon(ic, 16));
  const boldBtn = tool("bold", "Bold", () => format("bold"), "⌘B");
  const italicBtn = tool("italic", "Italic", () => format("italic"), "⌘I");
  const linkBtn = tool("link", "Link", () => openLink(), "⌘K");
  linkBtn.removeAttribute("aria-pressed");
  linkBtn.setAttribute("aria-haspopup", "dialog");
  const fmt = h("div", { class: "fsk-ce-fmt", role: "toolbar", "aria-label": "Formatting" }, typeSel, boldBtn, italicBtn, linkBtn);
  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const statusEl = h("span", { class: "fsk-ce-status" });
  const wordsEl = h("span", { class: "fsk-ce-words fsk-num" });
  const note = h("button", { class: "fsk-ce-note", type: "button", hidden: true, onclick: () => showFirstEdit() });
  const publishBtn = actions?.publish ? h("button", { class: "fsk-btn fsk-btn--primary fsk-ce-publish", type: "button", onclick: () => void publish() }) : null;
  const alertEl = h("div", { class: "fsk-ce-alert", role: "alert", hidden: true });
  const statePill = h("span", { class: "fsk-ce-state" });
  const readEl = h("span", { class: "fsk-num" });
  const bylineEl = h("div", { class: "fsk-ce-by" });
  const topEl = h("div", { class: "fsk-ce-top" });
  const toc = h("nav", { class: "fsk-ce-toc", "aria-label": "Outline" });
  const bodyEl = h("div", { class: "fsk-ce-body" });

  function setStatus(s) {
    if (status === s) return;
    status = s;
    statusEl.dataset.s = s;
    statusEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-ce-dot", "aria-hidden": "true" }), "Saving…"]
      : s === "partial" ? [icon("alert", 14), "Too long: the agent sees part of it"]
      : s === "error" ? [icon("alert", 14), "Not shared. Keep writing to retry."]
      : [icon("check", 14), h("span", {}, "Saved", h("span", { class: "fsk-ce-long" }, " for the agent"))]));
  }
  function updateCounts() {
    const n = words(model);
    wordsEl.textContent = `${n.toLocaleString()} ${n === 1 ? "word" : "words"}`;
    readEl.textContent = readTime(n);
  }
  function updateHeader() {
    const tone = !model.publishedAt ? "neutral" : editedSincePublish ? "warning" : "success";
    statePill.replaceChildren(pill(!model.publishedAt ? "Draft" : editedSincePublish ? "Unpublished changes" : "Published", tone));
    topEl.replaceChildren(h("span", { class: "fsk-badge fsk-badge--agent" }, icon(kindIcon(model.kind), 12), model.kind ?? "Draft"));
    const crumbs = crumbsOf(model.collection);
    if (crumbs) topEl.append(crumbs);
    topEl.append(statePill);
    bylineEl.replaceChildren();
    if (model.author) bylineEl.append(avatar(model.author, { size: 26 }), h("b", {}, model.author), h("span", { "aria-hidden": "true" }, "·"));
    bylineEl.append(readEl);
    if (model.tags?.length) bylineEl.append(h("span", { class: "fsk-ce-tags" }, model.tags.map((t) => h("span", { class: "fsk-ce-tag" }, t))));
    if (publishBtn) {
      publishBtn.disabled = publishing || !model.title.trim();
      publishBtn.replaceChildren(...(publishing ? [h("span", { class: "fsk-ce-spin", "aria-hidden": "true" }), model.publishedAt ? "Updating…" : "Publishing…"]
        : [model.publishedAt ? "Update" : "Publish"]));
    }
  }
  function updateToc() {
    const heads = blocks.filter((b) => (b.type === "h2" || b.type === "h3") && textLen(b.edit));
    toc.replaceChildren(...(heads.length > 1 ? [h("p", {}, "On this page"), ...heads.map((b) => h("a", {
      href: `#${b.id}`, "data-l": b.type === "h3" ? "3" : "2",
      onclick: (e) => { e.preventDefault(); b.el.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "start" }); placeCaret(b.edit, textLen(b.edit)); },
    }, b.edit.textContent ?? ""))] : []));
  }
  function syncTitle() {
    const t = (model.canvasTitle ?? `${model.kind ?? "Draft"}: ${model.title.trim() || "Untitled"}`).replace(/\s+/g, " ").slice(0, 80);
    if (t !== lastTitle) { lastTitle = t; canvas?.setTitle?.(t); }
  }
  function updateNote(text) {
    if (!root.querySelector("[data-agent]")) { note.hidden = true; return; }
    if (text) { note.replaceChildren(icon("sparkle", 12), text); note.hidden = false; }
  }
  function showFirstEdit() {
    const el = root.querySelector("[data-agent]");
    if (!el) return;
    el.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "center" });
    const target = el.querySelector(".fsk-ce-edit, .fsk-ce-field");
    if (target instanceof win.HTMLTextAreaElement) target.focus({ preventScroll: true });
    else if (target) placeCaret(target, textLen(target));
  }
  /** Bold and italic state, and the block type, follow the caret. */
  function updateTools() {
    const on = !!current && current.edit.isConnected && !publishing;
    typeSel.disabled = !on;
    boldBtn.disabled = italicBtn.disabled = linkBtn.disabled = !on;
    if (current) typeSel.value = current.type;
    const state = (cmd) => { try { return on && doc.queryCommandState(cmd); } catch { return false; } };
    boldBtn.setAttribute("aria-pressed", String(state("bold")));
    italicBtn.setAttribute("aria-pressed", String(state("italic")));
  }

  // ---------- sharing with the agent ----------
  function sync(b) {
    const i = blocks.indexOf(b);
    if (i >= 0) model.blocks[i] = readBlock(b);
    b.el.removeAttribute("data-agent");
    changed();
  }
  function changed() {
    if (model.publishedAt) editedSincePublish = true;
    updateCounts();
    updateHeader();
    updateNote();
    relabel();
    updateToc();
    setStatus("pending");
    win.clearTimeout(timer);
    timer = win.setTimeout(flush, SHARE_DELAY_MS);
  }
  function flush() {
    win.clearTimeout(timer);
    timer = 0;
    const patch = {};
    if (model.title !== shared.title) patch.title = model.title;
    if ((model.subtitle ?? "") !== (shared.subtitle ?? "")) patch.subtitle = model.subtitle;
    if (!same(model.blocks, shared.blocks)) patch.blocks = model.blocks;
    if (model.publishedAt !== shared.publishedAt) patch.publishedAt = model.publishedAt;
    if (model.url !== shared.url) patch.url = model.url;
    if (!Object.keys(patch).length) { setStatus(lastResult); return; }
    const before = shared;
    shared = { ...shared, ...structuredClone(patch) };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas?.setState?.(structuredClone(patch)), (res) => {
      if (res?.ok === false) { shared = before; setStatus("error"); return; }
      lastResult = res?.notSent?.length ? "partial" : "saved";
      setStatus(lastResult);
    });
    syncTitle();
    actions?.onChange?.(structuredClone(model));
  }

  /** The agent's edit. A three-way merge: what the agent changed wins; what only the user changed (not shared yet) stays. */
  function applyRemote(next) {
    const remote = normalize(structuredClone(next));
    const base = shared;
    const active = activeEl();
    const edited = [];
    const titleChanged = remote.title !== base.title;
    const dekChanged = (remote.subtitle ?? "") !== (base.subtitle ?? "");
    let list = model.blocks;
    if (!same(remote.blocks, base.blocks)) {
      const baseById = new Map(base.blocks.map((x) => [x.id, x]));
      const localById = new Map(model.blocks.map((x) => [x.id, x]));
      const remoteIds = new Set(remote.blocks.map((x) => x.id));
      const merged = [];
      for (const r of remote.blocks) {
        const b = baseById.get(r.id);
        const l = localById.get(r.id);
        if (!b || !same(r, b)) { edited.push(r.id); merged.push(r); } else if (l) merged.push(l);
        // else: the user removed it and the agent didn't touch it, so it stays removed
      }
      // Blocks the user added since the last share stay, after the block they followed.
      model.blocks.forEach((l, i) => {
        if (baseById.has(l.id) || remoteIds.has(l.id)) return;
        const prev = model.blocks[i - 1];
        merged.splice(prev ? merged.findIndex((x) => x.id === prev.id) + 1 : 0, 0, l);
      });
      list = merged;
    }
    model = structuredClone({ ...remote, title: titleChanged ? remote.title : model.title, subtitle: dekChanged ? remote.subtitle : model.subtitle, blocks: list });
    shared = remote;
    syncDom(active, new Set(edited));
    if (edited.length || titleChanged || dekChanged) { if (model.publishedAt) editedSincePublish = true; }
    updateCounts();
    updateHeader();
    updateToc();
    syncTitle();
    showAgentEdits(edited, titleChanged, dekChanged);
    if (model.title !== shared.title || (model.subtitle ?? "") !== (shared.subtitle ?? "") || !same(model.blocks, shared.blocks)) changed(); // share the user's unsent writing on top
    else { win.clearTimeout(timer); timer = 0; setStatus(lastResult); }
  }

  function syncDom(active, edited) {
    setValue(titleEl, model.title, active);
    setValue(dekEl, model.subtitle ?? "", active);
    const byId = new Map(blocks.map((b) => [b.id, b]));
    const focused = blockOf(active);
    const at = focused ? caretIn(focused.edit) : null;
    const before = focused ? focused.edit.textContent ?? "" : "";
    const next = model.blocks.map((data) => {
      const old = byId.get(data.id);
      byId.delete(data.id);
      if (!old || old.type !== data.type) {
        const nb = makeBlock(data);
        old?.el.replaceWith(nb.el);
        return nb;
      }
      if (edited.has(data.id)) fillBlock(old.edit, data);
      return old;
    });
    byId.forEach((b) => b.el.remove());
    next.forEach((b, i) => { const atEl = bodyEl.children[i]; if (atEl !== b.el) bodyEl.insertBefore(b.el, atEl ?? null); });
    blocks = next;
    if (current && !blocks.includes(current)) current = blocks.find((b) => b.id === current?.id) ?? null;
    relabel();
    fit(titleEl);
    fit(dekEl);
    // The caret stays where the user was writing, even when the agent rewrote that block.
    if (focused) {
      const now = blocks.find((b) => b.id === focused.id);
      if (now && at) {
        const [s, e] = remap(before, now.edit.textContent ?? "", at[0], at[1]);
        placeCaret(now.edit, s, e);
      }
    }
  }

  function showAgentEdits(ids, title, dek) {
    root.querySelectorAll("[data-agent]").forEach((e) => e.removeAttribute("data-agent"));
    const els = [title ? titleBlock : null, dek ? dekBlock : null, ...ids.map((id) => blocks.find((b) => b.id === id)?.el ?? null)]
      .filter((e) => !!e);
    for (const el of els) {
      el.setAttribute("data-agent", "");
      el.classList.remove("fsk-ce-flash");
      void el.offsetWidth; // restart the fade
      el.classList.add("fsk-ce-flash");
    }
    if (!els.length) { updateNote(); return; }
    const parts = [title && "the title", dek && "the summary", ids.length > 0 && `${ids.length} ${ids.length === 1 ? "block" : "blocks"}`].filter(Boolean);
    const what = parts.join(" and ");
    live.textContent = `The agent edited ${what}.`;
    updateNote(`The agent edited ${what}`);
  }

  // ---------- formatting ----------
  function format(cmd) {
    if (!current) return;
    try { doc.execCommand(cmd); } catch { return; }
    sync(current);
    updateTools();
  }

  let linkBox = null;
  function closeLink(restore) {
    if (!linkBox) return;
    linkBox.remove();
    linkBox = null;
    linkBtn.setAttribute("aria-expanded", "false");
    if (restore && current && linkRange) {
      current.edit.focus({ preventScroll: true });
      selection()?.setBaseAndExtent(linkRange.startContainer, linkRange.startOffset, linkRange.endContainer, linkRange.endOffset);
    }
  }
  function openLink() {
    if (!current) return;
    if (linkBox) { closeLink(true); return; }
    const r = range();
    if (!r || !current.edit.contains(r.startContainer)) return;
    linkRange = r.cloneRange();
    const anchor = (r.startContainer.nodeType === Node.ELEMENT_NODE ? (r.startContainer) : r.startContainer.parentElement)?.closest("a");
    const existing = anchor && current.edit.contains(anchor) ? anchor : null;
    const input = h("input", { type: "url", placeholder: "https://… or /help/…", "aria-label": "Link address", value: existing?.getAttribute("href") ?? "" });
    const err = h("p", { class: "fsk-ce-linkerr", role: "alert", hidden: true });
    const apply = () => {
      let href = input.value.trim();
      if (href && !/^[a-z]+:|^\//i.test(href)) href = `https://${href}`;
      if (!safeHref(href)) { err.textContent = "Use a full address (https://…) or a path in your app (/…)."; err.hidden = false; input.focus(); return; }
      closeLink(true);
      const b = current;
      if (!b) return;
      if (existing) { existing.setAttribute("href", href); }
      else if (linkRange?.collapsed) { doc.execCommand("insertHTML", false, ""); linkRange.insertNode(h("a", { href, rel: "noopener noreferrer", target: "_blank" }, href)); }
      else doc.execCommand("createLink", false, href);
      sync(b);
    };
    const remove = () => {
      closeLink(true);
      const b = current;
      if (!existing || !b) return;
      existing.replaceWith(...Array.from(existing.childNodes));
      sync(b);
    };
    linkBox = h("div", {
      class: "fsk-ce-linkbox", role: "dialog", "aria-label": existing ? "Edit link" : "Add link",
      onkeydown: (e) => {
        if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeLink(true); }
        if (e.key === "Enter") { e.preventDefault(); apply(); }
      },
    },
      input,
      h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: apply }, existing ? "Save" : "Add"),
      existing && h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: remove }, "Remove"),
      err);
    fmt.append(linkBox);
    linkBtn.setAttribute("aria-expanded", "true");
    input.focus();
  }

  // ---------- publish ----------
  async function publish() {
    if (!actions?.publish || publishing) return;
    flush();
    publishing = true;
    alertEl.hidden = true;
    updateHeader();
    updateTools();
    bodyEl.querySelectorAll(".fsk-ce-edit").forEach((e) => e.setAttribute("contenteditable", "false"));
    titleEl.readOnly = dekEl.readOnly = true;
    try {
      const res = await actions.publish(structuredClone(model));
      model.publishedAt = new Date().toISOString();
      if (res && res.url) model.url = res.url;
      editedSincePublish = false;
      live.textContent = "Published.";
      flush();
    } catch (e) {
      const msg = e instanceof Error && e.message ? e.message : "Something went wrong.";
      alertEl.replaceChildren(icon("alert", 15), h("span", {}, `Couldn't publish: ${msg} Your draft is saved.`),
        h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => void publish() }, "Try again"));
      alertEl.hidden = false;
    } finally {
      publishing = false;
      if (root.isConnected) {
        bodyEl.querySelectorAll(".fsk-ce-edit").forEach((e) => e.setAttribute("contenteditable", "true"));
        titleEl.readOnly = dekEl.readOnly = false;
        updateHeader();
        updateTools();
      }
    }
  }

  // ---------- the user's writing ----------
  function onInput(e) {
    const t = e.target;
    if (t === titleEl || t === dekEl) {
      const ta = t;
      if (ta.value.includes("\n")) { const pos = ta.selectionStart; ta.value = ta.value.replace(/\s*\n+\s*/g, " "); ta.setSelectionRange(pos, pos); }
      if (ta === titleEl) { model.title = ta.value; titleBlock.removeAttribute("data-agent"); }
      else { model.subtitle = ta.value; dekBlock.removeAttribute("data-agent"); }
      fit(ta);
      changed();
      return;
    }
    const b = blockOf(t);
    if (!b) return;
    // A browser leaves a <br> in a block it emptied: clear it so the placeholder shows.
    if (!isList(b.type) && !textLen(b.edit) && b.edit.querySelector("br") && !b.edit.querySelector("br + *")) b.edit.replaceChildren();
    if (isList(b.type) && !b.edit.querySelector("li")) { convert(b, "p", null); return; }
    if (b.type === "p") {
      const lead = b.edit.textContent ?? "";
      const hit = SHORTCUTS.find(([re]) => re.test(lead));
      if (hit) {
        const [re, type] = hit;
        const [first] = pointAt(b.edit, 0);
        const cut = (lead.match(re)?.[0] ?? "").length;
        if (first.nodeType === Node.TEXT_NODE) first.nodeValue = (first.nodeValue ?? "").slice(cut);
        convert(b, type, [0, 0]);
        return;
      }
    }
    sync(b);
  }

  function onKey(e) {
    if (e.isComposing) return;
    const t = e.target;
    const mod = e.metaKey || e.ctrlKey;
    if (t === titleEl || t === dekEl) {
      const ta = t;
      const atEnd = ta.selectionStart === ta.value.length;
      if (e.key === "Enter" || (e.key === "ArrowDown" && atEnd && !mod && !e.altKey)) {
        e.preventDefault();
        if (ta === titleEl) { dekEl.focus(); dekEl.setSelectionRange(0, 0); } else if (blocks[0]) placeCaret(blocks[0].edit, 0);
      } else if (e.key === "ArrowUp" && !mod && !e.altKey && ta === dekEl && ta.selectionStart === 0) { e.preventDefault(); titleEl.focus(); titleEl.setSelectionRange(titleEl.value.length, titleEl.value.length); }
      return;
    }
    const b = blockOf(t);
    if (!b) return;
    const i = blocks.indexOf(b);
    if (mod && !e.altKey && (e.key === "b" || e.key === "i")) { e.preventDefault(); format(e.key === "b" ? "bold" : "italic"); return; }
    if (mod && !e.altKey && e.key === "k") { e.preventDefault(); current = b; openLink(); return; }
    const r = range();
    if (!r) return;
    const at = caretIn(b.edit) ?? [0, 0];
    const len = textLen(b.edit);

    if (e.key === "Enter" && !e.shiftKey) {
      if (isList(b.type)) {
        const li = (r.startContainer.nodeType === Node.ELEMENT_NODE ? (r.startContainer) : r.startContainer.parentElement)?.closest("li");
        if (!li || li.textContent) return; // the browser adds the next item
        // Enter on an empty item leaves the list.
        e.preventDefault();
        li.remove();
        const nb = insertBlock({ id: newId(), type: "p", text: "" }, i + 1);
        if (!b.edit.querySelector("li")) { removeBlock(i); } else sync(b);
        placeCaret(nb.edit, 0);
        sync(nb);
        return;
      }
      e.preventDefault();
      if (!r.collapsed) r.deleteContents();
      if (at[0] === 0 && len > 0) {
        // At the start: a new paragraph above, the caret stays with this text.
        insertBlock({ id: newId(), type: "p", text: "" }, i);
        placeCaret(b.edit, 0);
        sync(b);
        return;
      }
      // Split at the caret: the rest of the text moves to a new paragraph.
      const tail = doc.createRange();
      tail.selectNodeContents(b.edit);
      tail.setStart(r.endContainer, r.endOffset);
      const holder = h("div", {}, tail.extractContents());
      const nb = insertBlock({ id: newId(), type: "p", text: tidy(toMd(holder)) }, i + 1);
      sync(b);
      placeCaret(nb.edit, 0);
      sync(nb);
      return;
    }

    if (e.key === "Backspace" && r.collapsed && at[0] === 0) {
      if (isList(b.type)) {
        const items = Array.from(b.edit.querySelectorAll(":scope > li"));
        if (!items[0]?.contains(r.startContainer) && items[0] !== r.startContainer) return;
        e.preventDefault();
        if (items.length === 1) { convert(b, "p", [0, 0]); return; }
        const first = readBlock(b).items?.[0] ?? "";
        items[0].remove();
        sync(b);
        const nb = insertBlock({ id: newId(), type: "p", text: first }, i);
        placeCaret(nb.edit, 0);
        sync(nb);
        return;
      }
      if (b.type !== "p") { e.preventDefault(); convert(b, "p", [0, 0]); return; }
      const prev = blocks[i - 1];
      if (!prev) return;
      e.preventDefault();
      if (!len) { removeBlock(i); placeCaret(prev.edit, textLen(prev.edit)); changed(); return; }
      if (isList(prev.type)) return;
      // Join this paragraph onto the one before it.
      const join = textLen(prev.edit);
      const md = readBlock(b).text ?? "";
      prev.edit.append(...inline(md));
      removeBlock(i);
      placeCaret(prev.edit, join);
      sync(prev);
      return;
    }

    if ((e.key === "ArrowUp" || e.key === "ArrowDown") && r.collapsed && !e.shiftKey && !mod && !e.altKey) {
      const up = e.key === "ArrowUp";
      if (!atEdge(b.edit, r, up, at[0], len)) return;
      const to = blocks[i + (up ? -1 : 1)];
      if (to) { e.preventDefault(); placeCaret(to.edit, up ? textLen(to.edit) : 0); }
      else if (up) { e.preventDefault(); dekEl.focus(); dekEl.setSelectionRange(dekEl.value.length, dekEl.value.length); }
    }
  }

  /** Is the caret on the block's first line (up) or last line (down)? */
  function atEdge(el, r, up, at, len) {
    if (up ? at === 0 : at === len) return true;
    const rect = r.getClientRects()[0];
    if (!rect) return false;
    const box = el.getBoundingClientRect();
    const line = parseFloat(win.getComputedStyle(el).lineHeight) || 24;
    return up ? rect.top - box.top < line * 0.75 : box.bottom - rect.bottom < line * 0.75;
  }

  /** Paste as plain text. Several paragraphs become several blocks; in a list, several items. */
  function onPaste(e) {
    const text = e.clipboardData?.getData("text/plain");
    if (text == null) return;
    e.preventDefault();
    const t = e.target;
    if (t === titleEl || t === dekEl) { doc.execCommand("insertText", false, text.replace(/\s*\n+\s*/g, " ")); return; }
    const b = blockOf(t);
    if (!b) return;
    const parts = text.replace(/\r/g, "").split(isList(b.type) ? /\n+/ : /\n\s*\n/).map((x) => x.trim()).filter(Boolean);
    if (!parts.length) return;
    doc.execCommand("insertText", false, isList(b.type) ? parts[0] : parts[0].replace(/\n/g, " "));
    if (isList(b.type)) {
      const r = range();
      const li = (r?.startContainer.nodeType === Node.ELEMENT_NODE ? (r.startContainer) : r?.startContainer.parentElement)?.closest("li");
      let after = li ?? null;
      for (const p of parts.slice(1)) { const item = h("li", {}, p); after?.after(item); after = item; }
      sync(b);
      return;
    }
    sync(b);
    let at = blocks.indexOf(b);
    let last = b;
    for (const p of parts.slice(1)) last = insertBlock({ id: newId(), type: "p", text: p.replace(/\n/g, " ").replace(/([\\`*[\]])/g, "\\$1") }, ++at);
    if (last !== b) { placeCaret(last.edit, textLen(last.edit)); sync(last); }
  }

  function onFocusIn(e) {
    const b = blockOf(e.target);
    if (b) current = b;
    else if (e.target === titleEl || e.target === dekEl) current = null;
    updateTools();
  }
  function onFocusOut() { if (timer) flush(); }
  function onSelection() {
    if (linkBox) return;
    const r = range();
    const b = r ? blockOf(r.startContainer) : undefined;
    if (b) { current = b; caret = caretIn(b.edit); }
    updateTools();
  }
  typeSel.addEventListener("change", () => {
    const b = current;
    if (b) convert(b, typeSel.value, caret);
  });

  function addParagraph() {
    const last = blocks[blocks.length - 1];
    if (last && last.type === "p" && !textLen(last.edit)) { placeCaret(last.edit, 0); return; }
    const nb = insertBlock({ id: newId(), type: "p", text: "" }, blocks.length);
    placeCaret(nb.edit, 0);
    sync(nb);
  }

  // ---------- draw ----------
  blocks = model.blocks.map(makeBlock);
  bodyEl.append(...blocks.map((b) => b.el));
  relabel();
  updateCounts();
  updateHeader();
  updateToc();
  setStatus("saved");
  syncTitle();
  const page = h("div", { class: "fsk-ce-doc", oninput: onInput, onkeydown: onKey, onpaste: onPaste, onfocusin: onFocusIn, onfocusout: onFocusOut },
    topEl,
    titleBlock,
    dekBlock,
    bylineEl,
    h("hr", { class: "fsk-ce-rule" }),
    bodyEl,
    h("button", { class: "fsk-ce-add", type: "button", onclick: addParagraph }, icon("plus", 14), "Add a paragraph"),
    h("p", { class: "fsk-ce-hint" }, icon("message", 14),
      h("span", {}, "Type ", h("kbd", {}, "##"), " for a heading, ", h("kbd", {}, "-"), " for a list, ", h("kbd", {}, ">"), " for a quote. I see your changes with your next message.")));
  root.replaceChildren(h("div", { class: "fsk fsk-ce" },
    h("div", { class: "fsk-ce-bar" },
      h("div", { class: "fsk-ce-bar-in" },
        fmt,
        h("div", { class: "fsk-ce-right" }, note, wordsEl, statusEl, publishBtn)),
      alertEl),
    h("div", { class: "fsk-ce-wrap" }, page, toc),
    live));
  fit(titleEl);
  fit(dekEl);
  doc.addEventListener("selectionchange", onSelection);
  const onOutside = (e) => { if (linkBox && !e.composedPath().includes(fmt)) closeLink(false); };
  doc.addEventListener("pointerdown", onOutside, true);
  const off = canvas?.onStateChange?.((next) => applyRemote(next));

  return () => {
    if (timer) flush(); // closing keeps the state: share what the user wrote last
    off?.();
    doc.removeEventListener("selectionchange", onSelection);
    doc.removeEventListener("pointerdown", onOutside, true);
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only preview card (a chat card action) of the article. */
export function mountMobile({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const s = normalize(structuredClone(data));
  const n = words(s);
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-cec", "aria-label": `${s.kind ?? "Draft"}: ${s.title || "Untitled"}` },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(kindIcon(s.kind), 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title || "Untitled"), h("p", { class: "fsk-sub" }, `${s.kind ?? "Draft"} · ${readTime(n)}${s.publishedAt ? " · Published" : " · Draft"}`))),
    s.subtitle && h("p", { class: "fsk-cec-dek" }, s.subtitle),
    h("div", { class: "fsk-cec-doc" }, s.blocks.slice(0, 5).map(staticBlock)),
    h("p", { class: "fsk-cec-foot" }, icon("pencil", 12), "Read-only here. Edit it on desktop, where the editor opens beside the chat.")));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this editor draws besides its article. No empty state: an empty draft is the editor itself, with its placeholders. */
export const states = ["loading", "error"];

/** "Help center / Reports" as a breadcrumb. */
const crumbsOf = (path) => {
  const parts = (path ?? "").split("/").map((x) => x.trim()).filter(Boolean);
  return parts.length ? h("span", { class: "fsk-ce-crumbs" }, parts.map((c, i) => [i > 0 && icon("chevron", 12), c])) : null;
};

const loadingLabel = (s) => (s.kind === "loading" ? s.label ?? "Loading the article…" : "");

/** The article as bones: summary, byline, then paragraphs, a heading, a numbered list and a callout. */
function articleSkeleton(title, subtitle) {
  const lines = (widths, i) => h("div", { class: "fsk-ce-sk-lines" }, widths.map((w) => bone(`${w}%`, "12px", { i })));
  return [
    h("div", { class: "fsk-ce-top" }, bone("96px", "22px", { cls: "fsk-ce-sk-pill" }), crumbsOf(subtitle) ?? bone("120px", "12px", { i: 1 })),
    h("h2", { class: "fsk-ce-title" }, title || bone("68%", "30px")),
    h("div", { class: "fsk-ce-sk-lines", style: { marginTop: "12px" } }, bone("92%", "15px", { i: 1 }), bone("54%", "15px", { i: 1 })),
    h("div", { class: "fsk-ce-by" }, bone("26px", "26px", { cls: "fsk-ce-sk-round", i: 2 }), bone("140px", "12px", { i: 2 })),
    h("hr", { class: "fsk-ce-rule" }),
    lines([100, 97, 62], 2),
    h("div", { class: "fsk-ce-sk-h" }, bone("38%", "18px", { i: 3 })),
    [86, 74, 80].map((w, i) => h("div", { class: "fsk-ce-sk-li", style: { marginTop: "12px" } }, bone("14px", "12px", { i: 3 + i }), bone(`${w}%`, "12px", { i: 3 + i }))),
    h("div", { class: "fsk-ce-sk-callout" }, bone("90%", "12px", { i: 5 }), bone("48%", "12px", { i: 5 })),
  ];
}

/**
 * Desktop canvas in a state: the editor's page with the article as bones while it loads or the agent writes it,
 * or a centered error block under the title. It doesn't change the canvas status: the agent writes the first draft in EDIT_MODE.
 */
export function mountState({ root, head, state, title, subtitle, canvas, canvasTitle, eyebrow }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const kind = eyebrow ?? "Draft";
  canvas?.setTitle?.((canvasTitle ?? `${kind}: ${title?.trim() || "Untitled"}`).replace(/\s+/g, " ").slice(0, 80));
  const loading = state.kind === "loading";
  let dispose = () => {};
  let body;
  if (state.kind === "loading") body = h("div", { "aria-hidden": "true" }, articleSkeleton(title, subtitle));
  else {
    let block;
    if (state.kind === "empty") block = emptyBlock(state);
    else { const e = errorBlock(state); dispose = e.dispose; block = e.el; }
    body = [
      h("div", { class: "fsk-ce-top" }, h("span", { class: "fsk-badge fsk-badge--agent" }, icon(kindIcon(kind), 12), kind), crumbsOf(subtitle)),
      h("h2", { class: "fsk-ce-title" }, title || "Untitled"),
      h("div", { class: "fsk-ce-st-box" }, h("div", { class: "fsk-ce-st-panel" }, block)),
    ];
  }
  root.replaceChildren(h("div", {
    class: "fsk fsk-ce fsk-ce-st", "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, loadingLabel(state)),
    loading && h("div", { class: "fsk-ce-bar", "aria-hidden": "true" },
      h("div", { class: "fsk-ce-bar-in" },
        h("div", { class: "fsk-ce-fmt" }, bone("96px", "30px"), bone("30px", "30px", { i: 1 }), bone("30px", "30px", { i: 1 }), bone("30px", "30px", { i: 1 })),
        h("div", { class: "fsk-ce-right" }, h("span", { class: "fsk-ce-status" }, h("span", { class: "fsk-ce-dot" }), loadingLabel(state))))),
    h("div", { class: "fsk-ce-wrap" }, h("div", { class: "fsk-ce-doc" }, body))));
  return () => { dispose(); root.replaceChildren(); };
}

/** Mobile preview card in a state: its header above paragraph bones, or an error block. Read-only: report displayed() yourself. */
export function mountMobileState({ root, head, state, title, subtitle, eyebrow, surface = "mobile" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ce", CSS);
  const card = stateCard({
    state: state.kind === "loading" ? { ...state, label: loadingLabel(state) } : state, cls: "fsk-cec", icon: kindIcon(eyebrow), title, subtitle, surface,
    skeleton: () => h("div", { class: "fsk-cec-doc fsk-sk-lines" }, [100, 94, 98, 60, 0, 42, 100, 88].map((w, i) => (w ? bone(`${w}%`, "10px", { i }) : h("span", { style: { height: "4px" } })))),
  });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    kind: "Help article",
    collection: "Help center / Reports",
    title: "Schedule a report",
    subtitle: "Send any report to your team's inbox every day, week or month, without exporting it by hand.",
    author: "Dana Ortiz",
    tags: ["Reports", "Email"],
    blocks: [
      { id: "intro", type: "p", text: "A scheduled report arrives as a PDF with a link to the live report, so everyone sees the same numbers without opening the app." },
      { id: "h-setup", type: "h2", text: "Set up a schedule" },
      { id: "steps", type: "ol", items: ["Open the report and choose **Schedule**.", "Pick who gets it: people, teams or any email address.", "Choose how often and at what time, then select **Save**."] },
      { id: "tz", type: "callout", text: "Schedules use the time zone in your **workspace settings**, not each person's own." },
      { id: "h-change", type: "h2", text: "Change or pause a schedule" },
      { id: "change", type: "p", text: "Go to [Settings › Reports](/settings/reports) to see every schedule in your workspace. Pause one to stop sending without losing it, or change who gets it at any time." },
      { id: "h-who", type: "h3", text: "Who can create schedules" },
      { id: "who", type: "p", text: "Scheduled reports are on the *Business* and *Enterprise* plans. Admins choose who may create them on the Permissions page." },
      { id: "h-help", type: "h2", text: "If a report doesn't arrive" },
      { id: "help", type: "ul", items: ["Check the recipient's spam folder.", "Make sure the schedule isn't paused.", "An empty PDF means the report had no data for that period."] },
    ],
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
