---
title: "Page Editor · UI SDK — StyleX Blocks"
description: "Collaborative document editor with a resizable pages tree and live block outline, formatting toolbar, page-width switcher, inline-editable structured blocks (headings, paragraphs, callouts, checklists, code snippets), collaborator presence, review comments, and share controls."
url: "https://stylexblocks.com/block/ui-sdk/page-editor/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Page Editor block

Collaborative document editor with a resizable pages tree and live block outline, formatting toolbar, page-width switcher, inline-editable structured blocks (headings, paragraphs, callouts, checklists, code snippets), collaborator presence, review comments, and share controls.

- Behavior engine: UI SDK
- Category: [App shells](https://stylexblocks.com/blocks/app-shells.md)
- Built with: [Alert](https://stylexblocks.com/components/ui-sdk/alert.md), [Avatar](https://stylexblocks.com/components/ui-sdk/avatar.md), [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Breadcrumb](https://stylexblocks.com/components/ui-sdk/breadcrumb.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Code Block](https://stylexblocks.com/components/ui-sdk/code-block.md), [Dialog](https://stylexblocks.com/components/ui-sdk/dialog.md), [Empty State](https://stylexblocks.com/components/ui-sdk/empty-state.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Menu](https://stylexblocks.com/components/ui-sdk/menu.md), [Popover](https://stylexblocks.com/components/ui-sdk/popover.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [Select](https://stylexblocks.com/components/ui-sdk/select.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Splitter](https://stylexblocks.com/components/ui-sdk/splitter.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Tabs](https://stylexblocks.com/components/ui-sdk/tabs.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Textarea](https://stylexblocks.com/components/ui-sdk/textarea.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md), [Toggle Group](https://stylexblocks.com/components/ui-sdk/toggle-group.md), [Toolbar](https://stylexblocks.com/components/ui-sdk/toolbar.md), [Tree View](https://stylexblocks.com/components/ui-sdk/tree-view.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/page-editor/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add page-editor
```

Equivalent: `npx shadcn add @stylexblocks/page-editor`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/page-editor.json

## Usage

```tsx
import { PageEditor } from "#components/blocks/ui-sdk/page-editor.tsx";

export function Example() {
  return (
    <div style={{ height: "100dvh" }}>
      <PageEditor />
    </div>
  );
}
```

## Source

`components/blocks/ui-sdk/page-editor.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { Fragment, useCallback, useMemo, useRef, useState } from "react";
import { Alert } from "#components/ui/ui-sdk/alert.tsx";
import { Avatar } from "#components/ui/ui-sdk/avatar.tsx";
import { Badge } from "#components/ui/ui-sdk/badge.tsx";
import { Breadcrumb } from "#components/ui/ui-sdk/breadcrumb.tsx";
import { Button } from "#components/ui/ui-sdk/button.tsx";
import { Center } from "#components/ui/ui-sdk/center.tsx";
import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";
import { CodeBlock } from "#components/ui/ui-sdk/code-block.tsx";
import { Dialog } from "#components/ui/ui-sdk/dialog.tsx";
import { EmptyState } from "#components/ui/ui-sdk/empty-state.tsx";
import { Grid } from "#components/ui/ui-sdk/grid.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { Icon } from "#components/ui/ui-sdk/icon.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { Menu } from "#components/ui/ui-sdk/menu.tsx";
import { Popover } from "#components/ui/ui-sdk/popover.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";
import { Select } from "#components/ui/ui-sdk/select.tsx";
import { Separator } from "#components/ui/ui-sdk/separator.tsx";
import { Splitter } from "#components/ui/ui-sdk/splitter.tsx";
import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Tabs } from "#components/ui/ui-sdk/tabs.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Textarea } from "#components/ui/ui-sdk/textarea.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import { ToggleGroup } from "#components/ui/ui-sdk/toggle-group.tsx";
import { Toolbar } from "#components/ui/ui-sdk/toolbar.tsx";
import { TreeView } from "#components/ui/ui-sdk/tree-view.tsx";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import {
  accentPalette,
  amberPalette,
  bluePalette,
  emeraldPalette,
  grayPalette,
  purplePalette,
  redPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { durations } from "@stylexblocks/ui/tokens/durations.stylex.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

const NARROW_SIDEBAR = "@container page-editor (max-width: 780px)";
const COMPACT_HEADER = "@container page-editor (max-width: 580px)";

/* -------------------------------------------------------------------------- */
/* Types                                                                      */
/* -------------------------------------------------------------------------- */

export type BlockKind = "heading" | "paragraph" | "callout" | "checklist" | "code";
export type CalloutTone = "info" | "warning" | "success";
export type TextAlign = "left" | "center" | "right";
export type PageStatus = "Draft" | "In Review" | "Approved";
type PageWidth = "standard" | "wide" | "compact";
type SidebarTab = "pages" | "outline";
type AccessLevel = "workspace-edit" | "org-comment" | "reviewers-only";

export interface ChecklistItem {
  id: string;
  label: string;
  checked: boolean;
}

export interface EditorBlock {
  id: string;
  kind: BlockKind;
  level?: 2 | 3;
  text?: string;
  bold?: boolean;
  italic?: boolean;
  mono?: boolean;
  align?: TextAlign;
  calloutTone?: CalloutTone;
  calloutTitle?: string;
  items?: ChecklistItem[];
  codeFilename?: string;
  codeLanguage?: string;
}

export interface EditorComment {
  id: string;
  author: string;
  initials: string;
  paletteKey: "purple" | "blue" | "emerald" | "amber";
  timestamp: string;
  body: string;
  resolved?: boolean;
}

export interface EditorPageDocument {
  id: string;
  folderId: string;
  folderName: string;
  docCode: string;
  title: string;
  subtitle: string;
  status: PageStatus;
  updatedAt: string;
  blocks: EditorBlock[];
  comments: EditorComment[];
}

interface WorkspaceFolder {
  id: string;
  name: string;
}

interface Collaborator {
  id: string;
  name: string;
  initials: string;
  role: string;
  status: string;
  paletteKey: "purple" | "blue" | "emerald";
}

/* -------------------------------------------------------------------------- */
/* Demo Data                                                                  */
/* -------------------------------------------------------------------------- */

const COLLABORATOR_PALETTES = {
  purple: purplePalette,
  blue: bluePalette,
  emerald: emeraldPalette,
  amber: amberPalette,
} as const;

const COLLABORATORS: Collaborator[] = [
  {
    id: "clara",
    name: "Clara Lindholm",
    initials: "CL",
    role: "Design Systems Lead",
    status: "Editing",
    paletteKey: "purple",
  },
  {
    id: "mateo",
    name: "Mateo Silva",
    initials: "MS",
    role: "Accessibility Engineer",
    status: "Viewing",
    paletteKey: "blue",
  },
  {
    id: "hannah",
    name: "Hannah Sato",
    initials: "HS",
    role: "Staff Frontend Architect",
    status: "Reviewing",
    paletteKey: "emerald",
  },
];

const WORKSPACE_FOLDERS: WorkspaceFolder[] = [
  { id: "design-systems", name: "Design Systems" },
  { id: "release-planning", name: "Release Planning" },
];

const INITIAL_PAGES: EditorPageDocument[] = [
  {
    id: "rfc-color-motion",
    folderId: "design-systems",
    folderName: "Design Systems",
    docCode: "RFC-019",
    title: "Design Token RFC · Color Contrast & Motion Guidelines",
    subtitle:
      "Standardizing OKLCH perceptual contrast thresholds and reduced-motion fallbacks across v4 semantic tokens.",
    status: "In Review",
    updatedAt: "Edited 4 min ago",
    blocks: [
      {
        id: "b-1",
        kind: "heading",
        level: 2,
        text: "1. Perceptual Contrast Guardrails",
        align: "left",
      },
      {
        id: "b-2",
        kind: "paragraph",
        text: "Every interactive surface must maintain at least 4.5:1 contrast for body typography and 3:1 for focus rings and control boundaries in both light and dark color schemes. Semantic elevation steps derive from the base OKLCH lightness ramp rather than opaque overlays so nested panels stay legible at every contrast setting.",
        align: "left",
      },
      {
        id: "b-3",
        kind: "callout",
        calloutTone: "info",
        calloutTitle: "Scope for the v4.2 token release",
        text: "These rules apply to semanticColors.fgMuted, semanticColors.borderEmphasized, and every palette solid/contrast pair. Legacy hex aliases remain deprecated until Q3.",
      },
      {
        id: "b-4",
        kind: "heading",
        level: 2,
        text: "2. Reduced-Motion Fallbacks",
        align: "left",
      },
      {
        id: "b-5",
        kind: "paragraph",
        text: "Transient disclosures (menus, popovers, dialogs, and tree branches) animate opacity and subtle translation over 120–200ms using standard deceleration curves. When prefers-reduced-motion: reduce is active, spatial travel collapses to 0px and transition durations clamp to 0s.",
        align: "left",
      },
      {
        id: "b-6",
        kind: "code",
        codeFilename: "semantic-motion.stylex.ts",
        codeLanguage: "TypeScript",
        text: `import * as stylex from "@stylexjs/stylex";

export const motionTokens = stylex.defineVars({
  durationFast: {
    default: "120ms",
    "@media (prefers-reduced-motion: reduce)": "0s",
  },
  durationModerate: {
    default: "200ms",
    "@media (prefers-reduced-motion: reduce)": "0s",
  },
  easingStandard: "cubic-bezier(0.2, 0, 0, 1)",
});`,
      },
      {
        id: "b-7",
        kind: "heading",
        level: 2,
        text: "3. Rollout & Verification Checklist",
        align: "left",
      },
      {
        id: "b-8",
        kind: "checklist",
        items: [
          {
            id: "chk-1",
            label: "Audit all 22 OKLCH palette ramps against dark-surface WCAG AA targets",
            checked: true,
          },
          {
            id: "chk-2",
            label: "Verify reduced-motion overrides in Dialog, Popover, and TreeView recipes",
            checked: true,
          },
          {
            id: "chk-3",
            label: "Publish contrast regression snapshot suite to the CI pipeline",
            checked: false,
          },
          {
            id: "chk-4",
            label: "Collect final sign-off from Accessibility and Core Systems reviewers",
            checked: false,
          },
        ],
      },
    ],
    comments: [
      {
        id: "c-1",
        author: "Mateo Silva",
        initials: "MS",
        paletteKey: "blue",
        timestamp: "18m ago",
        body: "Confirmed that semanticColors.fgMuted passes 4.8:1 on bgPanel across all neutral bases in dark mode.",
      },
      {
        id: "c-2",
        author: "Hannah Sato",
        initials: "HS",
        paletteKey: "emerald",
        timestamp: "7m ago",
        body: "Should we also clamp Toast swipe spring durations to 0s when reduced motion is enabled?",
      },
    ],
  },
  {
    id: "spec-focus-model",
    folderId: "design-systems",
    folderName: "Design Systems",
    docCode: "SPEC-08",
    title: "Focus Ring & Keyboard Navigation Model",
    subtitle:
      "Consistent focus-visible geometry, roving tabindex contracts, and composite widget escape hatches.",
    status: "Approved",
    updatedAt: "Edited yesterday",
    blocks: [
      {
        id: "f-1",
        kind: "heading",
        level: 2,
        text: "Composite Roving Focus",
        align: "left",
      },
      {
        id: "f-2",
        kind: "paragraph",
        text: "Toolbars, segmented groups, tabs, and tree views expose a single Tab stop and move focus internally with arrow keys, Home, and End. Disabled controls stay discoverable with aria-disabled so screen reader users never lose context.",
        align: "left",
      },
      {
        id: "f-3",
        kind: "callout",
        calloutTone: "success",
        calloutTitle: "Approved for production",
        text: "Keyboard contracts verified across Safari, Chrome, and Firefox with VoiceOver and NVDA.",
      },
      {
        id: "f-4",
        kind: "checklist",
        items: [
          { id: "fc-1", label: "Toolbar roving focus wraps cleanly across nested ToggleGroups", checked: true },
          { id: "fc-2", label: "Dialog returns focus to triggering element on Escape", checked: true },
          { id: "fc-3", label: "TreeView supports typeahead matching on visible nodes", checked: true },
        ],
      },
    ],
    comments: [
      {
        id: "fc-m1",
        author: "Clara Lindholm",
        initials: "CL",
        paletteKey: "purple",
        timestamp: "1d ago",
        body: "Locked v1 of the focus ring tokens—ready for component adoption.",
      },
    ],
  },
  {
    id: "v4-2-migration",
    folderId: "release-planning",
    folderName: "Release Planning",
    docCode: "REL-42",
    title: "v4.2 Token Audit & Migration Notes",
    subtitle:
      "Automated codemod commands, deprecated alias timelines, and staged partner verification.",
    status: "Draft",
    updatedAt: "Edited 2 days ago",
    blocks: [
      {
        id: "m-1",
        kind: "heading",
        level: 2,
        text: "Automated Migration Command",
        align: "left",
      },
      {
        id: "m-2",
        kind: "paragraph",
        text: "Run the token codemod before upgrading @stylexblocks/ui to rewrite legacy elevation and surface references to the unified semanticColors scale.",
        align: "left",
      },
      {
        id: "m-3",
        kind: "code",
        codeFilename: "migrate-tokens.sh",
        codeLanguage: "Shell",
        text: `bunx @stylexblocks/codemod v4-semantic-tokens ./src
bun run typecheck && bun test`,
      },
      {
        id: "m-4",
        kind: "callout",
        calloutTone: "warning",
        calloutTitle: "Manual review required for custom themes",
        text: "Custom createTheme overrides that redefine fgSubtle directly should verify dark-mode contrast against bgMuted.",
      },
    ],
    comments: [],
  },
];

const BLOCK_KIND_LABELS: Record<BlockKind, string> = {
  heading: "Heading",
  paragraph: "Paragraph",
  callout: "Callout",
  checklist: "Checklist",
  code: "Code snippet",
};

const STATUS_CYCLE: PageStatus[] = ["Draft", "In Review", "Approved"];

const STATUS_PALETTE = {
  Draft: bluePalette,
  "In Review": amberPalette,
  Approved: emeraldPalette,
} as const;

const CALLOUT_PALETTE: Record<CalloutTone, typeof bluePalette> = {
  info: bluePalette,
  warning: amberPalette,
  success: emeraldPalette,
};

const ACCESS_OPTIONS = [
  { value: "workspace-edit", label: "Workspace editors can edit" },
  { value: "org-comment", label: "Anyone in org can comment" },
  { value: "reviewers-only", label: "Restricted to reviewers" },
] as const;

const LANGUAGE_OPTIONS = ["TypeScript", "CSS", "Shell", "JSON", "TSX"] as const;

const BLOCK_KIND_OPTIONS = (Object.keys(BLOCK_KIND_LABELS) as BlockKind[]).map(
  (kind) => ({ value: kind, label: BLOCK_KIND_LABELS[kind] }),
);

function createDefaultBlock(kind: BlockKind, id: string): EditorBlock {
  switch (kind) {
    case "heading":
      return { id, kind: "heading", level: 2, text: "New Section Heading", align: "left" };
    case "paragraph":
      return {
        id,
        kind: "paragraph",
        text: "Write supporting context, rationale, or edge-case notes here.",
        align: "left",
      };
    case "callout":
      return {
        id,
        kind: "callout",
        calloutTone: "info",
        calloutTitle: "Design note",
        text: "Highlight an important constraint, decision, or rollout milestone.",
      };
    case "checklist":
      return {
        id,
        kind: "checklist",
        items: [
          { id: `${id}-i1`, label: "Review token contrast in light and dark themes", checked: false },
          { id: `${id}-i2`, label: "Add unit test coverage for keyboard navigation", checked: false },
        ],
      };
    case "code":
      return {
        id,
        kind: "code",
        codeFilename: "tokens.stylex.ts",
        codeLanguage: "TypeScript",
        text: `export const surface = stylex.create({\n  card: { backgroundColor: semanticColors.bgPanel },\n});`,
      };
  }
}

function getBlockPreviewLabel(block: EditorBlock): string {
  switch (block.kind) {
    case "heading":
      return block.text?.trim() || "Untitled heading";
    case "paragraph":
      return block.text?.trim() || "Empty paragraph";
    case "callout":
      return block.calloutTitle?.trim() || block.text?.trim() || "Callout";
    case "checklist": {
      const total = block.items?.length ?? 0;
      const done = block.items?.filter((i) => i.checked).length ?? 0;
      return `Checklist (${done}/${total})`;
    }
    case "code":
      return block.codeFilename?.trim() || `${block.codeLanguage ?? "Code"} snippet`;
  }
}

function countDocumentWords(page: EditorPageDocument): number {
  const parts: string[] = [page.title, page.subtitle];
  for (const b of page.blocks) {
    if (b.text) parts.push(b.text);
    if (b.calloutTitle) parts.push(b.calloutTitle);
    if (b.items) {
      for (const item of b.items) parts.push(item.label);
    }
  }
  const tokens = parts.join(" ").trim().split(/\s+/).filter(Boolean);
  return tokens.length;
}

/* -------------------------------------------------------------------------- */
/* Inline SVG Icons (zero external icon packages)                             */
/* -------------------------------------------------------------------------- */

function SidebarIcon() {
  return (
    <Icon size="sm" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <rect x="2" y="2.5" width="12" height="11" rx="2" />
      <path d="M6 2.5v11" />
    </Icon>
  );
}

function ChevronRightIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="m6 4 4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function ChevronDownIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="m4 6 4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function FolderIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path
        d="M2 4.5A1.5 1.5 0 0 1 3.5 3h2.6a1.5 1.5 0 0 1 1.1.48l.8.9a1 1 0 0 0 .74.32H12.5A1.5 1.5 0 0 1 14 6.2v5.3A1.5 1.5 0 0 1 12.5 13h-9A1.5 1.5 0 0 1 2 11.5v-7Z"
        strokeLinejoin="round"
      />
    </Icon>
  );
}

function DocumentIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M4 2.5h5l3 3v8A1 1 0 0 1 11 14.5H4a1 1 0 0 1-1-1v-10a1 1 0 0 1 1-1Z" strokeLinejoin="round" />
      <path d="M9 2.5v3h3" strokeLinejoin="round" />
      <path d="M5.5 8.5h5M5.5 11h3.5" strokeLinecap="round" />
    </Icon>
  );
}

function PlusIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M8 3.25v9.5M3.25 8h9.5" strokeLinecap="round" />
    </Icon>
  );
}

function CommentIcon() {
  return (
    <Icon size="sm" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path
        d="M3 3.5h10a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H6.6L3.5 14v-2.5H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1Z"
        strokeLinejoin="round"
      />
    </Icon>
  );
}

function ShareIcon() {
  return (
    <Icon size="sm" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M8 2.5v7M5.25 5.25 8 2.5l2.75 2.75" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M3 9.5v3A1.5 1.5 0 0 0 4.5 14h7a1.5 1.5 0 0 0 1.5-1.5v-3" strokeLinecap="round" />
    </Icon>
  );
}

function CopyIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <rect x="5.5" y="5.5" width="8" height="8" rx="1.5" />
      <path d="M10.5 5.5V4a1.5 1.5 0 0 0-1.5-1.5H4A1.5 1.5 0 0 0 2.5 4v5A1.5 1.5 0 0 0 4 10.5h1.5" />
    </Icon>
  );
}

function BoldIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
      <path d="M4.5 3h4a2.5 2.5 0 0 1 0 5h-4V3Zm0 5h4.75a2.5 2.5 0 0 1 0 5H4.5V8Z" strokeLinejoin="round" />
    </Icon>
  );
}

function ItalicIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M9.5 3 6.5 13M6.5 3h5M4.5 13h5" strokeLinecap="round" />
    </Icon>
  );
}

function CodeInlineIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="m5.5 4.5-3.5 3.5 3.5 3.5M10.5 4.5l3.5 3.5-3.5 3.5" strokeLinecap="round" strokeLinejoin="round" />
    </Icon>
  );
}

function AlignLeftIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M2.5 4h11M2.5 8h7.5M2.5 12h9.5" strokeLinecap="round" />
    </Icon>
  );
}

function AlignCenterIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M2.5 4h11M4.25 8h7.5M3.25 12h9.5" strokeLinecap="round" />
    </Icon>
  );
}

function AlignRightIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M2.5 4h11M6 8h7.5M4 12h9.5" strokeLinecap="round" />
    </Icon>
  );
}

function ArrowUpIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M8 12.5v-9M4.5 7 8 3.5 11.5 7" strokeLinecap="round" strokeLinejoin="round" />
    </Icon>
  );
}

function ArrowDownIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M8 3.5v9M4.5 9 8 12.5 11.5 9" strokeLinecap="round" strokeLinejoin="round" />
    </Icon>
  );
}

