---
title: "IDE Workspace · UI SDK — StyleX Blocks"
description: "Multi-pane code IDE workspace with a filterable file tree, open and closable editor tabs, line-numbered syntax-highlighted code view, resizable Terminal / Problems / Output workbench, properties and history inspector, and live status bar."
url: "https://stylexblocks.com/block/ui-sdk/ide/"
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/"
---

# IDE Workspace block

Multi-pane code IDE workspace with a filterable file tree, open and closable editor tabs, line-numbered syntax-highlighted code view, resizable Terminal / Problems / Output workbench, properties and history inspector, and live status bar.

- Behavior engine: UI SDK
- Category: [App shells](https://stylexblocks.com/blocks/app-shells.md)
- Built with: [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Code Block](https://stylexblocks.com/components/ui-sdk/code-block.md), [Data List](https://stylexblocks.com/components/ui-sdk/data-list.md), [Empty State](https://stylexblocks.com/components/ui-sdk/empty-state.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), [Kbd](https://stylexblocks.com/components/ui-sdk/kbd.md), [Menu](https://stylexblocks.com/components/ui-sdk/menu.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.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), [Status](https://stylexblocks.com/components/ui-sdk/status.md), [Tabs](https://stylexblocks.com/components/ui-sdk/tabs.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.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/ide/

## 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 ide
```

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

## Usage

```tsx
import { Ide } from "#components/blocks/ui-sdk/ide.tsx";

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

## Source

`components/blocks/ui-sdk/ide.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useMemo, useState } from "react";
import { Badge } from "#components/ui/ui-sdk/badge.tsx";
import { Button } from "#components/ui/ui-sdk/button.tsx";
import { Square } from "#components/ui/ui-sdk/center.tsx";
import { CodeBlock } from "#components/ui/ui-sdk/code-block.tsx";
import { DataList } from "#components/ui/ui-sdk/data-list.tsx";
import { EmptyState } from "#components/ui/ui-sdk/empty-state.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 { Kbd } from "#components/ui/ui-sdk/kbd.tsx";
import { Menu } from "#components/ui/ui-sdk/menu.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.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 { Status } from "#components/ui/ui-sdk/status.tsx";
import { Tabs } from "#components/ui/ui-sdk/tabs.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.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 {
  accentPalette,
  amberPalette,
  bluePalette,
  emeraldPalette,
  purplePalette,
  tealPalette,
} 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 { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

const NARROW_INSPECTOR = "@container ide-workspace (max-width: 960px)";
const NARROW_EXPLORER = "@container ide-workspace (max-width: 680px)";
const COMPACT_HEADER = "@container ide-workspace (max-width: 620px)";

type FileLanguage = "typescript" | "json";
type BottomPanelTab = "terminal" | "problems" | "output";
type InspectorTab = "properties" | "history";
type DiagnosticSeverity = "warning" | "info";
type TokenKind =
  | "plain"
  | "keyword"
  | "type"
  | "string"
  | "number"
  | "comment"
  | "property"
  | "fn";

interface FileSymbol {
  name: string;
  kind: "function" | "interface" | "type" | "test" | "key";
  line: number;
}

interface WorkspaceFile {
  id: string;
  name: string;
  path: string;
  folder: "src" | "test" | null;
  language: FileLanguage;
  languageLabel: string;
  fileType: string;
  sizeLabel: string;
  importsCount: string;
  exportsCount: string;
  lastModified: string;
  defaultLine: number;
  symbols: FileSymbol[];
  content: string;
}

interface DiagnosticItem {
  id: string;
  severity: DiagnosticSeverity;
  code: string;
  message: string;
  fileId: string;
  path: string;
  line: number;
  col: number;
}

interface HistoryEntry {
  id: string;
  label: string;
  detail: string;
  time: string;
}

interface TerminalEntry {
  id: string;
  tone: "command" | "pass" | "info" | "muted" | "warn";
  text: string;
}

interface OutputEntry {
  id: string;
  time: string;
  channel: string;
  message: string;
}

const WORKSPACE_FILES: WorkspaceFile[] = [
  {
    id: "src/router.ts",
    name: "router.ts",
    path: "src/router.ts",
    folder: "src",
    language: "typescript",
    languageLabel: "TypeScript",
    fileType: "Core Router Module",
    sizeLabel: "1.6 KB",
    importsCount: "2 modules",
    exportsCount: "4 exports",
    lastModified: "4 min ago",
    defaultLine: 24,
    symbols: [
      { name: "RouteContext", kind: "interface", line: 4 },
      { name: "RouteHandler", kind: "type", line: 10 },
      { name: "RouterOptions", kind: "interface", line: 12 },
      { name: "createRouter", kind: "function", line: 18 },
    ],
    content: `import { compilePattern, matchPath, type CompiledPattern } from "./match.ts";
import { compose, type Middleware } from "./middleware.ts";

export interface RouteContext {
  request: Request;
  params: Record<string, string>;
  url: URL;
}

export type RouteHandler = (ctx: RouteContext) => Response | Promise<Response>;

export interface RouterOptions {
  basePath?: string;
  trailingSlash?: "ignore" | "strict";
  notFound?: RouteHandler;
}

interface RouteRecord {
  method: string;
  compiled: CompiledPattern;
  handler: RouteHandler;
}

export function createRouter(options: RouterOptions = {}) {
  const routes: RouteRecord[] = [];
  const middlewares: Middleware[] = [];
  const basePath = options.basePath ?? "";

  function register(method: string, pattern: string, handler: RouteHandler) {
    routes.push({
      method: method.toUpperCase(),
      compiled: compilePattern(\`\${basePath}\${pattern}\`),
      handler,
    });
  }

  async function fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    const pipeline = compose(middlewares);

    for (const record of routes) {
      if (record.method !== request.method && record.method !== "ALL") continue;
      const params = matchPath(record.compiled, url.pathname);
      if (!params) continue;
      return pipeline({ request, params, url }, record.handler);
    }

    if (options.notFound) {
      return options.notFound({ request, params: {}, url });
    }
    return new Response("Not Found", { status: 404 });
  }

  return {
    use: (mw: Middleware) => void middlewares.push(mw),
    get: (path: string, handler: RouteHandler) => register("GET", path, handler),
    post: (path: string, handler: RouteHandler) => register("POST", path, handler),
    fetch,
  };
}`,
  },
  {
    id: "src/match.ts",
    name: "match.ts",
    path: "src/match.ts",
    folder: "src",
    language: "typescript",
    languageLabel: "TypeScript",
    fileType: "Pattern Matcher",
    sizeLabel: "1.2 KB",
    importsCount: "0 modules",
    exportsCount: "3 exports",
    lastModified: "18 min ago",
    defaultLine: 26,
    symbols: [
      { name: "CompiledPattern", kind: "interface", line: 1 },
      { name: "compilePattern", kind: "function", line: 8 },
      { name: "matchPath", kind: "function", line: 24 },
      { name: "scoreRoute", kind: "function", line: 41 },
    ],
    content: `export interface CompiledPattern {
  source: string;
  segments: string[];
  params: string[];
  hasWildcard: boolean;
}

export function compilePattern(pattern: string): CompiledPattern {
  const clean = pattern.replace(/^\\/+|\\/+$/g, "");
  const segments = clean ? clean.split("/") : [];
  const params: string[] = [];
  let hasWildcard = false;

  for (const segment of segments) {
    if (segment.startsWith(":")) {
      params.push(segment.slice(1));
    } else if (segment === "*") {
      hasWildcard = true;
    }
  }

  return { source: pattern, segments, params, hasWildcard };
}

export function matchPath(
  compiled: CompiledPattern,
  pathname: string,
): Record<string, string> | null {
  const incoming = pathname.replace(/^\\/+|\\/+$/g, "").split("/").filter(Boolean);
  if (!compiled.hasWildcard && incoming.length !== compiled.segments.length) {
    return null;
  }

  const matched: Record<string, string> = {};
  for (let i = 0; i < compiled.segments.length; i += 1) {
    const token = compiled.segments[i];
    const value = incoming[i];
    if (token === "*") {
      matched["*"] = incoming.slice(i).join("/");
      return matched;
    }
    if (token?.startsWith(":")) {
      if (!value) return null;
      matched[token.slice(1)] = decodeURIComponent(value);
      continue;
    }
    if (token !== value) return null;
  }

  return matched;
}

export function scoreRoute(compiled: CompiledPattern): number {
  return compiled.segments.reduce((score, segment) => {
    if (segment === "*") return score + 1;
    if (segment.startsWith(":")) return score + 5;
    return score + 10;
  }, 0);
}`,
  },
  {
    id: "src/middleware.ts",
    name: "middleware.ts",
    path: "src/middleware.ts",
    folder: "src",
    language: "typescript",
    languageLabel: "TypeScript",
    fileType: "Middleware Pipeline",
    sizeLabel: "1.1 KB",
    importsCount: "1 module",
    exportsCount: "4 exports",
    lastModified: "32 min ago",
    defaultLine: 11,
    symbols: [
      { name: "Middleware", kind: "type", line: 3 },
      { name: "compose", kind: "function", line: 8 },
      { name: "withTiming", kind: "function", line: 23 },
      { name: "withCors", kind: "function", line: 33 },
    ],
    content: `import type { RouteContext, RouteHandler } from "./router.ts";

export type Middleware = (
  ctx: RouteContext,
  next: () => Promise<Response>,
) => Response | Promise<Response>;

export function compose(stack: Middleware[]) {
  return async (
    ctx: RouteContext,
    handler: RouteHandler,
  ): Promise<Response> => {
    let cursor = -1;

    async function dispatch(index: number): Promise<Response> {
      if (index <= cursor) {
        throw new Error("next() called multiple times in middleware");
      }
      cursor = index;
      const fn = stack[index];
      if (!fn) return handler(ctx);
      return fn(ctx, () => dispatch(index + 1));
    }

    return dispatch(0);
  };
}

export function withTiming(): Middleware {
  return async (_ctx, next) => {
    const start = performance.now();
    const res = await next();
    const elapsed = (performance.now() - start).toFixed(2);
    res.headers.set("X-Router-Time", \`\${elapsed}ms\`);
    return res;
  };
}

export function withCors(origin = "*"): Middleware {
  return async (_ctx, next) => {
    const res = await next();
    res.headers.set("Access-Control-Allow-Origin", origin);
    res.headers.set("Vary", "Origin");
    return res;
  };
}`,
  },
  {
    id: "test/router.test.ts",
    name: "router.test.ts",
    path: "test/router.test.ts",
    folder: "test",
    language: "typescript",
    languageLabel: "TypeScript",
    fileType: "Unit Test Suite",
    sizeLabel: "1.4 KB",
    importsCount: "3 modules",
    exportsCount: "0 exports",
    lastModified: "6 min ago",
    defaultLine: 10,
    symbols: [
      { name: 'describe("stylex-router")', kind: "test", line: 6 },
      { name: "matches static and param routes", kind: "test", line: 7 },
      { name: "runs middleware in declaration order", kind: "test", line: 20 },
      { name: "returns 404 for unknown paths", kind: "test", line: 37 },
    ],
    content: `import { describe, expect, test } from "bun:test";
import { createRouter } from "../src/router.ts";
import { withCors, withTiming } from "../src/middleware.ts";

describe("stylex-router", () => {
  test("matches static and param routes", async () => {
    const router = createRouter({ basePath: "/api" });
    router.get("/packages/:scope/:name", ({ params }) =>
      Response.json({ pkg: \`\${params.scope}/\${params.name}\` }),
    );

    const res = await router.fetch(
      new Request("https://stylex.dev/api/packages/@acme/router"),
    );

    expect(res.status).toBe(200);
    expect(await res.json()).toEqual({ pkg: "@acme/router" });
  });

  test("runs middleware in declaration order", async () => {
    const trace: string[] = [];
    const router = createRouter();
    router.use(withTiming());
    router.use(withCors("https://stylex.dev"));
    router.use(async (_ctx, next) => {
      trace.push("before");
      const res = await next();
      trace.push("after");
      return res;
    });
    router.get("/health", () => new Response("ok"));

    const res = await router.fetch(new Request("https://stylex.dev/health"));
    expect(res.headers.get("X-Router-Time")).toContain("ms");
    expect(trace).toEqual(["before", "after"]);
  });

  test("returns 404 for unknown paths", async () => {
    const router = createRouter();
    const res = await router.fetch(new Request("https://stylex.dev/missing"));
    expect(res.status).toBe(404);
  });
});`,
  },
  {
    id: "package.json",
    name: "package.json",
    path: "package.json",
    folder: null,
    language: "json",
    languageLabel: "JSON",
    fileType: "Package Manifest",
    sizeLabel: "0.6 KB",
    importsCount: "0 deps",
    exportsCount: "2 entrypoints",
    lastModified: "1 hr ago",
    defaultLine: 7,
    symbols: [
      { name: "name", kind: "key", line: 2 },
      { name: "exports", kind: "key", line: 7 },
      { name: "scripts", kind: "key", line: 12 },
    ],
    content: `{
  "name": "@acme/stylex-router",
  "version": "0.4.2",
  "type": "module",
  "description": "Zero-dependency typed Fetch router with composable middleware",
  "license": "MIT",
  "exports": {
    ".": "./src/router.ts",
    "./middleware": "./src/middleware.ts"
  },
  "scripts": {
    "test": "bun test",
    "typecheck": "tsc --noEmit",
    "build": "bun build ./src/router.ts --outdir ./dist --target bun"
  },
  "devDependencies": {
    "typescript": "^5.8.0"
  }
}`,
  },
  {
    id: "tsconfig.json",
    name: "tsconfig.json",
    path: "tsconfig.json",
    folder: null,
    language: "json",
    languageLabel: "JSON",
    fileType: "TypeScript Config",
    sizeLabel: "0.4 KB",
    importsCount: "0 deps",
    exportsCount: "config",
    lastModified: "2 hrs ago",
    defaultLine: 5,
    symbols: [
      { name: "compilerOptions", kind: "key", line: 2 },
      { name: "include", kind: "key", line: 13 },
    ],
    content: `{
  "compilerOptions": {
    "target": "ES2023",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "skipLibCheck": true
  },
  "include": ["src", "test"]
}`,
  },
];

const INITIAL_DIAGNOSTICS: DiagnosticItem[] = [
  {
    id: "diag-decode",
    severity: "warning",
    code: "router/safe-decode",
    message:
      "Wrap decodeURIComponent(value) in try/catch to guard against malformed percent-encoding.",
    fileId: "src/match.ts",
    path: "src/match.ts",
    line: 43,
    col: 32,
  },
  {
    id: "diag-cors",
    severity: "info",
    code: "router/cors-origin",
    message:
      'Default CORS origin "*" can be narrowed to an explicit allow-list in production.',
    fileId: "src/middleware.ts",
    path: "src/middleware.ts",
    line: 39,
    col: 28,
  },
];

const INITIAL_TERMINAL: TerminalEntry[] = [
  { id: "t-1", tone: "command", text: "$ bun test" },
  { id: "t-2", tone: "muted", text: "bun test v1.2.8 (stylex-router)" },
  { id: "t-3", tone: "info", text: "test/router.test.ts:" },
  {
    id: "t-4",
    tone: "pass",
    text: "✓ stylex-router > matches static and param routes [1.14ms]",
  },
  {
    id: "t-5",
    tone: "pass",
    text: "✓ stylex-router > runs middleware in declaration order [0.68ms]",
  },
  {
    id: "t-6",
    tone: "pass",
    text: "✓ stylex-router > returns 404 for unknown paths [0.22ms]",
  },
  {
    id: "t-7",
    tone: "muted",
    text: " 3 pass · 0 fail · 5 expect() calls · Ran 3 tests across 1 file. [14.00ms]",
  },
];

const INITIAL_OUTPUT: OutputEntry[] = [
  {
    id: "o-1",
    time: "14:02:11",
    channel: "tsserver",
    message: "Loaded project tsconfig.json (6 files indexed in 82ms).",
  },
  {
    id: "o-2",
    time: "14:02:12",
    channel: "lint",
    message: "Workspace check finished: 0 errors, 1 warning, 1 hint.",
  },
  {
    id: "o-3",
    time: "14:02:18",
    channel: "bun-test",
    message: "Test watcher ready on branch main.",
  },
];

const INITIAL_HISTORY: HistoryEntry[] = [
  {
    id: "h-1",
    label: "Opened src/router.ts",
    detail: "Ln 24 · createRouter",
    time: "2m ago",
  },
  {
    id: "h-2",
    label: "Ran bun test",
    detail: "3 passed in 14ms",
    time: "5m ago",
  },
  {
    id: "h-3",
    label: "Opened test/router.test.ts",
    detail: "Unit Test Suite",
    time: "9m ago",
  },
];

const TS_KEYWORDS = new Set([
  "import",
  "export",
  "from",
  "type",
  "interface",
  "function",
  "async",
  "await",
  "const",
  "let",
  "return",
  "for",
  "of",
  "if",
  "else",
  "continue",
  "throw",
  "new",
  "void",
  "null",
  "true",
  "false",
]);

const TS_TYPES = new Set([
  "Request",
  "Response",
  "Promise",
  "Record",
  "URL",
  "Error",
  "RouteContext",
  "RouteHandler",
  "RouterOptions",
  "RouteRecord",
  "CompiledPattern",
  "Middleware",
  "string",
  "number",
  "boolean",
]);

function tokenizeLine(
  line: string,
  language: FileLanguage,
): Array<{ kind: TokenKind; text: string }> {
  if (!line) return [{ kind: "plain", text: " " }];

  const tokens: Array<{ kind: TokenKind; text: string }> = [];
  let i = 0;

  while (i < line.length) {
    const ch = line[i]!;

    // Line comments in TS
    if (language === "typescript" && ch === "/" && line[i + 1] === "/") {
      tokens.push({ kind: "comment", text: line.slice(i) });
      break;
    }

    // String / template literals
    if (ch === '"' || ch === "'" || ch === "`") {
      const quote = ch;
      let j = i + 1;
      while (j < line.length) {
        if (line[j] === "\\" && j + 1 < line.length) {
          j += 2;
          continue;
        }
        if (line[j] === quote) {
          j += 1;
          break;
        }
        j += 1;
      }
      const raw = line.slice(i, j);
      if (language === "json") {
        const rest = line.slice(j).trimStart();
        tokens.push({
          kind: rest.startsWith(":") ? "property" : "string",
          text: raw,
        });
      } else {
        tokens.push({ kind: "string", text: raw });
      }
      i = j;
      continue;
    }

    // Numbers
    if (/[0-9]/.test(ch) && (i === 0 || !/[A-Za-z0-9_$]/.test(line[i - 1]!))) {
      let j = i;
      while (j < line.length && /[0-9._]/.test(line[j]!)) j += 1;
      tokens.push({ kind: "number", text: line.slice(i, j) });
      i = j;
      continue;
    }

    // Identifiers
    if (/[A-Za-z_$]/.test(ch)) {
      let j = i;
      while (j < line.length && /[A-Za-z0-9_$]/.test(line[j]!)) j += 1;
      const word = line.slice(i, j);
      if (language === "json") {
        const isBool = word === "true" || word === "false" || word === "null";
        tokens.push({ kind: isBool ? "keyword" : "plain", text: word });
      } else if (TS_KEYWORDS.has(word)) {
        tokens.push({ kind: "keyword", text: word });
      } else if (TS_TYPES.has(word)) {
        tokens.push({ kind: "type", text: word });
      } else if (line[j] === "(") {
        tokens.push({ kind: "fn", text: word });
      } else {
        tokens.push({ kind: "plain", text: word });
      }
      i = j;
      continue;
    }

    // Accumulate punctuation / whitespace
    let j = i + 1;
    while (
      j < line.length &&
      !/[A-Za-z0-9_$"'`/]/.test(line[j]!)
    ) {
      j += 1;
    }
    tokens.push({ kind: "plain", text: line.slice(i, j) });
    i = j;
  }

  return tokens;
}

function formatTimeStamp(): string {
  const now = new Date();
  const hh = String(now.getHours()).padStart(2, "0");
  const mm = String(now.getMinutes()).padStart(2, "0");
  const ss = String(now.getSeconds()).padStart(2, "0");
  return `${hh}:${mm}:${ss}`;
}

function FolderGlyph({ open = false }: { open?: boolean }) {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {open ? (
        <>
          <path d="M2 4.2A1.2 1.2 0 0 1 3.2 3h3l1.3 1.5h5.3A1.2 1.2 0 0 1 14 5.7v.8" />
          <path d="M2 6.5h11.3a.8.8 0 0 1 .78 1l-.9 4.5a1.2 1.2 0 0 1-1.18 1H3.2A1.2 1.2 0 0 1 2 11.8V4.2Z" />
        </>
      ) : (
        <path d="M2 4.2A1.2 1.2 0 0 1 3.2 3h3l1.3 1.5h5.3A1.2 1.2 0 0 1 14 5.7v6.1a1.2 1.2 0 0 1-1.2 1.2H3.2A1.2 1.2 0 0 1 2 11.8V4.2Z" />
      )}
    </Icon>
  );
}

function FileGlyph({ language }: { language: FileLanguage }) {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      style={language === "typescript" ? styles.tsIcon : styles.jsonIcon}
    >
      <path d="M4 2.5h5.2L12.5 5.8v7.7a1 1 0 0 1-1 1h-7.5a1 1 0 0 1-1-1v-10a1 1 0 0 1 1-1Z" />
      <path d="M9 2.5V6h3.5" />
    </Icon>
  );
}

function PlayGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="currentColor"
      aria-hidden="true"
    >
      <path d="M4.5 3.3c0-.6.66-.96 1.17-.64l7.2 4.5a.75.75 0 0 1 0 1.28l-7.2 4.5A.75.75 0 0 1 4.5 12.3V3.3Z" />
    </Icon>
  );
}

function CopyGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="5.5" y="5.5" width="8" height="8" rx="1.4" />
      <path d="M10.5 5.5V3.9a1.4 1.4 0 0 0-1.4-1.4H3.9a1.4 1.4 0 0 0-1.4 1.4v5.2a1.4 1.4 0 0 0 1.4 1.4h1.6" />
    </Icon>
  );
}

function FormatGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M2.5 4h11" />
      <path d="M5 8h8.5" />
      <path d="M5 12h6" />
      <path d="M2.5 8h.5" />
      <path d="M2.5 12h.5" />
    </Icon>
  );
}

function CloseGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="m4.5 4.5 7 7m0-7-7 7" />
    </Icon>
  );
}

function BranchGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="5" cy="4" r="1.5" />
      <circle cx="5" cy="12" r="1.5" />
      <circle cx="11.5" cy="6.5" r="1.5" />
      <path d="M5 5.5v5" />
      <path d="M11.5 8c0 2-1.5 3-4.5 3H5" />
    </Icon>
  );
}

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

function PanelBottomGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="2" y="2.5" width="12" height="11" rx="1.6" />
      <path d="M2 9.5h12" />
    </Icon>
  );
}

function PanelRightGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="2" y="2.5" width="12" height="11" rx="1.6" />
      <path d="M10 2.5v11" />
    </Icon>
  );
}

function MoreGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="currentColor"
      aria-hidden="true"
    >
      <circle cx="3.5" cy="8" r="1.15" />
      <circle cx="8" cy="8" r="1.15" />
      <circle cx="12.5" cy="8" r="1.15" />
    </Icon>
  );
}

function ClockGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="8" cy="8" r="5.5" />
      <path d="M8 5.2v3l2 1.2" />
    </Icon>
  );
}

function SearchGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="7.2" cy="7.2" r="4.4" />
      <path d="m10.6 10.6 2.9 2.9" />
    </Icon>
  );
}

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "ide-workspace",
    containerType: "inline-size",
    fontFamily: fonts.body,
    height: "100%",
    minHeight: "640px",
    overflow: "hidden",
    width: "100%",
  },
  header: {
    backgroundColor: semanticColors.bgSurface,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    minHeight: "2.75rem",
    paddingBlock: spacing._1_5,
    paddingInline: spacing._3,
  },
  brandMark: {
    backgroundColor: semanticColors.accentSubtle,
    borderColor: semanticColors.accentBorder,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.accentFg,
    height: "1.625rem",
    width: "1.625rem",
  },
  hideCompact: {
    display: {
      default: "inline-flex",
      [COMPACT_HEADER]: "none",
    },
  },
  shrink0: {
    flexShrink: 0,
  },
  flexGrow: {
    flexGrow: 1,
    minWidth: 0,
  },
  noSelect: {
    userSelect: "none",
  },
  paneToggleActive: {
    backgroundColor: semanticColors.bgMuted,
    color: semanticColors.fg,
  },
  workspace: {
    flexGrow: 1,
    minHeight: 0,
    width: "100%",
  },
  explorerPanel: {
    display: {
      default: "flex",
      [NARROW_EXPLORER]: "none",
    },
    flexDirection: "column",
    minHeight: 0,
    minWidth: 0,
  },
  explorerHandle: {
    display: {
      default: "grid",
      [NARROW_EXPLORER]: "none",
    },
  },
  centerPanel: {
    display: "flex",
    flexDirection: "column",
    minHeight: 0,
    minWidth: 0,
  },
  inspectorPanel: {
    display: {
      default: "flex",
      [NARROW_INSPECTOR]: "none",
    },
    flexDirection: "column",
    minHeight: 0,
    minWidth: 0,
  },
  inspectorHandle: {
    display: {
      default: "grid",
      [NARROW_INSPECTOR]: "none",
    },
  },
  sidebarInner: {
    backgroundColor: semanticColors.bgSurface,
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._2_5,
  },
  paneHeaderRow: {
    paddingInline: spacing._1,
  },
  searchBox: {
    position: "relative",
  },
  searchIconSlot: {
    color: semanticColors.fgSubtle,
    display: "inline-flex",
    insetInlineStart: spacing._2_5,
    pointerEvents: "none",
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineStart: spacing._7,
  },
  treeTextTruncate: {
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
  folderIconMuted: {
    color: semanticColors.fgMuted,
    display: "inline-flex",
    flexShrink: 0,
  },
  tsIcon: {
    color: semanticColors.blueFg,
  },
  jsonIcon: {
    color: semanticColors.amberFg,
  },
  treeBadgeDot: {
    backgroundColor: semanticColors.statusWarning,
    borderRadius: radii.full,
    flexShrink: 0,
    height: "6px",
    width: "6px",
  },
  treeEmpty: {
    marginBlock: spacing._2,
    paddingInline: spacing._2,
  },
  editorColumn: {
    backgroundColor: semanticColors.bg,
    display: "flex",
    flexDirection: "column",
    flexGrow: 1,
    minHeight: 0,
    minWidth: 0,
  },
  tabStrip: {
    backgroundColor: semanticColors.bgSurface,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    overflowX: "auto",
    scrollbarWidth: "none",
  },
  editorTabItem: {
    alignItems: "center",
    borderInlineEndColor: semanticColors.borderMuted,
    borderInlineEndStyle: "solid",
    borderInlineEndWidth: "1px",
    display: "inline-flex",
    flexShrink: 0,
    position: "relative",
  },
  editorTabItemActive: {
    backgroundColor: semanticColors.bg,
    boxShadow: `inset 0 -2px 0 0 ${semanticColors.accentSolid}`,
  },
  editorTabButton: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: "transparent",
    borderWidth: 0,
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    gap: spacing._1_5,
    height: "2.25rem",
    lineHeight: lineHeights.xs,
    paddingInlineEnd: spacing._1_5,
    paddingInlineStart: spacing._3,
    whiteSpace: "nowrap",
  },
  editorTabButtonActive: {
    color: semanticColors.fg,
    fontWeight: fontWeights.medium,
  },
  editorTabClose: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgMuted,
    },
    borderRadius: semanticRadii.control,
    borderWidth: 0,
    color: {
      default: semanticColors.fgSubtle,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    display: "inline-flex",
    height: "1.25rem",
    justifyContent: "center",
    marginInlineEnd: spacing._1_5,
    paddingBlock: 0,
    paddingInline: 0,
    width: "1.25rem",
  },
  modifiedDot: {
    backgroundColor: semanticColors.accentSolid,
    borderRadius: radii.full,
    display: "inline-block",
    height: "6px",
    width: "6px",
  },
  breadcrumbBar: {
    backgroundColor: semanticColors.bg,
    borderBottomColor: semanticColors.borderMuted,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    color: semanticColors.fgMuted,
    flexShrink: 0,
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    paddingBlock: spacing._1_5,
    paddingInline: spacing._3,
  },
  breadcrumbTrail: {
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
  codeBlockRoot: {
    borderRadius: 0,
    borderWidth: 0,
    display: "flex",
    flexDirection: "column",
    flexGrow: 1,
    minHeight: 0,
    width: "100%",
  },
  codeBlockContent: {
    borderRadius: 0,
    colorScheme: "inherit",
    flexGrow: 1,
    maxHeight: "none",
    minHeight: 0,
    overflowX: "auto",
    overflowY: "auto",
  },
  codeBlockPre: {
    minHeight: "100%",
    overflowX: "visible",
    overflowY: "visible",
  },
  codeBlockPreWrap: {
    whiteSpace: "pre-wrap",
    wordBreak: "break-word",
  },
  codeBlockText: {
    paddingBlock: spacing._2,
    paddingInline: 0,
  },
  codeRow: {
    alignItems: "baseline",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    cursor: "text",
    display: "flex",
    minWidth: "100%",
    paddingInlineEnd: spacing._4,
    transitionDuration: durations.fast,
    transitionProperty: "background-color",
  },
  codeRowActive: {
    backgroundColor: semanticColors.accentMuted,
    boxShadow: `inset 2px 0 0 0 ${semanticColors.accentSolid}`,
  },
  codeRowWarning: {
    backgroundColor: semanticColors.bgWarning,
  },
  lineNumber: {
    color: semanticColors.fgSubtle,
    flexShrink: 0,
    fontVariantNumeric: "tabular-nums",
    paddingInlineEnd: spacing._4,
    paddingInlineStart: spacing._3,
    textAlign: "right",
    userSelect: "none",
    width: "3.25rem",
  },
  lineNumberActive: {
    color: semanticColors.fg,
    fontWeight: fontWeights.semibold,
  },
  lineContent: {
    flexGrow: 1,
    minWidth: 0,
  },
  tokPlain: { color: semanticColors.fg },
  tokKeyword: { color: semanticColors.purpleFg },
  tokType: { color: semanticColors.tealFg },
  tokString: { color: semanticColors.emeraldFg },
  tokNumber: { color: semanticColors.amberFg },
  tokComment: { color: semanticColors.fgSubtle, fontStyle: "italic" },
  tokProperty: { color: semanticColors.blueFg },
  tokFn: { color: semanticColors.blueFg },
  bottomPanel: {
    backgroundColor: semanticColors.bgSurface,
    display: "flex",
    flexDirection: "column",
    height: "100%",
    minHeight: 0,
    overflow: "hidden",
    width: "100%",
  },
  bottomTabsRoot: {
    display: "flex",
    flexDirection: "column",
    height: "100%",
    minHeight: 0,
    width: "100%",
  },
  bottomTabHeader: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingInline: spacing._2_5,
  },
  bottomTabsList: {
    borderBottomWidth: 0,
  },
  bottomTabPanel: {
    display: "flex",
    flexDirection: "column",
    flexGrow: 1,
    minHeight: 0,
    overflow: "hidden",
    paddingBlock: 0,
    paddingInline: 0,
  },
  terminalScroll: {
    backgroundColor: semanticColors.bg,
    flexGrow: 1,
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.sm,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
  },
  terminalLine: {
    marginBlock: 0,
    whiteSpace: "pre-wrap",
    wordBreak: "break-word",
  },
  termCommand: {
    color: semanticColors.fg,
    fontWeight: fontWeights.semibold,
  },
  termPass: {
    color: semanticColors.fgSuccess,
  },
  termInfo: {
    color: semanticColors.fgInfo,
  },
  termWarn: {
    color: semanticColors.fgWarning,
  },
  termMuted: {
    color: semanticColors.fgMuted,
  },
  terminalPromptBar: {
    backgroundColor: semanticColors.bgSurface,
    borderTopColor: semanticColors.borderMuted,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._1_5,
    paddingInline: spacing._3,
  },
  terminalInput: {
    fontFamily: fonts.mono,
  },
  problemsList: {
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._1_5,
    paddingInline: spacing._2,
  },
  problemRow: {
    alignItems: "flex-start",
    appearance: "none",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgMuted,
    },
    borderRadius: semanticRadii.control,
    borderWidth: 0,
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    gap: spacing._2_5,
    justifyContent: "space-between",
    paddingBlock: spacing._2,
    paddingInline: spacing._2_5,
    textAlign: "left",
    width: "100%",
  },
  outputScroll: {
    backgroundColor: semanticColors.bg,
    flexGrow: 1,
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.sm,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
  },
  outputChannel: {
    color: semanticColors.purpleFg,
    flexShrink: 0,
  },
  inspectorInner: {
    backgroundColor: semanticColors.bgSurface,
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
  },
  segmentFull: {
    display: "flex",
    width: "100%",
  },
  segmentItemFill: {
    flexGrow: 1,
    justifyContent: "center",
  },
  inspectorHeading: {
    marginBlock: 0,
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
  metadataCompact: {
    gap: spacing._2,
  },
  metadataLabel: {
    minWidth: "5.75rem",
  },
  symbolRow: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgMuted,
    },
    borderRadius: semanticRadii.control,
    borderWidth: 0,
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    fontSize: fontSizes.xs,
    gap: spacing._2,
    justifyContent: "space-between",
    lineHeight: lineHeights.xs,
    paddingBlock: spacing._1_5,
    paddingInline: spacing._2,
    textAlign: "left",
    width: "100%",
  },
  inspectorActions: {
    marginTop: "auto",
    paddingTop: spacing._2,
  },
  actionButtonFull: {
    justifyContent: "flex-start",
    width: "100%",
  },
  historyRow: {
    borderRadius: semanticRadii.control,
    paddingBlock: spacing._1_5,
    paddingInline: spacing._1_5,
  },
  historyIcon: {
    color: semanticColors.fgSubtle,
    display: "inline-flex",
    marginTop: "2px",
  },
  statusBar: {
    backgroundColor: semanticColors.bgSurface,
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    color: semanticColors.fgMuted,
    flexShrink: 0,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    minHeight: "1.75rem",
    paddingBlock: spacing._1,
    paddingInline: spacing._3,
  },
  statusItem: {
    alignItems: "center",
    display: "inline-flex",
    gap: spacing._1,
    whiteSpace: "nowrap",
  },
  statusButton: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgMuted,
    },
    borderRadius: semanticRadii.control,
    borderWidth: 0,
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: "inherit",
    fontSize: fontSizes.xs,
    gap: spacing._1,
    lineHeight: lineHeights.xs,
    paddingBlock: "2px",
    paddingInline: spacing._1_5,
    whiteSpace: "nowrap",
  },
  statusMono: {
    fontFamily: fonts.mono,
    fontVariantNumeric: "tabular-nums",
  },
  menuContentWidth: {
    minWidth: "13rem",
  },
});