function TrashIcon() {
  return (
    <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M3 4.5h10M6 4.5V3h4v1.5M4.5 4.5l.6 8.2a1 1 0 0 0 1 .8h3.8a1 1 0 0 0 1-.8l.6-8.2" strokeLinecap="round" strokeLinejoin="round" />
    </Icon>
  );
}

function CloseIcon() {
  return (
    <Icon size="sm" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="m4 4 8 8M12 4l-8 8" strokeLinecap="round" />
    </Icon>
  );
}

function BlockKindIcon({ kind }: { kind: BlockKind }) {
  switch (kind) {
    case "heading":
      return (
        <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
          <path d="M3.5 3.5v9M11.5 3.5v9M3.5 8h8" strokeLinecap="round" />
        </Icon>
      );
    case "paragraph":
      return (
        <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
          <path d="M3 4.5h10M3 8h10M3 11.5h6.5" strokeLinecap="round" />
        </Icon>
      );
    case "callout":
      return (
        <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
          <circle cx="8" cy="8" r="5.5" />
          <path d="M8 7.5v3M8 5.2v.1" strokeLinecap="round" />
        </Icon>
      );
    case "checklist":
      return (
        <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
          <path d="m2.5 5 1.5 1.5L6.5 4M9 5.25h4.5M2.5 11l1.5 1.5L6.5 10M9 11.25h4.5" strokeLinecap="round" strokeLinejoin="round" />
        </Icon>
      );
    case "code":
      return <CodeInlineIcon />;
  }
}

function CalloutGlyph({ tone }: { tone: CalloutTone }) {
  if (tone === "warning") {
    return (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
        <path d="M8 2.5 14 13H2L8 2.5Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
        <path d="M8 6.5v3M8 11.2v.1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    );
  }
  if (tone === "success") {
    return (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
        <circle cx="8" cy="8" r="5.5" stroke="currentColor" strokeWidth="1.5" />
        <path d="m5.75 8.1 1.5 1.5 3.25-3.4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  }
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <circle cx="8" cy="8" r="5.5" stroke="currentColor" strokeWidth="1.5" />
      <path d="M8 7.4v3.1M8 5.3v.1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

/* -------------------------------------------------------------------------- */
/* Styles                                                                     */
/* -------------------------------------------------------------------------- */

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "page-editor",
    containerType: "inline-size",
    fontFamily: fonts.body,
    height: "100%",
    minHeight: "640px",
    overflowX: "hidden",
    overflowY: "hidden",
    width: "100%",
  },
  topBar: {
    backgroundColor: semanticColors.bgPanel,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    minHeight: "3rem",
    paddingBlock: spacing._2,
    paddingInline: spacing._3,
  },
  flexShrink0: {
    flexShrink: 0,
  },
  marginTop1: {
    marginTop: spacing._1,
  },
  desktopSidebarToggle: {
    display: {
      default: "inline-flex",
      [NARROW_SIDEBAR]: "none",
    },
  },
  mobileSidebarToggle: {
    display: {
      default: "none",
      [NARROW_SIDEBAR]: "inline-flex",
    },
  },
  breadcrumbWrap: {
    minWidth: 0,
    overflowX: "hidden",
    overflowY: "hidden",
  },
  breadcrumbTruncate: {
    maxWidth: "15rem",
    overflowX: "hidden",
    overflowY: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
  hideCompact: {
    display: {
      default: "inline-flex",
      [COMPACT_HEADER]: "none",
    },
  },
  avatarStack: {
    display: {
      default: "flex",
      [COMPACT_HEADER]: "none",
    },
    paddingInlineEnd: spacing._1,
  },
  avatarOverlap: {
    borderColor: semanticColors.bgPanel,
    borderStyle: "solid",
    borderWidth: "2px",
    marginInlineStart: "-6px",
  },
  avatarFirst: {
    borderColor: semanticColors.bgPanel,
    borderStyle: "solid",
    borderWidth: "2px",
  },
  workspace: {
    flexGrow: 1,
    minHeight: 0,
    minWidth: 0,
    overflowX: "hidden",
    overflowY: "hidden",
  },
  sidebarPanel: {
    display: {
      default: "flex",
      [NARROW_SIDEBAR]: "none",
    },
    flexDirection: "column",
    minHeight: 0,
    minWidth: 0,
  },
  sidebarHandle: {
    display: {
      default: "grid",
      [NARROW_SIDEBAR]: "none",
    },
  },
  mainPanel: {
    display: "flex",
    flexDirection: "column",
    minHeight: 0,
    minWidth: 0,
  },
  sidebar: {
    backgroundColor: semanticColors.bgMuted,
    flexGrow: 1,
    height: "100%",
    minHeight: 0,
    overflowX: "hidden",
    overflowY: "hidden",
  },
  sidebarTabs: {
    display: "flex",
    flexDirection: "column",
    flexGrow: 1,
    minHeight: 0,
  },
  sidebarTabsList: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingInline: spacing._3,
    width: "100%",
  },
  sidebarTabPanel: {
    display: "flex",
    flexDirection: "column",
    flexGrow: 1,
    gap: spacing._3,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
  },
  treeIconMuted: {
    color: semanticColors.fgMuted,
    flexShrink: 0,
  },
  treeTextTruncate: {
    overflowX: "hidden",
    overflowY: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
  outlineRow: {
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    borderColor: "transparent",
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._1,
    paddingInline: spacing._1_5,
    transitionDuration: durations.fast,
    transitionProperty: "background-color, border-color",
  },
  outlineRowSelected: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.borderEmphasized,
    boxShadow: semanticShadows.xs,
  },
  outlineSelectBtn: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    flexGrow: 1,
    fontFamily: "inherit",
    fontSize: fontSizes.xs,
    gap: spacing._1_5,
    minWidth: 0,
    paddingBlock: spacing._0_5,
    paddingInline: 0,
    textAlign: "start",
  },
  insertGrid: {
    gap: spacing._1_5,
  },
  insertBtn: {
    justifyContent: "flex-start",
  },
  inspectorCard: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
  },
  formattingBar: {
    backgroundColor: semanticColors.bgPanel,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._1_5,
    paddingInline: spacing._4,
  },
  toolbarRow: {
    flexWrap: "wrap",
    width: "auto",
  },
  canvasScroll: {
    backgroundColor: semanticColors.bg,
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._8,
    paddingInline: {
      default: spacing._6,
      [COMPACT_HEADER]: spacing._3,
    },
  },
  pageSheet: {
    marginInline: "auto",
    transitionDuration: durations.moderate,
    transitionProperty: "max-width",
    width: "100%",
  },
  pageWidthStandard: {
    maxWidth: "46rem",
  },
  pageWidthWide: {
    maxWidth: "60rem",
  },
  pageWidthCompact: {
    maxWidth: "28rem",
  },
  statusBtn: {
    appearance: "none",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    cursor: "pointer",
    paddingBlock: 0,
    paddingInline: 0,
  },
  titleInput: {
    backgroundColor: "transparent",
    borderColor: "transparent",
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    fontFamily: fonts.heading,
    fontSize: fontSizes._3xl,
    fontWeight: fontWeights.semibold,
    height: "auto",
    letterSpacing: "-0.02em",
    lineHeight: lineHeights.heading_3xl,
    minHeight: "auto",
    paddingBlock: spacing._1,
    paddingInline: spacing._1_5,
    resize: "none",
  },
  subtitleInput: {
    backgroundColor: "transparent",
    borderColor: "transparent",
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fgMuted,
    fontSize: fontSizes.md,
    lineHeight: lineHeights.md,
    paddingBlock: spacing._1,
    paddingInline: spacing._1_5,
    resize: "none",
  },
  blockCard: {
    backgroundColor: "transparent",
    borderColor: {
      default: "transparent",
      ":hover": semanticColors.borderSubtle,
    },
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    position: "relative",
    transitionDuration: durations.fast,
    transitionProperty: "background-color, border-color, box-shadow",
  },
  blockCardSelected: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.accentBorder,
    boxShadow: semanticShadows.xs,
  },
  blockHeadingDisplay: {
    cursor: "text",
    marginBlock: 0,
  },
  blockParagraphDisplay: {
    cursor: "text",
    lineHeight: lineHeights.lg,
    whiteSpace: "pre-wrap",
  },
  textItalic: {
    fontStyle: "italic",
  },
  textMono: {
    fontFamily: fonts.mono,
    fontSize: fontSizes.sm,
  },
  alignLeft: {
    textAlign: "left",
  },
  alignCenter: {
    textAlign: "center",
  },
  alignRight: {
    textAlign: "right",
  },
  checklistItemChecked: {
    color: semanticColors.fgSubtle,
    textDecoration: "line-through",
  },
  codeEditStack: {
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
  },
  codeMetaInputs: {
    gridTemplateColumns: "1fr 8.5rem",
  },
  codeTextarea: {
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.md,
  },
  quickAddBar: {
    borderTopColor: semanticColors.borderMuted,
    borderTopStyle: "dashed",
    borderTopWidth: "1px",
    marginTop: spacing._2,
    paddingTop: spacing._4,
  },
  quickAddLabel: {
    marginInlineEnd: spacing._1,
  },
  popoverContentWide: {
    width: "21rem",
  },
  commentList: {
    maxHeight: "15rem",
    overflowY: "auto",
  },
  commentItem: {
    backgroundColor: semanticColors.bgMuted,
    borderRadius: semanticRadii.control,
    paddingBlock: spacing._2_5,
    paddingInline: spacing._2_5,
  },
  commentBody: {
    lineHeight: lineHeights.sm,
  },
  dialogSidebarWrap: {
    height: "65dvh",
    minHeight: "22rem",
    overflowX: "hidden",
    overflowY: "hidden",
  },
  dialogHeaderBar: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  dialogCloseReset: {
    position: "static",
  },
});

/* -------------------------------------------------------------------------- */
/* Component                                                                  */
/* -------------------------------------------------------------------------- */

export interface PageEditorProps extends StyleOverrideProps {
  /** Initial document ID to display. Defaults to `"rfc-color-motion"`. */
  defaultPageId?: string;
  /** Called when the user activates the Publish button. */
  onPublish?: (page: EditorPageDocument) => void;
}

/**
 * PageEditor — collaborative Notion/Linear-style document editor with a
 * resizable workspace sidebar (Pages tree + live Outline & Block settings),
 * formatting toolbar, width switcher, inline-editable structured blocks
 * (headings, paragraphs, callouts, checklists, code snippets), comments and
 * share popovers, and toast notifications.
 */
export function PageEditor({
  defaultPageId = "rfc-color-motion",
  onPublish,
  palette,
  style,
}: PageEditorProps) {
  const queue = useMemo(() => Toast.createToaster(), []);
  const idCounterRef = useRef(200);
  const nextId = useCallback((prefix: string) => {
    idCounterRef.current += 1;
    return `${prefix}-${idCounterRef.current}`;
  }, []);

  const [pages, setPages] = useState<EditorPageDocument[]>(INITIAL_PAGES);
  const [activePageId, setActivePageId] = useState<string>(defaultPageId);
  const [selectedBlockId, setSelectedBlockId] = useState<string | null>(null);
  const [editingCodeId, setEditingCodeId] = useState<string | null>(null);

  const [showSidebar, setShowSidebar] = useState(true);
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  const [sidebarTab, setSidebarTab] = useState<SidebarTab>("pages");
  const [expandedFolders, setExpandedFolders] = useState<string[]>([
    "design-systems",
    "release-planning",
  ]);
  const [pageFilter, setPageFilter] = useState("");
  const [pageWidth, setPageWidth] = useState<PageWidth>("standard");
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  const [newChecklistDraft, setNewChecklistDraft] = useState("");
  const [commentDraft, setCommentDraft] = useState("");
  const [shareAccess, setShareAccess] = useState<AccessLevel>("workspace-edit");
  const [inviteEmail, setInviteEmail] = useState("");

  const activePage = useMemo(
    () => pages.find((p) => p.id === activePageId) ?? pages[0],
    [pages, activePageId],
  );

  const selectedBlock = useMemo(
    () => activePage?.blocks.find((b) => b.id === selectedBlockId) ?? null,
    [activePage, selectedBlockId],
  );

  const updateActivePage = useCallback(
    (updater: (page: EditorPageDocument) => EditorPageDocument) => {
      setPages((prev) =>
        prev.map((page) => (page.id === activePage.id ? updater(page) : page)),
      );
      setHasUnsavedChanges(true);
    },
    [activePage.id],
  );

  const updateBlock = useCallback(
    (blockId: string, patch: Partial<EditorBlock>) => {
      updateActivePage((page) => ({
        ...page,
        updatedAt: "Edited just now",
        blocks: page.blocks.map((b) => (b.id === blockId ? { ...b, ...patch } : b)),
      }));
    },
    [updateActivePage],
  );

  const addBlock = useCallback(
    (kind: BlockKind, afterBlockId?: string) => {
      const id = nextId("blk");
      const created = createDefaultBlock(kind, id);
      updateActivePage((page) => {
        if (!afterBlockId) {
          return { ...page, updatedAt: "Edited just now", blocks: [...page.blocks, created] };
        }
        const idx = page.blocks.findIndex((b) => b.id === afterBlockId);
        if (idx === -1) {
          return { ...page, updatedAt: "Edited just now", blocks: [...page.blocks, created] };
        }
        const nextBlocks = [...page.blocks];
        nextBlocks.splice(idx + 1, 0, created);
        return { ...page, updatedAt: "Edited just now", blocks: nextBlocks };
      });
      setSelectedBlockId(id);
      if (kind === "code") setEditingCodeId(id);
      queue.info(`Added ${BLOCK_KIND_LABELS[kind].toLowerCase()} block`);
    },
    [nextId, queue, updateActivePage],
  );

  const moveBlock = useCallback(
    (blockId: string, direction: -1 | 1) => {
      updateActivePage((page) => {
        const idx = page.blocks.findIndex((b) => b.id === blockId);
        const target = idx + direction;
        if (idx < 0 || target < 0 || target >= page.blocks.length) return page;
        const nextBlocks = [...page.blocks];
        [nextBlocks[idx], nextBlocks[target]] = [nextBlocks[target], nextBlocks[idx]];
        return { ...page, updatedAt: "Edited just now", blocks: nextBlocks };
      });
    },
    [updateActivePage],
  );

  const duplicateBlock = useCallback(
    (block: EditorBlock) => {
      const id = nextId("blk");
      const clone: EditorBlock = {
        ...block,
        id,
        items: block.items?.map((item, idx) => ({ ...item, id: `${id}-i${idx}` })),
      };
      updateActivePage((page) => {
        const idx = page.blocks.findIndex((b) => b.id === block.id);
        const nextBlocks = [...page.blocks];
        nextBlocks.splice(idx + 1, 0, clone);
        return { ...page, updatedAt: "Edited just now", blocks: nextBlocks };
      });
      setSelectedBlockId(id);
      queue.info("Block duplicated");
    },
    [nextId, queue, updateActivePage],
  );

  const deleteBlock = useCallback(
    (blockId: string) => {
      updateActivePage((page) => ({
        ...page,
        updatedAt: "Edited just now",
        blocks: page.blocks.filter((b) => b.id !== blockId),
      }));
      setSelectedBlockId((curr) => (curr === blockId ? null : curr));
      setEditingCodeId((curr) => (curr === blockId ? null : curr));
    },
    [updateActivePage],
  );

  const convertBlockKind = useCallback(
    (blockId: string, nextKind: BlockKind) => {
      updateActivePage((page) => ({
        ...page,
        updatedAt: "Edited just now",
        blocks: page.blocks.map((block) => {
          if (block.id !== blockId || block.kind === nextKind) return block;
          const fallback = createDefaultBlock(nextKind, block.id);
          const carriedText =
            block.text ??
            block.items?.map((i) => i.label).join("\n") ??
            fallback.text;
          if (nextKind === "checklist") {
            const lines = (carriedText ?? "")
              .split("\n")
              .map((l) => l.trim())
              .filter(Boolean);
            return {
              ...fallback,
              items:
                lines.length > 0
                  ? lines.map((label, i) => ({ id: `${block.id}-c${i}`, label, checked: false }))
                  : fallback.items,
            };
          }
          return {
            ...fallback,
            text: carriedText || fallback.text,
            align: block.align ?? fallback.align,
          };
        }),
      }));
    },
    [updateActivePage],
  );

  const toggleChecklistItem = useCallback(
    (blockId: string, itemId: string, checked: boolean) => {
      updateActivePage((page) => ({
        ...page,
        updatedAt: "Edited just now",
        blocks: page.blocks.map((b) => {
          if (b.id !== blockId) return b;
          return {
            ...b,
            items: (b.items ?? []).map((item) =>
              item.id === itemId ? { ...item, checked } : item,
            ),
          };
        }),
      }));
    },
    [updateActivePage],
  );

  const addChecklistItem = useCallback(
    (blockId: string) => {
      const label = newChecklistDraft.trim();
      if (!label) return;
      const itemId = nextId("chk");
      updateActivePage((page) => ({
        ...page,
        updatedAt: "Edited just now",
        blocks: page.blocks.map((b) =>
          b.id === blockId
            ? { ...b, items: [...(b.items ?? []), { id: itemId, label, checked: false }] }
            : b,
        ),
      }));
      setNewChecklistDraft("");
    },
    [newChecklistDraft, nextId, updateActivePage],
  );

  const removeChecklistItem = useCallback(
    (blockId: string, itemId: string) => {
      updateActivePage((page) => ({
        ...page,
        updatedAt: "Edited just now",
        blocks: page.blocks.map((b) =>
          b.id === blockId
            ? { ...b, items: (b.items ?? []).filter((item) => item.id !== itemId) }
            : b,
        ),
      }));
    },
    [updateActivePage],
  );

  const handleSelectPage = useCallback((pageId: string) => {
    setActivePageId(pageId);
    setSelectedBlockId(null);
    setEditingCodeId(null);
    setMobileNavOpen(false);
  }, []);

  const handleCreatePage = useCallback(() => {
    const id = nextId("page");
    const docNum = pages.length + 20;
    const newPage: EditorPageDocument = {
      id,
      folderId: "design-systems",
      folderName: "Design Systems",
      docCode: `RFC-0${docNum}`,
      title: "Untitled Design Proposal",
      subtitle: "Summarize the proposal goals, constraints, and open design questions.",
      status: "Draft",
      updatedAt: "Created just now",
      blocks: [
        createDefaultBlock("heading", nextId("blk")),
        createDefaultBlock("paragraph", nextId("blk")),
      ],
      comments: [],
    };
    setPages((prev) => [...prev, newPage]);
    setActivePageId(id);
    setSelectedBlockId(null);
    setHasUnsavedChanges(true);
    setMobileNavOpen(false);
    queue.success("Created new draft page", { description: `${newPage.docCode} added to Design Systems.` });
  }, [nextId, pages.length, queue]);

  const handleCycleStatus = useCallback(() => {
    const idx = STATUS_CYCLE.indexOf(activePage.status);
    const nextStatus = STATUS_CYCLE[(idx + 1) % STATUS_CYCLE.length];
    updateActivePage((page) => ({ ...page, status: nextStatus, updatedAt: "Edited just now" }));
    queue.info(`Status updated to ${nextStatus}`);
  }, [activePage.status, queue, updateActivePage]);

  const handlePublish = useCallback(() => {
    setHasUnsavedChanges(false);
    onPublish?.(activePage);
    queue.success(`Published "${activePage.title}"`, {
      description: `${activePage.docCode} · Shared with ${COLLABORATORS.length} reviewers.`,
    });
  }, [activePage, onPublish, queue]);

  const handleCopyCode = useCallback(
    (code: string, filename?: string) => {
      if (typeof navigator !== "undefined" && navigator.clipboard) {
        void navigator.clipboard.writeText(code).catch(() => {});
      }
      queue.success("Copied snippet to clipboard", {
        description: filename ?? "Code block copied.",
      });
    },
    [queue],
  );

  const handleAddComment = useCallback(() => {
    const body = commentDraft.trim();
    if (!body) return;
    const newComment: EditorComment = {
      id: nextId("cmt"),
      author: "Clara Lindholm",
      initials: "CL",
      paletteKey: "purple",
      timestamp: "Just now",
      body,
    };
    updateActivePage((page) => ({
      ...page,
      comments: [newComment, ...page.comments],
    }));
    setCommentDraft("");
    queue.success("Comment posted");
  }, [commentDraft, nextId, queue, updateActivePage]);

  const handleResolveComment = useCallback(
    (commentId: string) => {
      updateActivePage((page) => ({
        ...page,
        comments: page.comments.map((c) =>
          c.id === commentId ? { ...c, resolved: !c.resolved } : c,
        ),
      }));
    },
    [updateActivePage],
  );

  const handleSendInvite = useCallback(() => {
    const email = inviteEmail.trim();
    if (!email) return;
    setInviteEmail("");
    queue.success("Invitation sent", { description: `${email} added to ${activePage.docCode}.` });
  }, [activePage.docCode, inviteEmail, queue]);

  const handleCopyShareLink = useCallback(() => {
    const url = `https://workspace.stylexblocks.dev/docs/${activePage.id}`;
    if (typeof navigator !== "undefined" && navigator.clipboard) {
      void navigator.clipboard.writeText(url).catch(() => {});
    }
    queue.success("Share link copied", { description: url });
  }, [activePage.id, queue]);

  const handleRestoreSampleBlocks = useCallback(() => {
    const original = INITIAL_PAGES.find((p) => p.id === activePage.id) ?? INITIAL_PAGES[0];
    updateActivePage((page) => ({
      ...page,
      updatedAt: "Restored just now",
      blocks: original.blocks,
    }));
    queue.info("Restored sample document blocks");
  }, [activePage.id, queue, updateActivePage]);

  const activeFormatValues = useMemo(() => {
    if (!selectedBlock) return [];
    const values: string[] = [];
    if (selectedBlock.bold) values.push("bold");
    if (selectedBlock.italic) values.push("italic");
    if (selectedBlock.mono) values.push("mono");
    return values;
  }, [selectedBlock]);

  const activeAlignValue = useMemo(
    () => [selectedBlock?.align ?? "left"],
    [selectedBlock?.align],
  );

  const handleFormatChange = useCallback(
    (next: string[]) => {
      if (!selectedBlock) {
        queue.info("Select a heading or paragraph block to apply formatting");
        return;
      }
      updateBlock(selectedBlock.id, {
        bold: next.includes("bold"),
        italic: next.includes("italic"),
        mono: next.includes("mono"),
      });
    },
    [queue, selectedBlock, updateBlock],
  );

  const handleAlignChange = useCallback(
    (next: string[]) => {
      const align = (next[0] as TextAlign | undefined) ?? "left";
      if (!selectedBlock) {
        queue.info("Select a block to adjust alignment");
        return;
      }
      updateBlock(selectedBlock.id, { align });
    },
    [queue, selectedBlock, updateBlock],
  );

  const openCommentsCount = useMemo(
    () => activePage.comments.filter((c) => !c.resolved).length,
    [activePage.comments],
  );

  const wordCount = useMemo(() => countDocumentWords(activePage), [activePage]);
  const readMinutes = Math.max(1, Math.ceil(wordCount / 200));

  const filteredPages = useMemo(() => {
    const q = pageFilter.trim().toLowerCase();
    if (!q) return pages;
    return pages.filter(
      (p) =>
        p.title.toLowerCase().includes(q) ||
        p.docCode.toLowerCase().includes(q) ||
        p.folderName.toLowerCase().includes(q),
    );
  }, [pageFilter, pages]);

  /* ------------------------------ Sidebar Content ------------------------- */

  const sidebarContent = (
    <Tabs.Root
      value={sidebarTab}
      onValueChange={setSidebarTab}
      variant="line"
      size="sm"
      palette={accentPalette}
      style={styles.sidebarTabs}
    >
      <Tabs.List aria-label="Editor navigation" style={styles.sidebarTabsList}>
        <Tabs.Tab value="pages">Pages</Tabs.Tab>
        <Tabs.Tab value="outline">
          Outline
          <Badge variant="subtle" size="xs" palette={grayPalette}>
            {activePage.blocks.length}
          </Badge>
        </Tabs.Tab>
      </Tabs.List>

      <Tabs.Panel value="pages" style={styles.sidebarTabPanel}>
        <Input
          size="xs"
          variant="subtle"
          aria-label="Filter pages"
          placeholder="Filter pages..."
          value={pageFilter}
          onValueChange={setPageFilter}
        />

        <HStack justify="between" gap="2">
          <Text render={<h2 />} variant="overline" tone="subtle">
            Workspace
          </Text>
          <Button
            variant="ghost"
            size="2xs"
            onClick={handleCreatePage}
            aria-label="New page"
          >
            <PlusIcon />
            New
          </Button>
        </HStack>

        <TreeView.Root
          size="xs"
          variant="subtle"
          palette={accentPalette}
          expandedValue={expandedFolders}
          onExpandedChange={(details) => setExpandedFolders(details.expandedValue)}
        >
          <TreeView.Tree aria-label="Workspace pages">
            {WORKSPACE_FOLDERS.map((folder) => {
              const folderPages = filteredPages.filter((p) => p.folderId === folder.id);
              if (pageFilter.trim() && folderPages.length === 0) return null;
              return (
                <TreeView.Branch key={folder.id} value={folder.id}>
                  <TreeView.BranchControl>
                    <TreeView.BranchIndicator>
                      <ChevronRightIcon />
                    </TreeView.BranchIndicator>
                    <Center render={<span />} display="inline" style={styles.treeIconMuted}>
                      <FolderIcon />
                    </Center>
                    <TreeView.BranchText style={styles.treeTextTruncate}>
                      {folder.name}
                    </TreeView.BranchText>
                  </TreeView.BranchControl>
                  <TreeView.BranchContent>
                    <TreeView.BranchIndentGuide />
                    {folderPages.map((page) => (
                      <TreeView.Item
                        key={page.id}
                        value={page.id}
                        data-selected={page.id === activePage.id ? "true" : undefined}
                        onClick={() => handleSelectPage(page.id)}
                      >
                        <Center render={<span />} display="inline" style={styles.treeIconMuted}>
                          <DocumentIcon />
                        </Center>
                        <TreeView.ItemText style={styles.treeTextTruncate}>
                          {page.title}
                        </TreeView.ItemText>
                      </TreeView.Item>
                    ))}
                  </TreeView.BranchContent>
                </TreeView.Branch>
              );
            })}
          </TreeView.Tree>
        </TreeView.Root>
      </Tabs.Panel>

      <Tabs.Panel value="outline" style={styles.sidebarTabPanel}>
        <HStack justify="between" gap="2">
          <Text render={<h2 />} variant="overline" tone="subtle">
            Blocks
          </Text>
          <Text render={<span />} size="xs" tone="subtle">
            {activePage.blocks.length} total
          </Text>
        </HStack>

        <VStack gap="1">
          {activePage.blocks.map((block, idx) => {
            const isSelected = block.id === selectedBlockId;
            return (
              <HStack
                key={block.id}
                gap="1.5"
                style={[styles.outlineRow, isSelected && styles.outlineRowSelected]}
              >
                <button
                  type="button"
                  {...stylex.props(styles.outlineSelectBtn)}
                  onClick={() => {
                    setSelectedBlockId(block.id);
                    setMobileNavOpen(false);
                  }}
                >
                  <Center render={<span />} display="inline" style={styles.treeIconMuted}>
                    <BlockKindIcon kind={block.kind} />
                  </Center>
                  <Text render={<span />} size="xs" truncate="true">
                    {getBlockPreviewLabel(block)}
                  </Text>
                </button>
                <HStack gap="0.5" style={styles.flexShrink0}>
                  <IconButton
                    variant="ghost"
                    size="2xs"
                    disabled={idx === 0}
                    aria-label="Move block up"
                    onClick={() => moveBlock(block.id, -1)}
                  >
                    <ArrowUpIcon />
                  </IconButton>
                  <IconButton
                    variant="ghost"
                    size="2xs"
                    disabled={idx === activePage.blocks.length - 1}
                    aria-label="Move block down"
                    onClick={() => moveBlock(block.id, 1)}
                  >
                    <ArrowDownIcon />
                  </IconButton>
                  <IconButton
                    variant="ghost"
                    size="2xs"
                    palette={redPalette}
                    aria-label="Delete block"
                    onClick={() => deleteBlock(block.id)}
                  >
                    <TrashIcon />
                  </IconButton>
                </HStack>
              </HStack>
            );
          })}
        </VStack>

        <Separator decorative />

        <HStack justify="between" gap="2">
          <Text render={<h2 />} variant="overline" tone="subtle">
            Insert block
          </Text>
        </HStack>

        <Grid columns="2" style={styles.insertGrid}>
          {(Object.keys(BLOCK_KIND_LABELS) as BlockKind[]).map((kind) => (
            <Button
              key={kind}
              variant="surface"
              size="xs"
              style={styles.insertBtn}
              onClick={() => addBlock(kind)}
            >
              <BlockKindIcon kind={kind} />
              {BLOCK_KIND_LABELS[kind]}
            </Button>
          ))}
        </Grid>

        {selectedBlock ? (
          <>
            <Separator decorative />
            <VStack gap="2.5" style={styles.inspectorCard}>
              <HStack justify="between" gap="2">
                <Text render={<h2 />} variant="overline" tone="subtle">
                  Block settings
                </Text>
                <Badge variant="subtle" size="xs" palette={accentPalette}>
                  {BLOCK_KIND_LABELS[selectedBlock.kind]}
                </Badge>
              </HStack>

              {selectedBlock.kind === "heading" ? (
                <VStack gap="1">
                  <Text render={<span />} size="xs" tone="muted" weight="medium">
                    Heading level
                  </Text>
                  <SegmentGroup.Root
                    size="xs"
                    value={String(selectedBlock.level ?? 2)}
                    onValueChange={(v) =>
                      updateBlock(selectedBlock.id, { level: v === "3" ? 3 : 2 })
                    }
                  >
                    <SegmentGroup.Item value="2">H2</SegmentGroup.Item>
                    <SegmentGroup.Item value="3">H3</SegmentGroup.Item>
                  </SegmentGroup.Root>
                </VStack>
              ) : null}

              {selectedBlock.kind === "callout" ? (
                <VStack gap="1">
                  <Text render={<span />} size="xs" tone="muted" weight="medium">
                    Callout tone
                  </Text>
                  <SegmentGroup.Root
                    size="xs"
                    value={selectedBlock.calloutTone ?? "info"}
                    onValueChange={(v) =>
                      updateBlock(selectedBlock.id, { calloutTone: v as CalloutTone })
                    }
                  >
                    <SegmentGroup.Item value="info">Info</SegmentGroup.Item>
                    <SegmentGroup.Item value="warning">Warn</SegmentGroup.Item>
                    <SegmentGroup.Item value="success">Pass</SegmentGroup.Item>
                  </SegmentGroup.Root>
                </VStack>
              ) : null}

              {selectedBlock.kind === "code" ? (
                <VStack gap="1">
                  <Text render={<span />} size="xs" tone="muted" weight="medium">
                    Language
                  </Text>
                  <Select.Root
                    size="xs"
                    items={LANGUAGE_OPTIONS}
                    value={selectedBlock.codeLanguage ?? "TypeScript"}
                    onValueChange={(next) => {
                      if (typeof next === "string") {
                        updateBlock(selectedBlock.id, { codeLanguage: next });
                      }
                    }}
                  >
                    <Select.Control>
                      <Select.Trigger aria-label="Code language">
                        <Select.Value />
                        <Select.IndicatorGroup>
                          <Select.Icon />
                        </Select.IndicatorGroup>
                      </Select.Trigger>
                    </Select.Control>
                    <Select.Content>
                      {LANGUAGE_OPTIONS.map((lang) => (
                        <Select.Item key={lang} value={lang}>
                          <Select.ItemText>{lang}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>
                </VStack>
              ) : null}

              <VStack gap="1">
                <Text render={<span />} size="xs" tone="muted" weight="medium">
                  Convert block
                </Text>
                <Select.Root
                  size="xs"
                  items={BLOCK_KIND_OPTIONS}
                  value={selectedBlock.kind}
                  onValueChange={(next) => {
                    if (typeof next === "string") {
                      convertBlockKind(selectedBlock.id, next as BlockKind);
                    }
                  }}
                >
                  <Select.Control>
                    <Select.Trigger aria-label="Block type">
                      <Select.Value />
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Trigger>
                  </Select.Control>
                  <Select.Content>
                    {BLOCK_KIND_OPTIONS.map((option) => (
                      <Select.Item key={option.value} value={option.value}>
                        <Select.ItemText>{option.label}</Select.ItemText>
                        <Select.ItemIndicator />
                      </Select.Item>
                    ))}
                  </Select.Content>
                </Select.Root>
              </VStack>
            </VStack>
          </>
        ) : null}
      </Tabs.Panel>
    </Tabs.Root>
  );

  /* ------------------------------ Block Renderer -------------------------- */

  const renderBlock = (block: EditorBlock, index: number) => {
    const isSelected = block.id === selectedBlockId;
    const alignStyle =
      block.align === "center"
        ? styles.alignCenter
        : block.align === "right"
          ? styles.alignRight
          : styles.alignLeft;
    const textAlign =
      block.align === "center"
        ? "center"
        : block.align === "right"
          ? "end"
          : "start";

    return (
      <VStack
        render={<section />}
        key={block.id}
        gap="2"
        aria-label={`${BLOCK_KIND_LABELS[block.kind]} block`}
        onClick={() => setSelectedBlockId(block.id)}
        style={[styles.blockCard, isSelected && styles.blockCardSelected]}
      >
        {isSelected ? (
          <HStack justify="between" wrap="wrap" gap="1.5">
            <HStack gap="1">
              <Badge variant="subtle" size="xs" palette={accentPalette}>
                <BlockKindIcon kind={block.kind} />
                {BLOCK_KIND_LABELS[block.kind]}
              </Badge>
              {block.kind === "heading" ? (
                <SegmentGroup.Root
                  size="xs"
                  value={String(block.level ?? 2)}
                  onValueChange={(v) =>
                    updateBlock(block.id, { level: v === "3" ? 3 : 2 })
                  }
                >
                  <SegmentGroup.Item value="2">H2</SegmentGroup.Item>
                  <SegmentGroup.Item value="3">H3</SegmentGroup.Item>
                </SegmentGroup.Root>
              ) : null}
              {block.kind === "callout" ? (
                <SegmentGroup.Root
                  size="xs"
                  value={block.calloutTone ?? "info"}
                  onValueChange={(v) =>
                    updateBlock(block.id, { calloutTone: v as CalloutTone })
                  }
                >
                  <SegmentGroup.Item value="info">Info</SegmentGroup.Item>
                  <SegmentGroup.Item value="warning">Warning</SegmentGroup.Item>
                  <SegmentGroup.Item value="success">Success</SegmentGroup.Item>
                </SegmentGroup.Root>
              ) : null}
            </HStack>

            <HStack gap="1">
              <IconButton
                variant="ghost"
                size="2xs"
                disabled={index === 0}
                aria-label="Move block up"
                onClick={(e) => {
                  e.stopPropagation();
                  moveBlock(block.id, -1);
                }}
              >
                <ArrowUpIcon />
              </IconButton>
              <IconButton
                variant="ghost"
                size="2xs"
                disabled={index === activePage.blocks.length - 1}
                aria-label="Move block down"
                onClick={(e) => {
                  e.stopPropagation();
                  moveBlock(block.id, 1);
                }}
              >
                <ArrowDownIcon />
              </IconButton>
              <IconButton
                variant="ghost"
                size="2xs"
                aria-label="Duplicate block"
                onClick={(e) => {
                  e.stopPropagation();
                  duplicateBlock(block);
                }}
              >
                <CopyIcon />
              </IconButton>
              <IconButton
                variant="ghost"
                size="2xs"
                palette={redPalette}
                aria-label="Delete block"
                onClick={(e) => {
                  e.stopPropagation();
                  deleteBlock(block.id);
                }}
              >
                <TrashIcon />
              </IconButton>
            </HStack>
          </HStack>
        ) : null}

        {block.kind === "heading" ? (
          isSelected ? (
            <Input
              size="lg"
              variant="subtle"
              aria-label="Heading text"
              value={block.text ?? ""}
              onValueChange={(value) => updateBlock(block.id, { text: value })}
            />
          ) : (
            <Heading
              render={block.level === 3 ? <h3 /> : <h2 />}
              size={block.level === 3 ? "lg" : "2xl"}
              style={[
                styles.blockHeadingDisplay,
                alignStyle,
                block.italic && styles.textItalic,
                block.mono && styles.textMono,
              ]}
            >
              {block.text || "Untitled heading"}
            </Heading>
          )
        ) : null}

        {block.kind === "paragraph" ? (
          isSelected ? (
            <Textarea
              size="md"
              variant="subtle"
              rows={3}
              autoResize
              aria-label="Paragraph content"
              value={block.text ?? ""}
              onChange={(e) => updateBlock(block.id, { text: e.target.value })}
            />
          ) : (
            <Text
              size="md"
              weight={block.bold ? "semibold" : "inherit"}
              align={textAlign}
              style={[
                styles.blockParagraphDisplay,
                block.italic && styles.textItalic,
                block.mono && styles.textMono,
              ]}
            >
              {block.text || "Click to write paragraph copy…"}
            </Text>
          )
        ) : null}

        {block.kind === "callout" ? (
          <>
            <Alert.Root
              variant="subtle"
              size="md"
              status={block.calloutTone ?? "info"}
              palette={CALLOUT_PALETTE[block.calloutTone ?? "info"]}
            >
              <Alert.Indicator>
                <CalloutGlyph tone={block.calloutTone ?? "info"} />
              </Alert.Indicator>
              <Alert.Content>
                <Alert.Title>{block.calloutTitle || "Callout title"}</Alert.Title>
                <Alert.Description>
                  {block.text || "Add callout details here."}
                </Alert.Description>
              </Alert.Content>
            </Alert.Root>
            {isSelected ? (
              <VStack gap="2" style={styles.marginTop1}>
                <Input
                  size="sm"
                  variant="outline"
                  aria-label="Callout title"
                  placeholder="Callout title"
                  value={block.calloutTitle ?? ""}
                  onValueChange={(value) => updateBlock(block.id, { calloutTitle: value })}
                />
                <Textarea
                  size="sm"
                  variant="outline"
                  rows={2}
                  aria-label="Callout description"
                  placeholder="Callout description"
                  value={block.text ?? ""}
                  onChange={(e) => updateBlock(block.id, { text: e.target.value })}
                />
              </VStack>
            ) : null}
          </>
        ) : null}

        {block.kind === "checklist" ? (
          <VStack gap="2">
            <HStack justify="between" gap="2">
              <Text render={<span />} size="xs" tone="muted" weight="medium">
                Action items
              </Text>
              <Badge
                variant="subtle"
                size="xs"
                palette={
                  (block.items?.length ?? 0) > 0 &&
                  block.items?.every((i) => i.checked)
                    ? emeraldPalette
                    : grayPalette
                }
              >
                {block.items?.filter((i) => i.checked).length ?? 0}/
                {block.items?.length ?? 0} done
              </Badge>
            </HStack>

            <VStack gap="1.5">
              {(block.items ?? []).map((item) => (
                <HStack key={item.id} justify="between" gap="2">
                  <Checkbox.Root
                    size="sm"
                    palette={accentPalette}
                    onClick={(e) => e.stopPropagation()}
                  >
                    <Checkbox.Control
                      checked={item.checked}
                      onCheckedChange={(next) =>
                        toggleChecklistItem(block.id, item.id, next === true)
                      }
                    />
                    <Checkbox.Label style={item.checked ? styles.checklistItemChecked : undefined}>
                      {item.label}
                    </Checkbox.Label>
                  </Checkbox.Root>
                  {isSelected ? (
                    <IconButton
                      variant="ghost"
                      size="2xs"
                      palette={redPalette}
                      aria-label={`Remove "${item.label}"`}
                      onClick={(e) => {
                        e.stopPropagation();
                        removeChecklistItem(block.id, item.id);
                      }}
                    >
                      <CloseIcon />
                    </IconButton>
                  ) : null}
                </HStack>
              ))}
            </VStack>

            {isSelected ? (
              <HStack
                gap="2"
                style={styles.marginTop1}
                onClick={(e) => e.stopPropagation()}
              >
                <Input
                  size="xs"
                  variant="outline"
                  aria-label="Add checklist item"
                  placeholder="Add an action item..."
                  value={newChecklistDraft}
                  onValueChange={setNewChecklistDraft}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      addChecklistItem(block.id);
                    }
                  }}
                />
                <Button
                  variant="surface"
                  size="xs"
                  onClick={() => addChecklistItem(block.id)}
                >
                  Add
                </Button>
              </HStack>
            ) : null}
          </VStack>
        ) : null}

        {block.kind === "code" ? (
          <CodeBlock.Root size="sm">
            <CodeBlock.Header>
              <CodeBlock.Title>
                <CodeInlineIcon />
                <span>{block.codeFilename || "snippet.ts"}</span>
                <Badge variant="subtle" size="xs" palette={grayPalette}>
                  {block.codeLanguage || "TypeScript"}
                </Badge>
              </CodeBlock.Title>
              <CodeBlock.Control>
                <Button
                  variant="ghost"
                  size="2xs"
                  onClick={(e) => {
                    e.stopPropagation();
                    setSelectedBlockId(block.id);
                    setEditingCodeId((curr) => (curr === block.id ? null : block.id));
                  }}
                >
                  {editingCodeId === block.id ? "Done" : "Edit"}
                </Button>
                <Button
                  variant="ghost"
                  size="2xs"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleCopyCode(block.text ?? "", block.codeFilename);
                  }}
                >
                  <CopyIcon />
                  Copy
                </Button>
              </CodeBlock.Control>
            </CodeBlock.Header>

            {editingCodeId === block.id ? (
              <VStack
                gap="2"
                style={styles.codeEditStack}
                onClick={(e) => e.stopPropagation()}
              >
                <Grid gap="2" style={styles.codeMetaInputs}>
                  <Input
                    size="xs"
                    variant="outline"
                    aria-label="Code filename"
                    placeholder="filename.ts"
                    value={block.codeFilename ?? ""}
                    onValueChange={(value) => updateBlock(block.id, { codeFilename: value })}
                  />
                  <Select.Root
                    size="xs"
                    items={LANGUAGE_OPTIONS}
                    value={block.codeLanguage ?? "TypeScript"}
                    onValueChange={(next) => {
                      if (typeof next === "string") {
                        updateBlock(block.id, { codeLanguage: next });
                      }
                    }}
                  >
                    <Select.Control>
                      <Select.Trigger aria-label="Snippet language">
                        <Select.Value />
                        <Select.IndicatorGroup>
                          <Select.Icon />
                        </Select.IndicatorGroup>
                      </Select.Trigger>
                    </Select.Control>
                    <Select.Content>
                      {LANGUAGE_OPTIONS.map((lang) => (
                        <Select.Item key={lang} value={lang}>
                          <Select.ItemText>{lang}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>
                </Grid>
                <Textarea
                  size="sm"
                  variant="subtle"
                  rows={6}
                  aria-label="Code snippet source"
                  style={styles.codeTextarea}
                  value={block.text ?? ""}
                  onChange={(e) => updateBlock(block.id, { text: e.target.value })}
                />
              </VStack>
            ) : (
              <CodeBlock.Content>
                <CodeBlock.Code>
                  <CodeBlock.CodeText>{block.text ?? ""}</CodeBlock.CodeText>
                </CodeBlock.Code>
              </CodeBlock.Content>
            )}
          </CodeBlock.Root>
        ) : null}
      </VStack>
    );
  };

  /* ------------------------------ Main Render ----------------------------- */

  const pageWidthStyle =
    pageWidth === "wide"
      ? styles.pageWidthWide
      : pageWidth === "compact"
        ? styles.pageWidthCompact
        : styles.pageWidthStandard;

  return (
    <VStack gap="0" palette={palette} style={[styles.root, style]}>
      {/* Top Workspace Header */}
      <HStack render={<header />} justify="between" gap="3" style={styles.topBar}>
        <HStack gap="2">
          <IconButton
            variant="ghost"
            size="sm"
            style={styles.desktopSidebarToggle}
            aria-label={showSidebar ? "Hide pages sidebar" : "Show pages sidebar"}
            aria-pressed={showSidebar}
            onClick={() => setShowSidebar((v) => !v)}
          >
            <SidebarIcon />
          </IconButton>
          <IconButton
            variant="ghost"
            size="sm"
            style={styles.mobileSidebarToggle}
            aria-label="Open pages and outline"
            onClick={() => setMobileNavOpen(true)}
          >
            <SidebarIcon />
          </IconButton>

          <div {...stylex.props(styles.breadcrumbWrap)}>
            <Breadcrumb.Root size="sm" variant="plain" aria-label="Document location">
              <Breadcrumb.List>
                <Breadcrumb.Item style={styles.hideCompact}>
                  <Breadcrumb.Link
                    href="#workspace"
                    onClick={(e) => {
                      e.preventDefault();
                      setSidebarTab("pages");
                      setShowSidebar(true);
                    }}
                  >
                    {activePage.folderName}
                  </Breadcrumb.Link>
                </Breadcrumb.Item>
                <Breadcrumb.Separator aria-hidden="true" style={styles.hideCompact}>
                  <ChevronRightIcon />
                </Breadcrumb.Separator>
                <Breadcrumb.Item>
                  <Breadcrumb.CurrentLink aria-current="page" style={styles.breadcrumbTruncate}>
                    {activePage.title}
                  </Breadcrumb.CurrentLink>
                </Breadcrumb.Item>
              </Breadcrumb.List>
            </Breadcrumb.Root>
          </div>

          <Badge
            variant="subtle"
            size="xs"
            palette={hasUnsavedChanges ? amberPalette : grayPalette}
            style={styles.hideCompact}
          >
            {hasUnsavedChanges ? "Edited" : "Saved"}
          </Badge>
        </HStack>

        <HStack gap="2" style={styles.flexShrink0}>
          {/* Collaborator Avatars */}
          <HStack gap="0" style={styles.avatarStack} aria-label="Active collaborators">
            {COLLABORATORS.map((person, i) => (
              <Avatar.Root
                key={person.id}
                size="sm"
                variant="solid"
                palette={COLLABORATOR_PALETTES[person.paletteKey]}
                style={i === 0 ? styles.avatarFirst : styles.avatarOverlap}
                title={`${person.name} · ${person.status}`}
              >
                <Avatar.Fallback>{person.initials}</Avatar.Fallback>
              </Avatar.Root>
            ))}
          </HStack>

          {/* Comments Popover */}
          <Popover.Root size="sm">
            <Popover.Trigger
              render={
                <Button variant="ghost" size="sm" aria-label="Document comments" />
              }
            >
              <CommentIcon />
              {openCommentsCount > 0 ? (
                <Badge variant="subtle" size="xs" palette={accentPalette}>
                  {openCommentsCount}
                </Badge>
              ) : null}
            </Popover.Trigger>
            <Popover.Content align="end" style={styles.popoverContentWide}>
              <Popover.Header>
                <HStack justify="between" gap="2">
                  <Popover.Title>Review comments</Popover.Title>
                  <Badge variant="subtle" size="xs" palette={grayPalette}>
                    {openCommentsCount} open
                  </Badge>
                </HStack>
              </Popover.Header>
              <Popover.Body>
                <VStack gap="3">
                  {activePage.comments.length === 0 ? (
                    <Text render={<span />} size="xs" tone="subtle">
                      No comments on this document yet.
                    </Text>
                  ) : (
                    <VStack gap="2.5" style={styles.commentList}>
                      {activePage.comments.map((comment) => (
                        <VStack key={comment.id} gap="1.5" style={styles.commentItem}>
                          <HStack justify="between" gap="2">
                            <HStack gap="1.5">
                              <Avatar.Root
                                size="xs"
                                palette={COLLABORATOR_PALETTES[comment.paletteKey]}
                              >
                                <Avatar.Fallback>{comment.initials}</Avatar.Fallback>
                              </Avatar.Root>
                              <Text render={<span />} size="xs" weight="semibold">
                                {comment.author}
                              </Text>
                              <Text render={<span />} size="2xs" tone="subtle">
                                {comment.timestamp}
                              </Text>
                            </HStack>
                            <Button
                              variant="ghost"
                              size="2xs"
                              palette={comment.resolved ? emeraldPalette : undefined}
                              onClick={() => handleResolveComment(comment.id)}
                            >
                              {comment.resolved ? "Resolved" : "Resolve"}
                            </Button>
                          </HStack>
                          <Text
                            size="xs"
                            style={[
                              styles.commentBody,
                              comment.resolved && styles.checklistItemChecked,
                            ]}
                          >
                            {comment.body}
                          </Text>
                        </VStack>
                      ))}
                    </VStack>
                  )}

                  <Textarea
                    size="sm"
                    rows={2}
                    aria-label="Write a review comment"
                    placeholder="Leave a note for reviewers..."
                    value={commentDraft}
                    onChange={(e) => setCommentDraft(e.target.value)}
                  />
                  <Button
                    variant="solid"
                    size="sm"
                    palette={accentPalette}
                    disabled={!commentDraft.trim()}
                    onClick={handleAddComment}
                  >
                    Post comment
                  </Button>
                </VStack>
              </Popover.Body>
            </Popover.Content>
          </Popover.Root>

          {/* Share Popover */}
          <Popover.Root size="sm">
            <Popover.Trigger
              render={<Button variant="surface" size="sm" aria-label="Share document" />}
            >
              <ShareIcon />
              <span {...stylex.props(styles.hideCompact)}>Share</span>
            </Popover.Trigger>
            <Popover.Content align="end" style={styles.popoverContentWide}>
              <Popover.Header>
                <Popover.Title>Share {activePage.docCode}</Popover.Title>
              </Popover.Header>
              <Popover.Body>
                <VStack gap="3">
                  <HStack gap="2">
                    <Input
                      size="sm"
                      aria-label="Invite collaborator by email"
                      placeholder="name@studio.dev"
                      value={inviteEmail}
                      onValueChange={setInviteEmail}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") handleSendInvite();
                      }}
                    />
                    <Button
                      variant="solid"
                      size="sm"
                      palette={accentPalette}
                      disabled={!inviteEmail.trim()}
                      onClick={handleSendInvite}
                    >
                      Invite
                    </Button>
                  </HStack>

                  <Select.Root
                    size="sm"
                    items={ACCESS_OPTIONS}
                    value={shareAccess}
                    onValueChange={(next) => {
                      if (typeof next === "string") {
                        setShareAccess(next as AccessLevel);
                        queue.info("Updated document permissions");
                      }
                    }}
                  >
                    <Select.Label>General access</Select.Label>
                    <Select.Control>
                      <Select.Trigger aria-label="General access level">
                        <Select.Value />
                        <Select.IndicatorGroup>
                          <Select.Icon />
                        </Select.IndicatorGroup>
                      </Select.Trigger>
                    </Select.Control>
                    <Select.Content>
                      {ACCESS_OPTIONS.map((opt) => (
                        <Select.Item key={opt.value} value={opt.value}>
                          <Select.ItemText>{opt.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>

                  <VStack gap="2">
                    {COLLABORATORS.map((person) => (
                      <HStack key={person.id} justify="between" gap="2">
                        <HStack gap="1.5">
                          <Avatar.Root
                            size="sm"
                            palette={COLLABORATOR_PALETTES[person.paletteKey]}
                          >
                            <Avatar.Fallback>{person.initials}</Avatar.Fallback>
                          </Avatar.Root>
                          <VStack gap="0">
                            <Text render={<span />} size="xs" weight="medium">
                              {person.name}
                            </Text>
                            <Text render={<span />} size="2xs" tone="subtle">
                              {person.role}
                            </Text>
                          </VStack>
                        </HStack>
                        <Badge variant="subtle" size="xs" palette={grayPalette}>
                          {person.status}
                        </Badge>
                      </HStack>
                    ))}
                  </VStack>
                </VStack>
              </Popover.Body>
              <Popover.Footer>
                <Button variant="surface" size="sm" onClick={handleCopyShareLink}>
                  <CopyIcon />
                  Copy link
                </Button>
              </Popover.Footer>
            </Popover.Content>
          </Popover.Root>

          {/* Publish CTA */}
          <Button
            variant="solid"
            size="sm"
            palette={accentPalette}
            onClick={handlePublish}
          >
            Publish
          </Button>
        </HStack>
      </HStack>

      {/* Resizable 2-Pane Workspace */}
      <HStack align="stretch" gap="0" style={styles.workspace}>
        <Splitter.Root
          key={String(showSidebar)}
          defaultSize={showSidebar ? [25, 75] : [100]}
          minSize={18}
          style={styles.workspace}
        >
          {showSidebar ? (
            <Fragment>
              <Splitter.Panel style={styles.sidebarPanel}>
                <VStack
                  render={<aside />}
                  gap="0"
                  aria-label="Document navigation and outline"
                  style={styles.sidebar}
                >
                  {sidebarContent}
                </VStack>
              </Splitter.Panel>
              <Splitter.ResizeTrigger
                aria-label="Resize navigation sidebar"
                style={styles.sidebarHandle}
              />
            </Fragment>
          ) : null}

          <Splitter.Panel style={styles.mainPanel}>
            {/* Formatting Toolbar Strip */}
            <HStack
              justify="between"
              wrap="wrap"
              gap="2"
              style={styles.formattingBar}
            >
              <Toolbar.Root
                variant="plain"
                size="xs"
                aria-label="Document formatting"
                style={styles.toolbarRow}
              >
                <Menu.Root size="sm">
                  <Menu.Trigger
                    render={
                      <Toolbar.Button aria-label="Change block type">
                        <BlockKindIcon kind={selectedBlock?.kind ?? "paragraph"} />
                        <span>
                          {selectedBlock
                            ? BLOCK_KIND_LABELS[selectedBlock.kind]
                            : "Paragraph"}
                        </span>
                        <ChevronDownIcon />
                      </Toolbar.Button>
                    }
                  />
                  <Menu.Content align="start">
                    <Menu.Group>
                      <Menu.GroupLabel>
                        {selectedBlock ? "Turn into" : "Insert block"}
                      </Menu.GroupLabel>
                      {(Object.keys(BLOCK_KIND_LABELS) as BlockKind[]).map((kind) => (
                        <Menu.Item
                          key={kind}
                          onSelect={() => {
                            if (selectedBlock) {
                              convertBlockKind(selectedBlock.id, kind);
                            } else {
                              addBlock(kind);
                            }
                          }}
                        >
                          <BlockKindIcon kind={kind} />
                          <Menu.ItemText>{BLOCK_KIND_LABELS[kind]}</Menu.ItemText>
                        </Menu.Item>
                      ))}
                    </Menu.Group>
                  </Menu.Content>
                </Menu.Root>

                <Toolbar.Separator />

                <ToggleGroup.Root
                  multiple
                  size="xs"
                  variant="ghost"
                  palette={accentPalette}
                  value={activeFormatValues}
                  onValueChange={handleFormatChange}
                  aria-label="Inline text styles"
                >
                  <ToggleGroup.Item value="bold" aria-label="Bold">
                    <BoldIcon />
                  </ToggleGroup.Item>
                  <ToggleGroup.Item value="italic" aria-label="Italic">
                    <ItalicIcon />
                  </ToggleGroup.Item>
                  <ToggleGroup.Item value="mono" aria-label="Monospace">
                    <CodeInlineIcon />
                  </ToggleGroup.Item>
                </ToggleGroup.Root>

                <Toolbar.Separator />

                <ToggleGroup.Root
                  size="xs"
                  variant="ghost"
                  palette={accentPalette}
                  value={activeAlignValue}
                  onValueChange={handleAlignChange}
                  aria-label="Text alignment"
                >
                  <ToggleGroup.Item value="left" aria-label="Align left">
                    <AlignLeftIcon />
                  </ToggleGroup.Item>
                  <ToggleGroup.Item value="center" aria-label="Align center">
                    <AlignCenterIcon />
                  </ToggleGroup.Item>
                  <ToggleGroup.Item value="right" aria-label="Align right">
                    <AlignRightIcon />
                  </ToggleGroup.Item>
                </ToggleGroup.Root>

                <Toolbar.Separator />

                <Menu.Root size="sm">
                  <Menu.Trigger
                    render={
                      <Toolbar.Button aria-label="Insert block">
                        <PlusIcon />
                        <span>Insert</span>
                      </Toolbar.Button>
                    }
                  />
                  <Menu.Content align="start">
                    <Menu.Group>
                      <Menu.GroupLabel>Structured blocks</Menu.GroupLabel>
                      {(Object.keys(BLOCK_KIND_LABELS) as BlockKind[]).map((kind) => (
                        <Menu.Item
                          key={kind}
                          onSelect={() => addBlock(kind, selectedBlockId ?? undefined)}
                        >
                          <BlockKindIcon kind={kind} />
                          <Menu.ItemText>{BLOCK_KIND_LABELS[kind]}</Menu.ItemText>
                        </Menu.Item>
                      ))}
                    </Menu.Group>
                  </Menu.Content>
                </Menu.Root>
              </Toolbar.Root>

              <SegmentGroup.Root
                size="xs"
                value={pageWidth}
                onValueChange={(next) => setPageWidth(next as PageWidth)}
                aria-label="Page width"
                style={styles.hideCompact}
              >
                <SegmentGroup.Item value="standard">Doc</SegmentGroup.Item>
                <SegmentGroup.Item value="wide">Wide</SegmentGroup.Item>
                <SegmentGroup.Item value="compact">Narrow</SegmentGroup.Item>
              </SegmentGroup.Root>
            </HStack>

            {/* Scrollable Document Canvas */}
            <main
              aria-label="Document canvas"
              {...stylex.props(styles.canvasScroll)}
              onClick={(e) => {
                if (e.target === e.currentTarget) setSelectedBlockId(null);
              }}
            >
              <VStack
                render={<article />}
                gap="5"
                style={[styles.pageSheet, pageWidthStyle]}
              >
                {/* Document Metadata & Editable Title */}
                <VStack render={<header />} gap="3">
                  <HStack wrap="wrap" gap="2">
                    <Badge variant="outline" size="xs" palette={grayPalette}>
                      {activePage.docCode}
                    </Badge>
                    <button
                      type="button"
                      {...stylex.props(styles.statusBtn)}
                      aria-label={`Document status: ${activePage.status}. Click to change.`}
                      onClick={handleCycleStatus}
                    >
                      <Badge
                        variant="subtle"
                        size="xs"
                        palette={STATUS_PALETTE[activePage.status]}
                      >
                        {activePage.status}
                      </Badge>
                    </button>
                    <Text render={<span />} size="xs" tone="subtle">
                      {activePage.updatedAt} · {wordCount} words · {readMinutes} min read
                    </Text>
                  </HStack>

                  <Textarea
                    variant="flushed"
                    rows={1}
                    autoResize
                    aria-label="Document title"
                    style={styles.titleInput}
                    value={activePage.title}
                    onChange={(e) =>
                      updateActivePage((page) => ({
                        ...page,
                        title: e.target.value,
                        updatedAt: "Edited just now",
                      }))
                    }
                  />

                  <Textarea
                    variant="flushed"
                    rows={1}
                    autoResize
                    aria-label="Document summary"
                    style={styles.subtitleInput}
                    value={activePage.subtitle}
                    onChange={(e) =>
                      updateActivePage((page) => ({
                        ...page,
                        subtitle: e.target.value,
                        updatedAt: "Edited just now",
                      }))
                    }
                  />
                </VStack>

                <Separator decorative />

                {/* Structured Content Blocks */}
                {activePage.blocks.length > 0 ? (
                  <VStack gap="3">
                    {activePage.blocks.map((block, index) => renderBlock(block, index))}
                  </VStack>
                ) : (
                  <EmptyState.Root size="sm">
                    <EmptyState.Content>
                      <EmptyState.Indicator palette={accentPalette}>
                        <DocumentIcon />
                      </EmptyState.Indicator>
                      <EmptyState.Title>This document is empty</EmptyState.Title>
                      <EmptyState.Description>
                        Insert a heading, paragraph, callout, checklist, or code snippet to start writing.
                      </EmptyState.Description>
                      <EmptyState.Actions>
                        <Button
                          variant="solid"
                          size="sm"
                          palette={accentPalette}
                          onClick={() => addBlock("heading")}
                        >
                          Add heading
                        </Button>
                        <Button
                          variant="surface"
                          size="sm"
                          onClick={handleRestoreSampleBlocks}
                        >
                          Restore sample blocks
                        </Button>
                      </EmptyState.Actions>
                    </EmptyState.Content>
                  </EmptyState.Root>
                )}

                {/* Bottom Quick-Insert Bar */}
                <HStack wrap="wrap" gap="1.5" style={styles.quickAddBar}>
                  <Text
                    render={<span />}
                    size="xs"
                    tone="subtle"
                    style={styles.quickAddLabel}
                  >
                    Add block:
                  </Text>
                  {(Object.keys(BLOCK_KIND_LABELS) as BlockKind[]).map((kind) => (
                    <Button
                      key={kind}
                      variant="ghost"
                      size="xs"
                      onClick={() => addBlock(kind)}
                    >
                      <PlusIcon />
                      {BLOCK_KIND_LABELS[kind]}
                    </Button>
                  ))}
                </HStack>
              </VStack>
            </main>
          </Splitter.Panel>
        </Splitter.Root>
      </HStack>

      {/* Narrow-Viewport Pages & Outline Dialog */}
      <Dialog.Root
        open={mobileNavOpen}
        onOpenChange={setMobileNavOpen}
        size="md"
        placement="top"
      >
        <Dialog.Backdrop />
        <Dialog.Content style={styles.dialogSidebarWrap}>
          <HStack justify="between" gap="2" style={styles.dialogHeaderBar}>
            <Dialog.Title>Pages & Outline</Dialog.Title>
            <Dialog.Close
              style={styles.dialogCloseReset}
              render={
                <IconButton
                  variant="ghost"
                  size="xs"
                  aria-label="Close navigation"
                />
              }
            >
              <CloseIcon />
            </Dialog.Close>
          </HStack>
          {sidebarContent}
        </Dialog.Content>
      </Dialog.Root>

      <Toaster toaster={queue} />
    </VStack>
  );
}
```

Credit: Inspired by [Page Editor](https://astryx.atmeta.com/playground?template=editor) from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.)