const TOKEN_STYLE_MAP: Record<TokenKind, stylex.StyleXStyles> = {
  plain: styles.tokPlain,
  keyword: styles.tokKeyword,
  type: styles.tokType,
  string: styles.tokString,
  number: styles.tokNumber,
  comment: styles.tokComment,
  property: styles.tokProperty,
  fn: styles.tokFn,
};

export interface IdeProps extends StyleOverrideProps {
  /** Workspace title displayed in the IDE header. */
  workspaceName?: string;
  /** Git branch label displayed in the header and status bar. */
  branch?: string;
  /** Initial active file path (defaults to `"src/router.ts"`). */
  initialFile?: string;
}

/**
 * Ide — multi-pane code IDE workspace with a searchable file tree, closable
 * editor tabs, line-numbered syntax-highlighted code view, resizable bottom
 * Terminal / Problems / Output panel, file properties & session history
 * inspector, and live status bar.
 */
export function Ide({
  workspaceName = "stylex-router",
  branch = "main",
  initialFile = "src/router.ts",
  palette,
  style,
}: IdeProps) {
  const queue = useMemo(() => Toast.createToaster(), []);

  const validInitial = useMemo(
    () =>
      WORKSPACE_FILES.some((f) => f.id === initialFile)
        ? initialFile
        : WORKSPACE_FILES[0]!.id,
    [initialFile],
  );

  const [openTabs, setOpenTabs] = useState<string[]>([
    validInitial,
    "src/match.ts",
    "test/router.test.ts",
  ]);
  const [activeFileId, setActiveFileId] = useState<string | null>(validInitial);
  const [expandedFolders, setExpandedFolders] = useState<string[]>([
    "src",
    "test",
  ]);
  const [fileQuery, setFileQuery] = useState("");
  const [activeLines, setActiveLines] = useState<Record<string, number>>(() =>
    Object.fromEntries(WORKSPACE_FILES.map((f) => [f.id, f.defaultLine])),
  );
  const [cursorCol, setCursorCol] = useState(1);
  const [formattedFiles, setFormattedFiles] = useState<Record<string, boolean>>(
    {},
  );
  const [wordWrap, setWordWrap] = useState(false);

  const [showExplorer, setShowExplorer] = useState(true);
  const [showBottomPanel, setShowBottomPanel] = useState(true);
  const [showInspector, setShowInspector] = useState(true);

  const [bottomTab, setBottomTab] = useState<BottomPanelTab>("terminal");
  const [inspectorTab, setInspectorTab] = useState<InspectorTab>("properties");

  const [terminalLines, setTerminalLines] =
    useState<TerminalEntry[]>(INITIAL_TERMINAL);
  const [terminalCommand, setTerminalCommand] = useState("");
  const [outputLines, setOutputLines] = useState<OutputEntry[]>(INITIAL_OUTPUT);
  const [historyItems, setHistoryItems] =
    useState<HistoryEntry[]>(INITIAL_HISTORY);
  const [testRunCount, setTestRunCount] = useState(1);
  const [lastTestDuration, setLastTestDuration] = useState("14ms");

  const filesById = useMemo(
    () => new Map(WORKSPACE_FILES.map((f) => [f.id, f])),
    [],
  );

  const activeFile = activeFileId ? filesById.get(activeFileId) ?? null : null;
  const activeLine = activeFile ? (activeLines[activeFile.id] ?? 1) : 1;

  const diagnosticFileIds = useMemo(
    () => new Set(INITIAL_DIAGNOSTICS.map((d) => d.fileId)),
    [],
  );

  const filteredFiles = useMemo(() => {
    const q = fileQuery.trim().toLowerCase();
    if (!q) return WORKSPACE_FILES;
    return WORKSPACE_FILES.filter(
      (f) =>
        f.path.toLowerCase().includes(q) || f.name.toLowerCase().includes(q),
    );
  }, [fileQuery]);

  const srcFiles = useMemo(
    () => filteredFiles.filter((f) => f.folder === "src"),
    [filteredFiles],
  );
  const testFiles = useMemo(
    () => filteredFiles.filter((f) => f.folder === "test"),
    [filteredFiles],
  );
  const rootFiles = useMemo(
    () => filteredFiles.filter((f) => f.folder === null),
    [filteredFiles],
  );

  const pushHistory = useCallback((label: string, detail: string) => {
    setHistoryItems((prev) => [
      {
        id: `h-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
        label,
        detail,
        time: "just now",
      },
      ...prev.slice(0, 11),
    ]);
  }, []);

  const pushOutput = useCallback((channel: string, message: string) => {
    setOutputLines((prev) => [
      ...prev,
      {
        id: `o-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
        time: formatTimeStamp(),
        channel,
        message,
      },
    ]);
  }, []);

  const openFile = useCallback(
    (fileId: string, line?: number, col = 1) => {
      const target = filesById.get(fileId);
      if (!target) return;

      setOpenTabs((prev) => (prev.includes(fileId) ? prev : [...prev, fileId]));
      setActiveFileId(fileId);
      if (line !== undefined) {
        setActiveLines((prev) => ({ ...prev, [fileId]: line }));
      }
      setCursorCol(col);
      pushHistory(
        `Opened ${target.path}`,
        line !== undefined ? `Ln ${line}, Col ${col}` : target.fileType,
      );
    },
    [filesById, pushHistory],
  );

  const closeTab = useCallback(
    (fileId: string) => {
      setOpenTabs((prev) => {
        const index = prev.indexOf(fileId);
        if (index === -1) return prev;
        const nextTabs = prev.filter((id) => id !== fileId);
        if (activeFileId === fileId) {
          const fallback = nextTabs[Math.min(index, nextTabs.length - 1)] ?? null;
          setActiveFileId(fallback);
        }
        return nextTabs;
      });
    },
    [activeFileId],
  );

  const handleCopyCode = useCallback(() => {
    if (!activeFile) return;
    if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
      void navigator.clipboard.writeText(activeFile.content).catch(() => {});
    }
    pushHistory(`Copied ${activeFile.name}`, `${activeFile.sizeLabel} to clipboard`);
    queue.info(`Copied ${activeFile.path}`, {
      description: `${activeFile.content.split("\n").length} lines copied to clipboard.`,
    });
  }, [activeFile, pushHistory, queue]);

  const handleFormatFile = useCallback(() => {
    if (!activeFile) return;
    setFormattedFiles((prev) => ({ ...prev, [activeFile.id]: true }));
    pushOutput("formatter", `Formatted ${activeFile.path} (2 spaces, semicolons).`);
    pushHistory(`Formatted ${activeFile.name}`, "0 style issues");
    queue.success(`Formatted ${activeFile.path}`, {
      description: "Applied workspace TypeScript formatting rules.",
    });
  }, [activeFile, pushHistory, pushOutput, queue]);

  const handleRunTests = useCallback(
    (scopeLabel?: string) => {
      const nextRun = testRunCount + 1;
      const ms = 11 + ((nextRun * 3) % 7);
      const duration = `${ms}ms`;
      const cmd = scopeLabel ? `$ bun test ${scopeLabel}` : "$ bun test";

      setTestRunCount(nextRun);
      setLastTestDuration(duration);
      setShowBottomPanel(true);
      setBottomTab("terminal");

      const stamp = Date.now();
      setTerminalLines((prev) => [
        ...prev,
        { id: `t-${stamp}-0`, tone: "command", text: cmd },
        {
          id: `t-${stamp}-1`,
          tone: "pass",
          text: `✓ stylex-router > matches static and param routes [0.${84 + (nextRun % 9)}ms]`,
        },
        {
          id: `t-${stamp}-2`,
          tone: "pass",
          text: `✓ stylex-router > runs middleware in declaration order [0.${52 + (nextRun % 7)}ms]`,
        },
        {
          id: `t-${stamp}-3`,
          tone: "pass",
          text: `✓ stylex-router > returns 404 for unknown paths [0.${18 + (nextRun % 5)}ms]`,
        },
        {
          id: `t-${stamp}-4`,
          tone: "muted",
          text: ` 3 pass · 0 fail · 5 expect() calls · Run #${nextRun} finished in ${duration}.`,
        },
      ]);

      pushOutput("bun-test", `Run #${nextRun}: 3/3 tests passed in ${duration}.`);
      pushHistory(
        scopeLabel ? `Tested ${scopeLabel}` : "Ran bun test",
        `3 passed in ${duration}`,
      );
      queue.success("All 3 tests passed", {
        description: `stylex-router suite finished in ${duration} (0 failures).`,
      });
    },
    [pushHistory, pushOutput, queue, testRunCount],
  );

  const handleTerminalSubmit = useCallback(
    (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault();
      const raw = terminalCommand.trim();
      if (!raw) return;
      setTerminalCommand("");

      if (raw === "clear") {
        setTerminalLines([]);
        return;
      }

      if (raw.startsWith("bun test")) {
        const arg = raw.replace(/^bun test\s*/, "").trim();
        handleRunTests(arg || undefined);
        return;
      }

      const stamp = Date.now();
      if (raw === "bun typecheck" || raw === "tsc --noEmit") {
        setTerminalLines((prev) => [
          ...prev,
          { id: `t-${stamp}-c`, tone: "command", text: `$ ${raw}` },
          {
            id: `t-${stamp}-r`,
            tone: "pass",
            text: "✓ tsc --noEmit: 0 errors across 6 workspace files.",
          },
        ]);
        pushOutput("tsserver", "Manual typecheck passed with 0 errors.");
        return;
      }

      if (raw === "ls") {
        setTerminalLines((prev) => [
          ...prev,
          { id: `t-${stamp}-c`, tone: "command", text: "$ ls" },
          {
            id: `t-${stamp}-r`,
            tone: "info",
            text: "src/  test/  package.json  tsconfig.json",
          },
        ]);
        return;
      }

      if (raw === "help") {
        setTerminalLines((prev) => [
          ...prev,
          { id: `t-${stamp}-c`, tone: "command", text: "$ help" },
          {
            id: `t-${stamp}-r`,
            tone: "muted",
            text: "Commands: bun test | bun typecheck | ls | clear",
          },
        ]);
        return;
      }

      setTerminalLines((prev) => [
        ...prev,
        { id: `t-${stamp}-c`, tone: "command", text: `$ ${raw}` },
        {
          id: `t-${stamp}-r`,
          tone: "warn",
          text: `sh: command not found: ${raw.split(" ")[0]} (try: bun test, bun typecheck, ls, clear)`,
        },
      ]);
    },
    [handleRunTests, pushOutput, terminalCommand],
  );

  const handleResetWorkspace = useCallback(() => {
    setOpenTabs([validInitial, "src/match.ts", "test/router.test.ts"]);
    setActiveFileId(validInitial);
    setExpandedFolders(["src", "test"]);
    setFileQuery("");
    setShowExplorer(true);
    setShowBottomPanel(true);
    setShowInspector(true);
    setWordWrap(false);
    setFormattedFiles({});
    setTerminalLines(INITIAL_TERMINAL);
    setOutputLines(INITIAL_OUTPUT);
    setHistoryItems(INITIAL_HISTORY);
    queue.info("Workspace reset", {
      description: "Restored default panes, open tabs, and terminal buffer.",
    });
  }, [queue, validInitial]);

  const activeFileLines = useMemo(
    () => (activeFile ? activeFile.content.split("\n") : []),
    [activeFile],
  );

  const activeFileDiagnosticLines = useMemo(() => {
    if (!activeFile) return new Set<number>();
    return new Set(
      INITIAL_DIAGNOSTICS.filter((d) => d.fileId === activeFile.id).map(
        (d) => d.line,
      ),
    );
  }, [activeFile]);

  const horizontalSplitLayout =
    showExplorer && showInspector
      ? [20, 56, 24]
      : showExplorer
        ? [22, 78]
        : showInspector
          ? [74, 26]
          : [100];

  const allFoldersExpanded = expandedFolders.length >= 2;

  const renderFileLeaf = (file: WorkspaceFile) => {
    const isSelected = activeFileId === file.id;
    const hasDiagnostic = diagnosticFileIds.has(file.id);
    return (
      <TreeView.Item
        key={file.id}
        value={file.id}
        data-selected={isSelected ? "true" : undefined}
        onClick={() => openFile(file.id)}
      >
        <FileGlyph language={file.language} />
        <TreeView.ItemText style={styles.treeTextTruncate}>
          {file.name}
        </TreeView.ItemText>
        {hasDiagnostic ? (
          <span
            aria-label="Contains diagnostics"
            {...stylex.props(styles.treeBadgeDot)}
          />
        ) : null}
      </TreeView.Item>
    );
  };

  return (
    <VStack gap="0" palette={palette} style={[styles.root, style]}>
      {/* Top IDE Workspace Bar */}
      <HStack render={<header />} gap="2" justify="between" style={styles.header}>
        <HStack gap="2">
          <Square render={<span />} aria-hidden="true" style={styles.brandMark}>
            <Icon
              size="xs"
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.6"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M5.5 4.5 2 8l3.5 3.5" />
              <path d="M10.5 4.5 14 8l-3.5 3.5" />
              <path d="M9 3.5 7 12.5" />
            </Icon>
          </Square>
          <Text render={<span />} variant="mono" size="sm" weight="semibold" truncate="true">
            {workspaceName}
          </Text>
          <Badge variant="subtle" size="xs" style={styles.hideCompact}>
            v0.4.2
          </Badge>
          <Badge
            variant="surface"
            size="xs"
            palette={tealPalette}
            style={styles.hideCompact}
          >
            <BranchGlyph />
            {branch}
          </Badge>
        </HStack>

        <Toolbar.Root
          variant="plain"
          size="xs"
          aria-label="IDE workspace actions"
          style={styles.shrink0}
        >
          <Toolbar.Group aria-label="Panel visibility">
            <Toolbar.Button
              aria-label="Toggle file explorer"
              aria-pressed={showExplorer}
              style={showExplorer ? styles.paneToggleActive : undefined}
              onClick={() => setShowExplorer((v) => !v)}
            >
              <PanelLeftGlyph />
            </Toolbar.Button>
            <Toolbar.Button
              aria-label="Toggle bottom terminal panel"
              aria-pressed={showBottomPanel}
              style={showBottomPanel ? styles.paneToggleActive : undefined}
              onClick={() => setShowBottomPanel((v) => !v)}
            >
              <PanelBottomGlyph />
            </Toolbar.Button>
            <Toolbar.Button
              aria-label="Toggle properties inspector"
              aria-pressed={showInspector}
              style={showInspector ? styles.paneToggleActive : undefined}
              onClick={() => setShowInspector((v) => !v)}
            >
              <PanelRightGlyph />
            </Toolbar.Button>
          </Toolbar.Group>

          <Toolbar.Separator />

          <Toolbar.Group aria-label="Code actions">
            <Toolbar.Button
              disabled={!activeFile}
              onClick={handleFormatFile}
              style={styles.hideCompact}
            >
              <FormatGlyph />
              Format
            </Toolbar.Button>
            <Toolbar.Button disabled={!activeFile} onClick={handleCopyCode}>
              <CopyGlyph />
              Copy
            </Toolbar.Button>
            <Button
              variant="solid"
              size="xs"
              palette={accentPalette}
              onClick={() => handleRunTests()}
            >
              <PlayGlyph />
              Run Tests
            </Button>

            <Menu.Root size="sm">
              <Menu.Trigger
                render={
                  <IconButton
                    variant="ghost"
                    size="xs"
                    aria-label="More IDE commands"
                  />
                }
              >
                <MoreGlyph />
              </Menu.Trigger>
              <Menu.Content align="end" style={styles.menuContentWidth}>
                <Menu.Group>
                  <Menu.GroupLabel>Editor</Menu.GroupLabel>
                  <Menu.Item
                    disabled={!activeFile}
                    onSelect={handleFormatFile}
                  >
                    <Menu.ItemText>Format Document</Menu.ItemText>
                    <Menu.ItemCommand>⇧⌥F</Menu.ItemCommand>
                  </Menu.Item>
                  <Menu.Item onSelect={() => setWordWrap((v) => !v)}>
                    <Menu.ItemText>
                      {wordWrap ? "Disable Word Wrap" : "Enable Word Wrap"}
                    </Menu.ItemText>
                    <Menu.ItemCommand>⌥Z</Menu.ItemCommand>
                  </Menu.Item>
                  <Menu.Item
                    onSelect={() => {
                      setOpenTabs(WORKSPACE_FILES.map((f) => f.id));
                      if (!activeFileId) setActiveFileId(validInitial);
                    }}
                  >
                    <Menu.ItemText>Open All Workspace Files</Menu.ItemText>
                  </Menu.Item>
                </Menu.Group>
                <Menu.Separator />
                <Menu.Group>
                  <Menu.GroupLabel>Terminal</Menu.GroupLabel>
                  <Menu.Item onSelect={() => handleRunTests()}>
                    <Menu.ItemText>Run Test Suite</Menu.ItemText>
                    <Menu.ItemCommand>⌘⇧T</Menu.ItemCommand>
                  </Menu.Item>
                  <Menu.Item
                    onSelect={() => {
                      setTerminalLines([]);
                      queue.info("Terminal cleared");
                    }}
                  >
                    <Menu.ItemText>Clear Terminal Buffer</Menu.ItemText>
                    <Menu.ItemCommand>⌘K</Menu.ItemCommand>
                  </Menu.Item>
                </Menu.Group>
                <Menu.Separator />
                <Menu.Item onSelect={handleResetWorkspace}>
                  <Menu.ItemText>Reset Workspace</Menu.ItemText>
                </Menu.Item>
              </Menu.Content>
            </Menu.Root>
          </Toolbar.Group>
        </Toolbar.Root>
      </HStack>

      {/* Resizable 3-Pane IDE Workspace */}
      <HStack gap="0" style={styles.workspace}>
        <Splitter.Root
          key={`${showExplorer}-${showInspector}`}
          orientation="horizontal"
          defaultSize={horizontalSplitLayout}
          minSize={14}
        >
          {/* Left Pane: File Explorer */}
          {showExplorer ? (
            <>
              <Splitter.Panel style={styles.explorerPanel}>
                <VStack
                  render={<aside />}
                  gap="2.5"
                  aria-label="File explorer"
                  style={styles.sidebarInner}
                >
                  <HStack gap="2" justify="between" style={styles.paneHeaderRow}>
                    <Text render={<span />} variant="overline" tone="subtle">
                      Explorer
                    </Text>
                    <Button
                      variant="ghost"
                      size="2xs"
                      onClick={() =>
                        setExpandedFolders(
                          allFoldersExpanded ? [] : ["src", "test"],
                        )
                      }
                    >
                      {allFoldersExpanded ? "Collapse" : "Expand"}
                    </Button>
                  </HStack>

                  <div {...stylex.props(styles.searchBox)}>
                    <span {...stylex.props(styles.searchIconSlot)}>
                      <SearchGlyph />
                    </span>
                    <Input
                      aria-label="Filter workspace files"
                      size="xs"
                      variant="subtle"
                      placeholder="Filter files…"
                      value={fileQuery}
                      onValueChange={(value) => setFileQuery(value)}
                      style={styles.searchInput}
                    />
                  </div>

                  {filteredFiles.length === 0 ? (
                    <Text size="xs" tone="muted" style={styles.treeEmpty}>
                      No files match &ldquo;{fileQuery}&rdquo;.
                    </Text>
                  ) : (
                    <TreeView.Root
                      size="xs"
                      variant="subtle"
                      palette={accentPalette}
                      expandedValue={
                        fileQuery.trim() ? ["src", "test"] : expandedFolders
                      }
                      onExpandedChange={({ expandedValue }) =>
                        setExpandedFolders(expandedValue)
                      }
                    >
                      <TreeView.Tree aria-label="Workspace files">
                        {srcFiles.length > 0 ? (
                          <TreeView.Branch value="src">
                            <TreeView.BranchControl>
                              <TreeView.BranchIndicator>
                                <TreeView.Icon viewBox="0 0 16 16" fill="none">
                                  <path
                                    d="M6 3.5 10.5 8 6 12.5"
                                    stroke="currentColor"
                                    strokeWidth="1.5"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                  />
                                </TreeView.Icon>
                              </TreeView.BranchIndicator>
                              <span {...stylex.props(styles.folderIconMuted)}>
                                <FolderGlyph
                                  open={
                                    Boolean(fileQuery.trim()) ||
                                    expandedFolders.includes("src")
                                  }
                                />
                              </span>
                              <TreeView.BranchText
                                style={styles.treeTextTruncate}
                              >
                                src
                              </TreeView.BranchText>
                            </TreeView.BranchControl>
                            <TreeView.BranchContent>
                              <TreeView.BranchIndentGuide />
                              {srcFiles.map(renderFileLeaf)}
                            </TreeView.BranchContent>
                          </TreeView.Branch>
                        ) : null}

                        {testFiles.length > 0 ? (
                          <TreeView.Branch value="test">
                            <TreeView.BranchControl>
                              <TreeView.BranchIndicator>
                                <TreeView.Icon viewBox="0 0 16 16" fill="none">
                                  <path
                                    d="M6 3.5 10.5 8 6 12.5"
                                    stroke="currentColor"
                                    strokeWidth="1.5"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                  />
                                </TreeView.Icon>
                              </TreeView.BranchIndicator>
                              <span {...stylex.props(styles.folderIconMuted)}>
                                <FolderGlyph
                                  open={
                                    Boolean(fileQuery.trim()) ||
                                    expandedFolders.includes("test")
                                  }
                                />
                              </span>
                              <TreeView.BranchText
                                style={styles.treeTextTruncate}
                              >
                                test
                              </TreeView.BranchText>
                            </TreeView.BranchControl>
                            <TreeView.BranchContent>
                              <TreeView.BranchIndentGuide />
                              {testFiles.map(renderFileLeaf)}
                            </TreeView.BranchContent>
                          </TreeView.Branch>
                        ) : null}

                        {rootFiles.map(renderFileLeaf)}
                      </TreeView.Tree>
                    </TreeView.Root>
                  )}
                </VStack>
              </Splitter.Panel>

              <Splitter.ResizeTrigger
                aria-label="Resize file explorer"
                style={styles.explorerHandle}
              />
            </>
          ) : null}

          {/* Center Pane: Code Editor + Bottom Terminal/Problems/Output */}
          <Splitter.Panel style={styles.centerPanel}>
            <Splitter.Root
              key={showBottomPanel ? "editor-with-panel" : "editor-only"}
              orientation="vertical"
              defaultSize={showBottomPanel ? [66, 34] : [100]}
              minSize={20}
            >
              <Splitter.Panel style={styles.editorColumn}>
                {/* Open / Closable Editor Tabs */}
                {openTabs.length > 0 ? (
                  <HStack
                    gap="0"
                    align="stretch"
                    role="tablist"
                    aria-label="Open files"
                    style={styles.tabStrip}
                  >
                    {openTabs.map((tabId) => {
                      const file = filesById.get(tabId);
                      if (!file) return null;
                      const isActive = activeFileId === tabId;
                      const isFormatted = Boolean(formattedFiles[tabId]);
                      return (
                        <div
                          key={tabId}
                          {...stylex.props(
                            styles.editorTabItem,
                            isActive && styles.editorTabItemActive,
                          )}
                        >
                          <button
                            type="button"
                            role="tab"
                            aria-selected={isActive}
                            onClick={() => openFile(tabId)}
                            {...stylex.props(
                              styles.editorTabButton,
                              isActive && styles.editorTabButtonActive,
                            )}
                          >
                            <FileGlyph language={file.language} />
                            <span>{file.name}</span>
                            {isFormatted ? (
                              <span
                                title="Formatted this session"
                                {...stylex.props(styles.modifiedDot)}
                              />
                            ) : null}
                          </button>
                          <button
                            type="button"
                            aria-label={`Close ${file.name}`}
                            onClick={() => closeTab(tabId)}
                            {...stylex.props(styles.editorTabClose)}
                          >
                            <CloseGlyph />
                          </button>
                        </div>
                      );
                    })}
                  </HStack>
                ) : null}

                {/* Editor Body */}
                {activeFile ? (
                  <>
                    <HStack gap="2" justify="between" style={styles.breadcrumbBar}>
                      <HStack gap="1.5" style={styles.breadcrumbTrail}>
                        <span>{workspaceName}</span>
                        {activeFile.folder ? (
                          <>
                            <span>/</span>
                            <span>{activeFile.folder}</span>
                          </>
                        ) : null}
                        <span>/</span>
                        <Text render={<span />} variant="mono" size="xs" weight="medium">
                          {activeFile.name}
                        </Text>
                      </HStack>
                      <HStack gap="2" style={styles.shrink0}>
                        <Badge
                          variant="subtle"
                          size="xs"
                          palette={
                            activeFile.language === "typescript"
                              ? bluePalette
                              : amberPalette
                          }
                        >
                          {activeFile.languageLabel}
                        </Badge>
                        <span>{activeFileLines.length} lines</span>
                      </HStack>
                    </HStack>

                    <CodeBlock.Root size="sm" style={styles.codeBlockRoot}>
                      <CodeBlock.Content style={styles.codeBlockContent}>
                        <CodeBlock.Code
                          style={[
                            styles.codeBlockPre,
                            wordWrap && styles.codeBlockPreWrap,
                          ]}
                        >
                          <CodeBlock.CodeText style={styles.codeBlockText}>
                            {activeFileLines.map((lineText, idx) => {
                              const lineNum = idx + 1;
                              const isSelectedLine = lineNum === activeLine;
                              const hasWarning =
                                activeFileDiagnosticLines.has(lineNum);
                              const tokens = tokenizeLine(
                                lineText,
                                activeFile.language,
                              );
                              return (
                                <div
                                  key={`${activeFile.id}-${lineNum}`}
                                  onClick={() => {
                                    setActiveLines((prev) => ({
                                      ...prev,
                                      [activeFile.id]: lineNum,
                                    }));
                                    setCursorCol(
                                      Math.min(lineText.length + 1, 14),
                                    );
                                  }}
                                  {...stylex.props(
                                    styles.codeRow,
                                    hasWarning && styles.codeRowWarning,
                                    isSelectedLine && styles.codeRowActive,
                                  )}
                                >
                                  <span
                                    aria-hidden="true"
                                    {...stylex.props(
                                      styles.lineNumber,
                                      isSelectedLine && styles.lineNumberActive,
                                    )}
                                  >
                                    {lineNum}
                                  </span>
                                  <span {...stylex.props(styles.lineContent)}>
                                    {tokens.map((tok, tokIdx) => (
                                      <span
                                        key={tokIdx}
                                        {...stylex.props(
                                          TOKEN_STYLE_MAP[tok.kind],
                                        )}
                                      >
                                        {tok.text}
                                      </span>
                                    ))}
                                  </span>
                                </div>
                              );
                            })}
                          </CodeBlock.CodeText>
                        </CodeBlock.Code>
                      </CodeBlock.Content>
                    </CodeBlock.Root>
                  </>
                ) : (
                  <EmptyState.Root size="md">
                    <EmptyState.Content>
                      <EmptyState.Indicator>
                        <EmptyState.Icon
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <path d="M8 7 3 12l5 5" />
                          <path d="m16 7 5 5-5 5" />
                          <path d="m14 4-4 16" />
                        </EmptyState.Icon>
                      </EmptyState.Indicator>
                      <EmptyState.Title>No open editors</EmptyState.Title>
                      <EmptyState.Description>
                        Pick a file from the explorer or reopen one of the core{" "}
                        {workspaceName} modules.
                      </EmptyState.Description>
                      <EmptyState.Actions>
                        <Button
                          variant="solid"
                          size="sm"
                          palette={accentPalette}
                          onClick={() => openFile("src/router.ts")}
                        >
                          Open src/router.ts
                        </Button>
                        <Button
                          variant="surface"
                          size="sm"
                          onClick={() => openFile("test/router.test.ts")}
                        >
                          Open router.test.ts
                        </Button>
                      </EmptyState.Actions>
                    </EmptyState.Content>
                  </EmptyState.Root>
                )}
              </Splitter.Panel>

              {/* Bottom Resizable Panel: Terminal / Problems / Output */}
              {showBottomPanel ? (
                <>
                  <Splitter.ResizeTrigger aria-label="Resize terminal panel" />
                  <Splitter.Panel style={styles.bottomPanel}>
                    <Tabs.Root
                      value={bottomTab}
                      onValueChange={(next) => {
                        if (next) setBottomTab(next as BottomPanelTab);
                      }}
                      variant="line"
                      size="xs"
                      palette={accentPalette}
                      style={styles.bottomTabsRoot}
                    >
                      <HStack gap="2" justify="between" style={styles.bottomTabHeader}>
                        <Tabs.List
                          aria-label="Workbench panels"
                          style={styles.bottomTabsList}
                        >
                          <Tabs.Tab value="terminal">Terminal</Tabs.Tab>
                          <Tabs.Tab value="problems">
                            Problems
                            <Badge
                              variant="subtle"
                              size="xs"
                              palette={amberPalette}
                            >
                              {INITIAL_DIAGNOSTICS.length}
                            </Badge>
                          </Tabs.Tab>
                          <Tabs.Tab value="output">Output</Tabs.Tab>
                        </Tabs.List>

                        <HStack gap="1" style={styles.shrink0}>
                          {bottomTab === "terminal" ? (
                            <>
                              <Button
                                variant="ghost"
                                size="2xs"
                                onClick={() => handleRunTests()}
                              >
                                <PlayGlyph />
                                Re-run
                              </Button>
                              <Button
                                variant="ghost"
                                size="2xs"
                                onClick={() => setTerminalLines([])}
                              >
                                Clear
                              </Button>
                            </>
                          ) : null}
                          <IconButton
                            variant="ghost"
                            size="2xs"
                            aria-label="Close bottom panel"
                            onClick={() => setShowBottomPanel(false)}
                          >
                            <CloseGlyph />
                          </IconButton>
                        </HStack>
                      </HStack>

                      <Tabs.Panel value="terminal" style={styles.bottomTabPanel}>
                        <VStack
                          gap="1"
                          role="log"
                          aria-label="Terminal output"
                          style={styles.terminalScroll}
                        >
                          {terminalLines.length === 0 ? (
                            <p
                              {...stylex.props(
                                styles.terminalLine,
                                styles.termMuted,
                              )}
                            >
                              Terminal buffer cleared. Type &ldquo;bun test&rdquo;
                              or click Re-run.
                            </p>
                          ) : (
                            terminalLines.map((entry) => (
                              <p
                                key={entry.id}
                                {...stylex.props(
                                  styles.terminalLine,
                                  entry.tone === "command" && styles.termCommand,
                                  entry.tone === "pass" && styles.termPass,
                                  entry.tone === "info" && styles.termInfo,
                                  entry.tone === "warn" && styles.termWarn,
                                  entry.tone === "muted" && styles.termMuted,
                                )}
                              >
                                {entry.text}
                              </p>
                            ))
                          )}
                        </VStack>
                        <HStack
                          render={<form onSubmit={handleTerminalSubmit} />}
                          gap="2"
                          style={styles.terminalPromptBar}
                        >
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            weight="semibold"
                            palette={accentPalette}
                            tone="accent"
                            style={styles.noSelect}
                          >
                            $
                          </Text>
                          <Input
                            aria-label="Terminal command input"
                            size="xs"
                            variant="flushed"
                            placeholder="bun test · bun typecheck · ls · clear"
                            value={terminalCommand}
                            onValueChange={(value) => setTerminalCommand(value)}
                            style={styles.terminalInput}
                          />
                          <Kbd size="xs" variant="subtle">
                            ↵
                          </Kbd>
                        </HStack>
                      </Tabs.Panel>

                      <Tabs.Panel value="problems" style={styles.bottomTabPanel}>
                        <VStack gap="0" style={styles.problemsList}>
                          {INITIAL_DIAGNOSTICS.map((diag) => (
                            <button
                              key={diag.id}
                              type="button"
                              onClick={() =>
                                openFile(diag.fileId, diag.line, diag.col)
                              }
                              {...stylex.props(styles.problemRow)}
                            >
                              <VStack render={<span />} gap="0.5">
                                <Text render={<span />} size="xs">
                                  {diag.message}
                                </Text>
                                <Text render={<span />} variant="mono" size="xs" tone="muted">
                                  {diag.path}:{diag.line}:{diag.col} ·{" "}
                                  {diag.code}
                                </Text>
                              </VStack>
                              <Badge
                                variant="subtle"
                                size="xs"
                                palette={
                                  diag.severity === "warning"
                                    ? amberPalette
                                    : bluePalette
                                }
                              >
                                {diag.severity}
                              </Badge>
                            </button>
                          ))}
                        </VStack>
                      </Tabs.Panel>

                      <Tabs.Panel value="output" style={styles.bottomTabPanel}>
                        <VStack gap="1" style={styles.outputScroll}>
                          {outputLines.map((entry) => (
                            <HStack key={entry.id} gap="2" align="start">
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                tone="subtle"
                                tabular="true"
                                style={styles.shrink0}
                              >
                                [{entry.time}]
                              </Text>
                              <span {...stylex.props(styles.outputChannel)}>
                                [{entry.channel}]
                              </span>
                              <span>{entry.message}</span>
                            </HStack>
                          ))}
                        </VStack>
                      </Tabs.Panel>
                    </Tabs.Root>
                  </Splitter.Panel>
                </>
              ) : null}
            </Splitter.Root>
          </Splitter.Panel>

          {/* Right Pane: File Properties & Session History Inspector */}
          {showInspector ? (
            <>
              <Splitter.ResizeTrigger
                aria-label="Resize properties inspector"
                style={styles.inspectorHandle}
              />
              <Splitter.Panel style={styles.inspectorPanel}>
                <VStack
                  render={<aside />}
                  gap="3"
                  aria-label="File inspector"
                  style={styles.inspectorInner}
                >
                  <SegmentGroup.Root
                    aria-label="Inspector sections"
                    size="xs"
                    value={inspectorTab}
                    onValueChange={(value) =>
                      setInspectorTab(value as InspectorTab)
                    }
                    style={styles.segmentFull}
                  >
                    <SegmentGroup.Item
                      value="properties"
                      style={styles.segmentItemFill}
                    >
                      Properties
                    </SegmentGroup.Item>
                    <SegmentGroup.Item
                      value="history"
                      style={styles.segmentItemFill}
                    >
                      History
                    </SegmentGroup.Item>
                  </SegmentGroup.Root>

                  {inspectorTab === "properties" ? (
                    activeFile ? (
                      <>
                        <VStack gap="1">
                          <HStack gap="2" justify="between">
                            <Heading
                              render={<h2 />}
                              size="sm"
                              style={styles.inspectorHeading}
                            >
                              {activeFile.name}
                            </Heading>
                            <Badge
                              variant="subtle"
                              size="xs"
                              palette={
                                activeFile.language === "typescript"
                                  ? bluePalette
                                  : amberPalette
                              }
                            >
                              {activeFile.language === "typescript"
                                ? "TS"
                                : "JSON"}
                            </Badge>
                          </HStack>
                          <Text variant="mono" size="xs" tone="muted">
                            {activeFile.path}
                          </Text>
                        </VStack>

                        <DataList.Root
                          size="sm"
                          orientation="horizontal"
                          style={styles.metadataCompact}
                        >
                          <DataList.Item>
                            <DataList.ItemLabel style={styles.metadataLabel}>
                              Type
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              {activeFile.fileType}
                            </DataList.ItemValue>
                          </DataList.Item>
                          <DataList.Item>
                            <DataList.ItemLabel style={styles.metadataLabel}>
                              Lines
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              {activeFileLines.length}
                            </DataList.ItemValue>
                          </DataList.Item>
                          <DataList.Item>
                            <DataList.ItemLabel style={styles.metadataLabel}>
                              Size
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              {activeFile.sizeLabel}
                            </DataList.ItemValue>
                          </DataList.Item>
                          <DataList.Item>
                            <DataList.ItemLabel style={styles.metadataLabel}>
                              Imports
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              {activeFile.importsCount}
                            </DataList.ItemValue>
                          </DataList.Item>
                          <DataList.Item>
                            <DataList.ItemLabel style={styles.metadataLabel}>
                              Exports
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              {activeFile.exportsCount}
                            </DataList.ItemValue>
                          </DataList.Item>
                          <DataList.Item>
                            <DataList.ItemLabel style={styles.metadataLabel}>
                              Modified
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              {formattedFiles[activeFile.id]
                                ? "Just now"
                                : activeFile.lastModified}
                            </DataList.ItemValue>
                          </DataList.Item>
                        </DataList.Root>

                        <Separator decorative />

                        <VStack gap="1.5">
                          <Text render={<span />} variant="overline" tone="subtle">
                            Outline
                          </Text>
                          <VStack gap="0.5">
                            {activeFile.symbols.map((sym) => (
                              <button
                                key={`${activeFile.id}-${sym.name}`}
                                type="button"
                                onClick={() => {
                                  setActiveLines((prev) => ({
                                    ...prev,
                                    [activeFile.id]: sym.line,
                                  }));
                                  setCursorCol(1);
                                }}
                                {...stylex.props(styles.symbolRow)}
                              >
                                <Text render={<span />} variant="mono" size="xs" truncate="true">
                                  {sym.name}
                                </Text>
                                <Text
                                  render={<span />}
                                  variant="mono"
                                  size="xs"
                                  tone="subtle"
                                  tabular="true"
                                  style={styles.shrink0}
                                >
                                  :{sym.line}
                                </Text>
                              </button>
                            ))}
                          </VStack>
                        </VStack>

                        <VStack gap="1.5" style={styles.inspectorActions}>
                          <Button
                            variant="surface"
                            size="xs"
                            style={styles.actionButtonFull}
                            onClick={handleFormatFile}
                          >
                            <FormatGlyph />
                            Format Document
                          </Button>
                          <Button
                            variant="surface"
                            size="xs"
                            style={styles.actionButtonFull}
                            onClick={() => handleRunTests(activeFile.path)}
                          >
                            <PlayGlyph />
                            Run Tests for File
                          </Button>
                          <Button
                            variant="surface"
                            size="xs"
                            style={styles.actionButtonFull}
                            onClick={() => {
                              if (
                                typeof navigator !== "undefined" &&
                                navigator.clipboard?.writeText
                              ) {
                                void navigator.clipboard
                                  .writeText(activeFile.path)
                                  .catch(() => {});
                              }
                              queue.info("Copied relative path", {
                                description: activeFile.path,
                              });
                            }}
                          >
                            <CopyGlyph />
                            Copy Relative Path
                          </Button>
                        </VStack>
                      </>
                    ) : (
                      <Text size="xs" tone="muted" style={styles.treeEmpty}>
                        Open a file to inspect its symbols and metadata.
                      </Text>
                    )
                  ) : (
                    <VStack gap="1">
                      {historyItems.map((item) => (
                        <HStack
                          key={item.id}
                          gap="2"
                          align="start"
                          style={styles.historyRow}
                        >
                          <span {...stylex.props(styles.historyIcon)}>
                            <ClockGlyph />
                          </span>
                          <VStack gap="0.5" style={styles.flexGrow}>
                            <Text render={<span />} size="xs" weight="medium">
                              {item.label}
                            </Text>
                            <Text render={<span />} variant="mono" size="xs" tone="muted">
                              {item.detail}
                            </Text>
                          </VStack>
                          <Text
                            render={<span />}
                            size="xs"
                            tone="subtle"
                            style={styles.shrink0}
                          >
                            {item.time}
                          </Text>
                        </HStack>
                      ))}
                    </VStack>
                  )}
                </VStack>
              </Splitter.Panel>
            </>
          ) : null}
        </Splitter.Root>
      </HStack>

      {/* Bottom IDE Status Bar */}
      <HStack
        render={<footer />}
        gap="3"
        justify="between"
        aria-label="Editor status bar"
        style={styles.statusBar}
      >
        <HStack gap="3">
          <span {...stylex.props(styles.statusItem, styles.statusMono)}>
            <BranchGlyph />
            {branch}
          </span>
          <Status.Root size="sm" palette={emeraldPalette}>
            <Status.Indicator />
            <span>3/3 passing ({lastTestDuration})</span>
          </Status.Root>
          <button
            type="button"
            onClick={() => {
              setShowBottomPanel(true);
              setBottomTab("problems");
            }}
            {...stylex.props(styles.statusButton)}
          >
            <span>0 errors · {INITIAL_DIAGNOSTICS.length} notices</span>
          </button>
        </HStack>

        <HStack gap="3">
          <span {...stylex.props(styles.statusItem, styles.statusMono)}>
            Ln {activeLine}, Col {cursorCol}
          </span>
          <span {...stylex.props(styles.statusItem, styles.hideCompact)}>
            Spaces: 2
          </span>
          <span {...stylex.props(styles.statusItem, styles.hideCompact)}>
            UTF-8
          </span>
          <Badge
            variant="plain"
            size="xs"
            palette={
              activeFile?.language === "json" ? amberPalette : purplePalette
            }
          >
            {activeFile?.languageLabel ?? "Plain Text"}
          </Badge>
        </HStack>
      </HStack>

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

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