---
title: "Tree Table · UI SDK — StyleX Blocks"
description: "Hierarchical work breakdown and cost rollup tree table with multi-level expand/collapse, visual tree guide lines, live parent rollups, hierarchical indeterminate selection, ancestor-preserving search and health filters, in-place sibling sorting, keyboard treegrid navigation, a floating bulk ActionBar, and a node inspector Drawer."
url: "https://stylexblocks.com/block/ui-sdk/tree-table/"
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/"
---

# Tree Table block

Hierarchical work breakdown and cost rollup tree table with multi-level expand/collapse, visual tree guide lines, live parent rollups, hierarchical indeterminate selection, ancestor-preserving search and health filters, in-place sibling sorting, keyboard treegrid navigation, a floating bulk ActionBar, and a node inspector Drawer.

- Behavior engine: UI SDK
- Category: [Data tables](https://stylexblocks.com/blocks/tables.md)
- Built with: [Action Bar](https://stylexblocks.com/components/ui-sdk/action-bar.md), [Alert](https://stylexblocks.com/components/ui-sdk/alert.md), [Avatar](https://stylexblocks.com/components/ui-sdk/avatar.md), [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Breadcrumb](https://stylexblocks.com/components/ui-sdk/breadcrumb.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Data List](https://stylexblocks.com/components/ui-sdk/data-list.md), [Drawer](https://stylexblocks.com/components/ui-sdk/drawer.md), [Empty State](https://stylexblocks.com/components/ui-sdk/empty-state.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Menu](https://stylexblocks.com/components/ui-sdk/menu.md), [Progress](https://stylexblocks.com/components/ui-sdk/progress.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [Select](https://stylexblocks.com/components/ui-sdk/select.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Status](https://stylexblocks.com/components/ui-sdk/status.md), [Table](https://stylexblocks.com/components/ui-sdk/table.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md), [Visually Hidden](https://stylexblocks.com/components/ui-sdk/visually-hidden.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/tree-table/

## 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 tree-table
```

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

## Usage

```tsx
import { TreeTable } from "#components/blocks/ui-sdk/tree-table.tsx";

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

## Source

`components/blocks/ui-sdk/tree-table.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActionBar } from "#components/ui/ui-sdk/action-bar.tsx";
import { Alert } from "#components/ui/ui-sdk/alert.tsx";
import { Avatar } from "#components/ui/ui-sdk/avatar.tsx";
import { Badge } from "#components/ui/ui-sdk/badge.tsx";
import { Breadcrumb } from "#components/ui/ui-sdk/breadcrumb.tsx";
import { Button } from "#components/ui/ui-sdk/button.tsx";
import { Square } from "#components/ui/ui-sdk/center.tsx";
import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";
import { DataList } from "#components/ui/ui-sdk/data-list.tsx";
import { Drawer } from "#components/ui/ui-sdk/drawer.tsx";
import { EmptyState } from "#components/ui/ui-sdk/empty-state.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { Menu } from "#components/ui/ui-sdk/menu.tsx";
import { Progress } from "#components/ui/ui-sdk/progress.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";
import { Select } from "#components/ui/ui-sdk/select.tsx";
import { Separator } from "#components/ui/ui-sdk/separator.tsx";
import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Status } from "#components/ui/ui-sdk/status.tsx";
import { Table } from "#components/ui/ui-sdk/table.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import { VisuallyHidden } from "#components/ui/ui-sdk/visually-hidden.tsx";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import {
  accentPalette,
  amberPalette,
  bluePalette,
  cyanPalette,
  emeraldPalette,
  grayPalette,
  greenPalette,
  indigoPalette,
  orangePalette,
  purplePalette,
  redPalette,
  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 { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

const COMPACT_CONTAINER = "@container tree-table (max-width: 900px)";
const NARROW_CONTAINER = "@container tree-table (max-width: 640px)";

export type WbsLevel = "division" | "subsystem" | "work-package";
export type WbsHealth = "on-track" | "at-risk" | "over-budget" | "complete";
type LeadTone =
  | "blue"
  | "indigo"
  | "teal"
  | "purple"
  | "emerald"
  | "cyan"
  | "amber"
  | "orange";

export interface EngineerLead {
  name: string;
  initials: string;
  role: string;
  tone: LeadTone;
}

export interface WbsNode {
  id: string;
  wbsCode: string;
  name: string;
  level: WbsLevel;
  lead: EngineerLead;
  milestone: string;
  targetDate: string;
  notes: string;
  /** Direct budget in whole USD for leaf work packages; derived on parents. */
  budgetUsd?: number;
  /** Direct actual spend in whole USD for leaf work packages; derived on parents. */
  actualUsd?: number;
  /** Direct completion percentage (0–100) for leaf work packages; derived on parents. */
  completion?: number;
  /** Direct health status for leaf work packages; derived on parents. */
  health?: WbsHealth;
  children?: WbsNode[];
}

interface ComputedWbsNode extends Omit<WbsNode, "children" | "budgetUsd" | "actualUsd" | "completion" | "health"> {
  budgetUsd: number;
  actualUsd: number;
  variancePct: number;
  completion: number;
  health: WbsHealth;
  leafCount: number;
  directChildCount: number;
  leafIds: string[];
  children?: ComputedWbsNode[];
}

interface WbsCrumb {
  id: string;
  wbsCode: string;
  name: string;
}

interface VisibleTreeRow {
  node: ComputedWbsNode;
  depth: 0 | 1 | 2;
  parentId: string | null;
  ancestorPath: WbsCrumb[];
  /** For each ancestor depth 0..depth-1, true if a vertical continuation line should be drawn. */
  guideMask: boolean[];
  isLastSibling: boolean;
  posInSet: number;
  setSize: number;
  hasChildren: boolean;
  isExpanded: boolean;
}

type HealthFilter = "all" | WbsHealth;
type DepthPreset = "1" | "2" | "3";
type SortKey =
  | "wbs"
  | "budgetUsd"
  | "actualUsd"
  | "variancePct"
  | "completion"
  | "health";
type SortDirection = "asc" | "desc";

interface FilterOption<T extends string> {
  value: T;
  label: string;
}

const LEADS = {
  elena: {
    name: "Dr. Elena Rostova",
    initials: "ER",
    role: "Chief Propulsion Lead",
    tone: "blue",
  },
  marcus: {
    name: "Marcus Okonkwo",
    initials: "MO",
    role: "Turbomachinery Architect",
    tone: "indigo",
  },
  hana: {
    name: "Hana Takahashi",
    initials: "HT",
    role: "Cryogenics & Thermal Lead",
    tone: "teal",
  },
  david: {
    name: "David Morales",
    initials: "DM",
    role: "Avionics Director",
    tone: "purple",
  },
  priya: {
    name: "Priya Deshmukh",
    initials: "PD",
    role: "Flight Software Principal",
    tone: "emerald",
  },
  soren: {
    name: "Soren Lindholm",
    initials: "SL",
    role: "RF & Telemetry Lead",
    tone: "cyan",
  },
  claire: {
    name: "Claire Beaumont",
    initials: "CB",
    role: "Chief Structures Engineer",
    tone: "amber",
  },
  rafael: {
    name: "Rafael Mendoza",
    initials: "RM",
    role: "Launch Operations Lead",
    tone: "orange",
  },
} as const satisfies Record<string, EngineerLead>;

const LEAD_PALETTES = {
  blue: bluePalette,
  indigo: indigoPalette,
  teal: tealPalette,
  purple: purplePalette,
  emerald: emeraldPalette,
  cyan: cyanPalette,
  amber: amberPalette,
  orange: orangePalette,
} as const;

const HEALTH_LABELS: Record<WbsHealth, string> = {
  "on-track": "On track",
  "at-risk": "At risk",
  "over-budget": "Over budget",
  complete: "Complete",
};

const HEALTH_PALETTES = {
  "on-track": greenPalette,
  "at-risk": amberPalette,
  "over-budget": redPalette,
  complete: bluePalette,
} as const;

const HEALTH_SEVERITY: Record<WbsHealth, number> = {
  "over-budget": 0,
  "at-risk": 1,
  "on-track": 2,
  complete: 3,
};

const LEVEL_LABELS: Record<WbsLevel, string> = {
  division: "Division",
  subsystem: "Subsystem",
  "work-package": "Work package",
};

const DEPTH_OPTIONS: ReadonlyArray<FilterOption<DepthPreset>> = [
  { value: "1", label: "L1 Divisions" },
  { value: "2", label: "L2 Subsystems" },
  { value: "3", label: "L3 All" },
];

const HEALTH_OPTIONS: ReadonlyArray<FilterOption<HealthFilter>> = [
  { value: "all", label: "All health states" },
  { value: "on-track", label: "On track" },
  { value: "at-risk", label: "At risk" },
  { value: "over-budget", label: "Over budget" },
  { value: "complete", label: "Complete" },
];

const DEFAULT_WBS_DATA: WbsNode[] = [
  {
    id: "wbs-1",
    wbsCode: "1.0",
    name: "Propulsion & Cryogenics",
    level: "division",
    lead: LEADS.elena,
    milestone: "CDR-2",
    targetDate: "2027-01-22",
    notes:
      "Methalox main propulsion stack, staged-combustion turbomachinery, and flight cryogenic tankage for Helios-9 Block I.",
    children: [
      {
        id: "wbs-1-1",
        wbsCode: "1.1",
        name: "Main Stage Engine (HE-9)",
        level: "subsystem",
        lead: LEADS.marcus,
        milestone: "FRR-0",
        targetDate: "2027-01-22",
        notes:
          "2,400 kN sea-level staged-combustion engine assembly undergoing metallurgy and full-duration stand qualification.",
        children: [
          {
            id: "wbs-1-1-1",
            wbsCode: "1.1.1",
            name: "LOX/CH4 Turbopump Impeller Metallurgy",
            level: "work-package",
            lead: LEADS.marcus,
            milestone: "CDR-2",
            targetDate: "2026-12-18",
            budgetUsd: 4_800_000,
            actualUsd: 5_180_000,
            completion: 82,
            health: "over-budget",
            notes:
              "Secondary nickel-superalloy HIP forging lot required after ultrasonic inspection flagged micro-porosity in lot B.",
          },
          {
            id: "wbs-1-1-2",
            wbsCode: "1.1.2",
            name: "Main Injector Acoustic Baffle Array",
            level: "work-package",
            lead: LEADS.elena,
            milestone: "QTR-1",
            targetDate: "2026-12-09",
            budgetUsd: 3_200_000,
            actualUsd: 2_940_000,
            completion: 94,
            health: "on-track",
            notes:
              "3D-printed copper-chrome-zirconium baffle plates passed high-frequency combustion instability damping checks.",
          },
          {
            id: "wbs-1-1-3",
            wbsCode: "1.1.3",
            name: "Full-Duration Hot-Fire Stand Qualification",
            level: "work-package",
            lead: LEADS.elena,
            milestone: "FRR-0",
            targetDate: "2027-01-22",
            budgetUsd: 5_600_000,
            actualUsd: 4_650_000,
            completion: 64,
            health: "at-risk",
            notes:
              "Test Stand B2 propellant subcooler refurbishment shifted the 310-second throttle-profile burn window by 9 days.",
          },
        ],
      },
      {
        id: "wbs-1-2",
        wbsCode: "1.2",
        name: "Cryogenic Propellant Tanks",
        level: "subsystem",
        lead: LEADS.hana,
        milestone: "CDR-4",
        targetDate: "2026-12-28",
        notes:
          "Common-bulkhead Al-Li 2195 primary tank barrels, friction-stir welded domes, and multi-layer boiloff insulation.",
        children: [
          {
            id: "wbs-1-2-1",
            wbsCode: "1.2.1",
            name: "Al-Li Bulkhead Friction-Stir Welding",
            level: "work-package",
            lead: LEADS.hana,
            milestone: "PRR-3",
            targetDate: "2026-11-15",
            budgetUsd: 4_100_000,
            actualUsd: 3_980_000,
            completion: 100,
            health: "complete",
            notes:
              "Hydrostatic proof test at 1.4x MEOP completed with zero seam anomalies; flight article cleared for mate.",
          },
          {
            id: "wbs-1-2-2",
            wbsCode: "1.2.2",
            name: "Zero-Boiloff Multi-Layer Thermal Insulation",
            level: "work-package",
            lead: LEADS.hana,
            milestone: "CDR-4",
            targetDate: "2026-12-28",
            budgetUsd: 2_750_000,
            actualUsd: 2_420_000,
            completion: 76,
            health: "on-track",
            notes:
              "Vacuum-chamber boiloff flux measured within 4% of analytical target across 48-hour coast simulation.",
          },
        ],
      },
    ],
  },
  {
    id: "wbs-2",
    wbsCode: "2.0",
    name: "Avionics & Flight Software",
    level: "division",
    lead: LEADS.david,
    milestone: "ITR-1",
    targetDate: "2027-01-08",
    notes:
      "Fault-tolerant flight computers, real-time convex guidance, hardware-in-the-loop verification, and range safety RF links.",
    children: [
      {
        id: "wbs-2-1",
        wbsCode: "2.1",
        name: "Guidance, Navigation & Control",
        level: "subsystem",
        lead: LEADS.priya,
        milestone: "ITR-1",
        targetDate: "2027-01-08",
        notes:
          "Triple-modular redundant inertial navigation and closed-loop powered-descent guidance algorithms.",
        children: [
          {
            id: "wbs-2-1-1",
            wbsCode: "2.1.1",
            name: "Triple-Redundant IMU Sensor Fusion Core",
            level: "work-package",
            lead: LEADS.david,
            milestone: "QTR-2",
            targetDate: "2026-11-20",
            budgetUsd: 3_400_000,
            actualUsd: 3_280_000,
            completion: 100,
            health: "complete",
            notes:
              "Radiation-hardened FPGA voting logic and ring-laser gyro calibration signed off under thermal-vacuum cycling.",
          },
          {
            id: "wbs-2-1-2",
            wbsCode: "2.1.2",
            name: "Powered-Descent Convex Trajectory Solver",
            level: "work-package",
            lead: LEADS.priya,
            milestone: "CDR-5",
            targetDate: "2026-12-14",
            budgetUsd: 2_900_000,
            actualUsd: 2_610_000,
            completion: 88,
            health: "on-track",
            notes:
              "Worst-case Monte Carlo 10,000-run dispersion suite converges inside 14 ms cycle budget on flight CPU.",
          },
          {
            id: "wbs-2-1-3",
            wbsCode: "2.1.3",
            name: "Hardware-in-the-Loop Avionics FlatSat Rig",
            level: "work-package",
            lead: LEADS.priya,
            milestone: "ITR-1",
            targetDate: "2027-01-08",
            budgetUsd: 2_250_000,
            actualUsd: 2_430_000,
            completion: 71,
            health: "over-budget",
            notes:
              "Expedited procurement of second real-time actuator load simulator rack to unblock parallel flight-software shifts.",
          },
        ],
      },
      {
        id: "wbs-2-2",
        wbsCode: "2.2",
        name: "Telemetry & RF Communications",
        level: "subsystem",
        lead: LEADS.soren,
        milestone: "CDR-3",
        targetDate: "2026-12-21",
        notes:
          "High-rate Ka-band telemetry downlink and dual-string range-certified autonomous flight termination system.",
        children: [
          {
            id: "wbs-2-2-1",
            wbsCode: "2.2.1",
            name: "Ka-Band Phased Array Downlink Transceiver",
            level: "work-package",
            lead: LEADS.soren,
            milestone: "CDR-3",
            targetDate: "2026-12-21",
            budgetUsd: 2_600_000,
            actualUsd: 2_310_000,
            completion: 84,
            health: "on-track",
            notes:
              "Anechoic chamber beam-steering validation confirmed 120 Mbps link margin at 1,800 km slant range.",
          },
          {
            id: "wbs-2-2-2",
            wbsCode: "2.2.2",
            name: "Autonomous Flight Termination Unit (AFTS)",
            level: "work-package",
            lead: LEADS.soren,
            milestone: "FRR-1",
            targetDate: "2026-12-11",
            budgetUsd: 1_950_000,
            actualUsd: 1_890_000,
            completion: 95,
            health: "on-track",
            notes:
              "Eastern Range mission ruleset verification complete; final pyrotechnic initiator harness audit underway.",
          },
        ],
      },
    ],
  },
  {
    id: "wbs-3",
    wbsCode: "3.0",
    name: "Structures & Launch Operations",
    level: "division",
    lead: LEADS.claire,
    milestone: "CDR-6",
    targetDate: "2027-01-30",
    notes:
      "Composite primary airframe, thermal protection system, and launch complex 42 ground support infrastructure.",
    children: [
      {
        id: "wbs-3-1",
        wbsCode: "3.1",
        name: "Composite Airframe & Thermal Shield",
        level: "subsystem",
        lead: LEADS.claire,
        milestone: "CDR-6",
        targetDate: "2027-01-30",
        notes:
          "5.4-meter carbon-epoxy payload fairing, stage separation mechanisms, and reusable re-entry thermal protection.",
        children: [
          {
            id: "wbs-3-1-1",
            wbsCode: "3.1.1",
            name: "Carbon-Epoxy Payload Fairing Acoustic Liners",
            level: "work-package",
            lead: LEADS.claire,
            milestone: "PRR-2",
            targetDate: "2026-11-10",
            budgetUsd: 3_100_000,
            actualUsd: 2_960_000,
            completion: 100,
            health: "complete",
            notes:
              "Reverberant acoustic chamber test achieved 136 dB OASPL interior attenuation, beating payload envelope by 3 dB.",
          },
          {
            id: "wbs-3-1-2",
            wbsCode: "3.1.2",
            name: "Pneumatic Interstage Separation Pusher Ring",
            level: "work-package",
            lead: LEADS.claire,
            milestone: "QTR-3",
            targetDate: "2026-12-19",
            budgetUsd: 2_400_000,
            actualUsd: 2_190_000,
            completion: 91,
            health: "on-track",
            notes:
              "Low-shock cold-gas separation latches completed 12 consecutive zero-pyro actuation cycles under cryo soak.",
          },
          {
            id: "wbs-3-1-3",
            wbsCode: "3.1.3",
            name: "Carbon-Phenolic Re-entry Heatshield Bonding",
            level: "work-package",
            lead: LEADS.claire,
            milestone: "CDR-6",
            targetDate: "2027-01-30",
            budgetUsd: 4_400_000,
            actualUsd: 4_620_000,
            completion: 58,
            health: "at-risk",
            notes:
              "Arc-jet coupon test showed adhesive peel margin tightening at peak Mach 7.8 shear; re-formulated primer curing in test.",
          },
        ],
      },
      {
        id: "wbs-3-2",
        wbsCode: "3.2",
        name: "Pad Infrastructure & Ground Support",
        level: "subsystem",
        lead: LEADS.rafael,
        milestone: "ORR-1",
        targetDate: "2027-01-15",
        notes:
          "Transporter-erector strongback interfaces, cryo umbilical retraction, and pad acoustic water deluge system.",
        children: [
          {
            id: "wbs-3-2-1",
            wbsCode: "3.2.1",
            name: "Transporter-Erector Umbilical Quick-Disconnect",
            level: "work-package",
            lead: LEADS.rafael,
            milestone: "ITR-2",
            targetDate: "2026-12-29",
            budgetUsd: 3_700_000,
            actualUsd: 3_480_000,
            completion: 86,
            health: "on-track",
            notes:
              "T-0 pneumatic retraction arms cleared 180 ms pull-away requirement during wet-dress cryogenic ice buildup trials.",
          },
          {
            id: "wbs-3-2-2",
            wbsCode: "3.2.2",
            name: "Pad Flame Trench Water Deluge Suppression",
            level: "work-package",
            lead: LEADS.rafael,
            milestone: "ORR-1",
            targetDate: "2027-01-15",
            budgetUsd: 2_850_000,
            actualUsd: 2_590_000,
            completion: 79,
            health: "on-track",
            notes:
              "High-pressure stainless steel manifold flow test verified 140,000 L/min peak surge delivery within 1.2 seconds.",
          },
        ],
      },
    ],
  },
];

const EXTRA_WORK_PACKAGES: Array<{ parentId: string; node: WbsNode }> = [
  {
    parentId: "wbs-1-1",
    node: {
      id: "wbs-1-1-4",
      wbsCode: "1.1.4",
      name: "Thrust Vector Gimbal Hydraulic Servo",
      level: "work-package",
      lead: LEADS.marcus,
      milestone: "QTR-4",
      targetDate: "2027-01-12",
      budgetUsd: 1_850_000,
      actualUsd: 1_620_000,
      completion: 74,
      health: "on-track",
      notes:
        "Dual-channel electromechanical gimbal actuators tracking ±8° slew rates under simulated ascent aerodynamic loads.",
    },
  },
  {
    parentId: "wbs-2-1",
    node: {
      id: "wbs-2-1-4",
      wbsCode: "2.1.4",
      name: "Star Tracker Optical Baffle Calibration",
      level: "work-package",
      lead: LEADS.david,
      milestone: "CDR-7",
      targetDate: "2027-01-19",
      budgetUsd: 1_450_000,
      actualUsd: 1_310_000,
      completion: 68,
      health: "on-track",
      notes:
        "Stray-light rejection testing down to 22° solar exclusion angle for upper-stage orbital insertion attitude hold.",
    },
  },
  {
    parentId: "wbs-3-2",
    node: {
      id: "wbs-3-2-3",
      wbsCode: "3.2.3",
      name: "Subcooled LOX Farm Chilldown Manifold",
      level: "work-package",
      lead: LEADS.rafael,
      milestone: "ORR-2",
      targetDate: "2027-01-25",
      budgetUsd: 2_100_000,
      actualUsd: 2_180_000,
      completion: 62,
      health: "at-risk",
      notes:
        "Vacuum-jacketed transfer line check-valve replacement scheduled ahead of integrated wet-dress rehearsal.",
    },
  },
];

const DEFAULT_EXPANDED_IDS = ["wbs-1", "wbs-1-1", "wbs-2"];

const currencyCompactFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 2,
  minimumFractionDigits: 2,
});

const currencyWholeFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
});

const dateFormatter = new Intl.DateTimeFormat("en-US", {
  month: "short",
  day: "numeric",
  year: "numeric",
  timeZone: "UTC",
});

function formatUsdMillions(amountUsd: number): string {
  const abs = Math.abs(amountUsd);
  if (abs >= 1_000_000) {
    const sign = amountUsd < 0 ? "-" : "";
    return `${sign}${currencyCompactFormatter.format(abs / 1_000_000)}M`;
  }
  if (abs >= 1_000) {
    const sign = amountUsd < 0 ? "-" : "";
    return `${sign}$${(abs / 1_000).toFixed(0)}K`;
  }
  return currencyWholeFormatter.format(amountUsd);
}

function formatVariancePct(variancePct: number): string {
  const rounded = Math.round(variancePct * 10) / 10;
  if (Math.abs(rounded) < 0.05) return "0.0%";
  return `${rounded > 0 ? "+" : ""}${rounded.toFixed(1)}%`;
}

function formatIsoDate(isoDate: string): string {
  const [year, month, day] = isoDate.split("-").map(Number);
  if (!year || !month || !day) return isoDate;
  return dateFormatter.format(new Date(Date.UTC(year, month - 1, day)));
}

function deriveParentHealth(children: ComputedWbsNode[]): WbsHealth {
  if (children.length === 0) return "on-track";
  if (children.every((child) => child.health === "complete")) return "complete";
  if (children.some((child) => child.health === "over-budget")) return "over-budget";
  if (children.some((child) => child.health === "at-risk")) return "at-risk";
  return "on-track";
}

/**
 * Bottom-up rollup pass: parent divisions and subsystems derive budget, actual
 * spend, variance %, budget-weighted completion, and rolled-up health directly
 * from their surviving descendants.
 */
function computeRollups(nodes: WbsNode[]): ComputedWbsNode[] {
  return nodes.map((node) => {
    if (!node.children || node.children.length === 0) {
      const budgetUsd = node.budgetUsd ?? 0;
      const actualUsd = node.actualUsd ?? 0;
      const variancePct = budgetUsd > 0 ? ((actualUsd - budgetUsd) / budgetUsd) * 100 : 0;
      return {
        id: node.id,
        wbsCode: node.wbsCode,
        name: node.name,
        level: node.level,
        lead: node.lead,
        milestone: node.milestone,
        targetDate: node.targetDate,
        notes: node.notes,
        budgetUsd,
        actualUsd,
        variancePct,
        completion: node.completion ?? 0,
        health: node.health ?? "on-track",
        leafCount: 1,
        directChildCount: 0,
        leafIds: [node.id],
      };
    }

    const children = computeRollups(node.children);
    const budgetUsd = children.reduce((sum, child) => sum + child.budgetUsd, 0);
    const actualUsd = children.reduce((sum, child) => sum + child.actualUsd, 0);
    const variancePct = budgetUsd > 0 ? ((actualUsd - budgetUsd) / budgetUsd) * 100 : 0;
    const weightedSum = children.reduce(
      (sum, child) => sum + child.completion * Math.max(child.budgetUsd, 1),
      0,
    );
    const totalWeight = children.reduce((sum, child) => sum + Math.max(child.budgetUsd, 1), 0);
    const completion = totalWeight > 0 ? Math.round(weightedSum / totalWeight) : 0;
    const health = deriveParentHealth(children);
    const leafCount = children.reduce((sum, child) => sum + child.leafCount, 0);
    const leafIds = children.flatMap((child) => child.leafIds);

    return {
      id: node.id,
      wbsCode: node.wbsCode,
      name: node.name,
      level: node.level,
      lead: node.lead,
      milestone: node.milestone,
      targetDate: node.targetDate,
      notes: node.notes,
      budgetUsd,
      actualUsd,
      variancePct,
      completion,
      health,
      leafCount,
      directChildCount: children.length,
      leafIds,
      children,
    };
  });
}

function matchesSearch(node: WbsNode, needle: string): boolean {
  if (!needle) return true;
  return (
    node.wbsCode.toLowerCase().includes(needle) ||
    node.name.toLowerCase().includes(needle) ||
    node.lead.name.toLowerCase().includes(needle) ||
    node.milestone.toLowerCase().includes(needle) ||
    node.notes.toLowerCase().includes(needle)
  );
}

/**
 * Prunes the tree for search query and/or health status while preserving
 * matching ancestor chains. When a parent itself matches the search query (and
 * no health filter narrows its leaves), its entire subtree survives.
 */
function pruneWbsTree(
  nodes: WbsNode[],
  needle: string,
  healthFilter: HealthFilter,
): WbsNode[] {
  const result: WbsNode[] = [];

  for (const node of nodes) {
    const isLeaf = !node.children || node.children.length === 0;
    const selfQueryMatch = matchesSearch(node, needle);

    if (isLeaf) {
      const healthMatch = healthFilter === "all" || node.health === healthFilter;
      if (selfQueryMatch && healthMatch) {
        result.push(node);
      }
      continue;
    }

    const prunedChildren = pruneWbsTree(node.children ?? [], needle, healthFilter);

    if (needle.length > 0 && selfQueryMatch && healthFilter === "all") {
      // Parent itself matched the search query: keep full subtree when no leaf health filter is active.
      result.push(node);
    } else if (needle.length > 0 && selfQueryMatch && healthFilter !== "all") {
      // Parent matched text, but health filter still restricts leaves beneath it.
      const healthFilteredChildren = pruneWbsTree(node.children ?? [], "", healthFilter);
      if (healthFilteredChildren.length > 0) {
        result.push({ ...node, children: healthFilteredChildren });
      }
    } else if (prunedChildren.length > 0) {
      result.push({ ...node, children: prunedChildren });
    }
  }

  return result;
}

function compareWbsNodes(a: ComputedWbsNode, b: ComputedWbsNode, key: SortKey): number {
  switch (key) {
    case "wbs":
      return a.wbsCode.localeCompare(b.wbsCode, undefined, { numeric: true });
    case "budgetUsd":
      return a.budgetUsd - b.budgetUsd;
    case "actualUsd":
      return a.actualUsd - b.actualUsd;
    case "variancePct":
      return a.variancePct - b.variancePct;
    case "completion":
      return a.completion - b.completion;
    case "health":
      return (
        HEALTH_SEVERITY[a.health] - HEALTH_SEVERITY[b.health] ||
        b.variancePct - a.variancePct
      );
  }
}

/** Recursively sorts each sibling group in place so hierarchy is never broken. */
function sortWbsTree(
  nodes: ComputedWbsNode[],
  sortKey: SortKey,
  sortDirection: SortDirection,
): ComputedWbsNode[] {
  const factor = sortDirection === "asc" ? 1 : -1;
  return [...nodes]
    .sort((a, b) => {
      const delta = compareWbsNodes(a, b, sortKey) * factor;
      return delta !== 0 ? delta : a.wbsCode.localeCompare(b.wbsCode, undefined, { numeric: true });
    })
    .map((node) =>
      node.children && node.children.length > 0
        ? { ...node, children: sortWbsTree(node.children, sortKey, sortDirection) }
        : node,
    );
}

function collectBranchIds(nodes: ReadonlyArray<{ id: string; children?: ReadonlyArray<{ id: string; children?: unknown[] }> }>, maxDepth?: number): Set<string> {
  const ids = new Set<string>();
  function walk(list: ReadonlyArray<{ id: string; children?: ReadonlyArray<unknown> }>, depth: number) {
    for (const item of list) {
      if (item.children && item.children.length > 0) {
        if (maxDepth === undefined || depth < maxDepth) {
          ids.add(item.id);
        }
        walk(
          item.children as ReadonlyArray<{ id: string; children?: ReadonlyArray<unknown> }>,
          depth + 1,
        );
      }
    }
  }
  walk(nodes, 0);
  return ids;
}

function setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
  if (a.size !== b.size) return false;
  for (const value of a) {
    if (!b.has(value)) return false;
  }
  return true;
}

function flattenVisibleTree(
  nodes: ComputedWbsNode[],
  expandedIds: ReadonlySet<string>,
): VisibleTreeRow[] {
  const rows: VisibleTreeRow[] = [];

  function walk(
    list: ComputedWbsNode[],
    depth: 0 | 1 | 2,
    parentId: string | null,
    ancestorPath: WbsCrumb[],
    guideMask: boolean[],
  ) {
    const setSize = list.length;
    list.forEach((node, index) => {
      const isLastSibling = index === setSize - 1;
      const hasChildren = Boolean(node.children && node.children.length > 0);
      const isExpanded = hasChildren && expandedIds.has(node.id);
      const nextPath: WbsCrumb[] = [
        ...ancestorPath,
        { id: node.id, wbsCode: node.wbsCode, name: node.name },
      ];

      rows.push({
        node,
        depth,
        parentId,
        ancestorPath: nextPath,
        guideMask,
        isLastSibling,
        posInSet: index + 1,
        setSize,
        hasChildren,
        isExpanded,
      });

      if (hasChildren && isExpanded && node.children) {
        const nextDepth = Math.min(depth + 1, 2) as 0 | 1 | 2;
        const nextMask = depth === 0 ? [] : [...guideMask, !isLastSibling];
        walk(node.children, nextDepth, node.id, nextPath, nextMask);
      }
    });
  }

  walk(nodes, 0, null, [], []);
  return rows;
}

function findNodeWithPath(
  nodes: ComputedWbsNode[],
  targetId: string,
  trail: WbsCrumb[] = [],
): { node: ComputedWbsNode; path: WbsCrumb[] } | null {
  for (const node of nodes) {
    const nextTrail = [...trail, { id: node.id, wbsCode: node.wbsCode, name: node.name }];
    if (node.id === targetId) {
      return { node, path: nextTrail };
    }
    if (node.children) {
      const found = findNodeWithPath(node.children, targetId, nextTrail);
      if (found) return found;
    }
  }
  return null;
}

function updateLeafNodes(
  nodes: WbsNode[],
  targetLeafIds: ReadonlySet<string>,
  updater: (leaf: WbsNode) => WbsNode,
): WbsNode[] {
  return nodes.map((node) => {
    if (!node.children || node.children.length === 0) {
      return targetLeafIds.has(node.id) ? updater(node) : node;
    }
    return {
      ...node,
      children: updateLeafNodes(node.children, targetLeafIds, updater),
    };
  });
}

function appendChildNode(nodes: WbsNode[], parentId: string, child: WbsNode): WbsNode[] {
  return nodes.map((node) => {
    if (node.id === parentId) {
      return {
        ...node,
        children: [...(node.children ?? []), child],
      };
    }
    if (node.children && node.children.length > 0) {
      return {
        ...node,
        children: appendChildNode(node.children, parentId, child),
      };
    }
    return node;
  });
}

function countAllNodes(nodes: ReadonlyArray<{ children?: ReadonlyArray<unknown> }>): number {
  let count = 0;
  for (const node of nodes) {
    count += 1;
    if (node.children) {
      count += countAllNodes(node.children as ReadonlyArray<{ children?: ReadonlyArray<unknown> }>);
    }
  }
  return count;
}

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "tree-table",
    containerType: "inline-size",
    fontFamily: fonts.body,
    minHeight: "100%",
    paddingBlock: {
      default: spacing._8,
      [NARROW_CONTAINER]: spacing._5,
    },
    paddingInline: {
      default: spacing._6,
      [NARROW_CONTAINER]: spacing._4,
    },
    width: "100%",
  },
  container: {
    marginInline: "auto",
    maxWidth: "78rem",
    width: "100%",
  },
  heading: {
    marginBlock: 0,
  },
  subtitleMaxWidth: {
    maxWidth: "60ch",
  },
  fullWidth: {
    width: "100%",
  },
  flexGrow: {
    flexGrow: 1,
  },
  noShrink: {
    flexShrink: 0,
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  summaryGrid: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    display: "grid",
    gap: spacing._4,
    gridTemplateColumns: {
      default: "repeat(5, minmax(0, 1fr))",
      [COMPACT_CONTAINER]: "repeat(3, minmax(0, 1fr))",
      [NARROW_CONTAINER]: "repeat(2, minmax(0, 1fr))",
    },
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  summaryValue: {
    color: semanticColors.fg,
    fontSize: fontSizes.md,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.semibold,
    lineHeight: lineHeights.md,
  },
  summaryValuePositive: {
    color: semanticColors.fgSuccess,
  },
  summaryValueWarning: {
    color: semanticColors.fgWarning,
  },
  summaryValueDanger: {
    color: semanticColors.fgError,
  },
  summaryProgressBar: {
    flexGrow: 1,
    maxWidth: "6rem",
    minWidth: "3.5rem",
  },
  toolbarEnd: {
    flexGrow: 1,
    justifyContent: {
      default: "flex-end",
      [COMPACT_CONTAINER]: "flex-start",
    },
  },
  healthSelect: {
    minWidth: "10.25rem",
    width: "auto",
  },
  searchWrap: {
    flexGrow: {
      default: 0,
      [NARROW_CONTAINER]: 1,
    },
    minWidth: "14rem",
    position: "relative",
    width: {
      default: "17.5rem",
      [NARROW_CONTAINER]: "100%",
    },
  },
  searchIcon: {
    color: semanticColors.fgSubtle,
    insetInlineStart: spacing._2_5,
    pointerEvents: "none",
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineEnd: spacing._8,
    paddingInlineStart: spacing._8,
  },
  searchClearBtn: {
    color: semanticColors.fgMuted,
    insetInlineEnd: spacing._1,
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
  },
  tableCard: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    boxShadow: semanticShadows.xs,
    overflow: "hidden",
  },
  tableMetaBar: {
    backgroundColor: semanticColors.bgSubtle,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._2,
    paddingInline: spacing._4,
  },
  tableMetaHints: {
    color: semanticColors.fgSubtle,
    display: {
      default: "flex",
      [NARROW_CONTAINER]: "none",
    },
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
  kbdChip: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fgMuted,
    fontFamily: fonts.mono,
    fontSize: "0.6875rem",
    paddingBlock: "0.0625rem",
    paddingInline: spacing._1_5,
  },
  tableScroll: {
    overflowX: "auto",
    width: "100%",
  },
  tableHeaderRow: {
    backgroundColor: semanticColors.bgMuted,
  },
  tableHeaderCell: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.semibold,
    letterSpacing: "0.01em",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    whiteSpace: "nowrap",
  },
  checkboxCol: {
    paddingInlineEnd: spacing._1,
    paddingInlineStart: spacing._4,
    width: "2.75rem",
  },
  wbsCol: {
    minWidth: "22rem",
  },
  leadCol: {
    minWidth: "10.5rem",
  },
  numberCol: {
    minWidth: "6.5rem",
    textAlign: "end",
  },
  progressCol: {
    minWidth: "9.5rem",
  },
  healthCol: {
    minWidth: "7.75rem",
  },
  actionsCol: {
    paddingInlineEnd: spacing._3,
    paddingInlineStart: spacing._1,
    textAlign: "end",
    width: "2.75rem",
  },
  sortButton: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: "inherit",
    fontSize: "inherit",
    fontWeight: "inherit",
    gap: spacing._1,
    paddingBlock: 0,
    paddingInline: 0,
  },
  sortButtonActive: {
    color: semanticColors.fg,
  },
  sortButtonEnd: {
    justifyContent: "flex-end",
    width: "100%",
  },
  sortIconMuted: {
    opacity: 0.45,
  },
  bodyRow: {
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    outlineColor: {
      default: "transparent",
      ":focus-visible": semanticColors.accentFocusRing,
    },
    outlineOffset: "-2px",
    outlineStyle: {
      default: "none",
      ":focus-visible": "solid",
    },
    outlineWidth: {
      default: 0,
      ":focus-visible": "2px",
    },
    transitionDuration: durations.fast,
    transitionProperty: "background-color",
  },
  bodyRowDivision: {
    backgroundColor: {
      default: semanticColors.bgMuted,
      ":hover": semanticColors.bgSubtle,
    },
  },
  bodyRowSelected: {
    backgroundColor: {
      default: semanticColors.interactionSelected,
      ":hover": semanticColors.interactionSelected,
    },
  },
  bodyCell: {
    borderBottomColor: semanticColors.borderMuted,
    borderBottomStyle: "solid",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    verticalAlign: "middle",
  },
  bodyCellTree: {
    borderBottomColor: semanticColors.borderMuted,
    borderBottomStyle: "solid",
    paddingBlock: 0,
    paddingInlineEnd: spacing._3,
    paddingInlineStart: spacing._2,
    verticalAlign: "middle",
  },
  treeCellInner: {
    minHeight: "3rem",
  },
  guideTrack: {
    alignSelf: "stretch",
    flexShrink: 0,
    position: "relative",
    width: "1.5rem",
  },
  guideLineFull: {
    borderInlineStartColor: semanticColors.border,
    borderInlineStartStyle: "solid",
    borderInlineStartWidth: "1px",
    bottom: 0,
    insetInlineStart: "0.75rem",
    position: "absolute",
    top: 0,
  },
  guideLineHalfTop: {
    borderInlineStartColor: semanticColors.border,
    borderInlineStartStyle: "solid",
    borderInlineStartWidth: "1px",
    bottom: "50%",
    insetInlineStart: "0.75rem",
    position: "absolute",
    top: 0,
  },
  guideElbow: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    insetInlineEnd: "0.125rem",
    insetInlineStart: "0.75rem",
    position: "absolute",
    top: "50%",
  },
  treeNodeMain: {
    flexGrow: 1,
    paddingBlock: spacing._2,
  },
  expandBtn: {
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
  },
  chevronIcon: {
    transitionDuration: durations.fast,
    transitionProperty: "transform",
  },
  chevronExpanded: {
    transform: "rotate(90deg)",
  },
  levelIconRadius: {
    borderRadius: semanticRadii.control,
  },
  levelIconDivision: {
    backgroundColor: semanticColors.accentSubtle,
    color: semanticColors.accentFg,
  },
  levelIconSubsystem: {
    backgroundColor: semanticColors.bgMuted,
    color: semanticColors.fgEmphasized,
  },
  levelIconLeaf: {
    backgroundColor: "transparent",
    color: semanticColors.fgMuted,
  },
  nodeNameBtn: {
    appearance: "none",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: {
      default: semanticColors.fg,
      ":hover": semanticColors.accentFg,
    },
    cursor: "pointer",
    fontFamily: "inherit",
    fontSize: fontSizes.sm,
    fontWeight: fontWeights.medium,
    lineHeight: lineHeights.sm,
    overflow: "hidden",
    paddingBlock: 0,
    paddingInline: 0,
    textAlign: "start",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
  nodeNameDivision: {
    fontWeight: fontWeights.semibold,
  },
  nodeNameLeaf: {
    fontWeight: fontWeights.normal,
  },
  nodeMetaRow: {
    color: semanticColors.fgSubtle,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
  numericPrimary: {
    color: semanticColors.fg,
    fontSize: fontSizes.sm,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.medium,
    lineHeight: lineHeights.sm,
    whiteSpace: "nowrap",
  },
  progressCell: {
    minWidth: "8.5rem",
  },
  progressTrackGrow: {
    flexGrow: 1,
    minWidth: "4.5rem",
  },
  progressPct: {
    minWidth: "2.25rem",
  },
  footerRow: {
    backgroundColor: semanticColors.bgMuted,
  },
  footerCell: {
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
    verticalAlign: "middle",
  },
  footerLabelWrap: {
    paddingInlineStart: spacing._1,
  },
  alertRow: {
    alignItems: "center",
  },
  actionBarContent: {
    alignItems: "center",
    display: "flex",
    flexWrap: "wrap",
    gap: spacing._1_5,
  },
  menuWidth: {
    minWidth: "11.5rem",
  },
  drawerHeaderInner: {
    paddingInlineEnd: spacing._8,
  },
  drawerBodyStack: {
    paddingBottom: spacing._4,
  },
  drawerLeadCard: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  drawerMetricsGrid: {
    display: "grid",
    gap: spacing._3,
    gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
  },
  drawerChildItem: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: semanticColors.bgMuted,
      ":hover": semanticColors.bgSubtle,
    },
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    fontFamily: "inherit",
    gap: spacing._3,
    justifyContent: "space-between",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    textAlign: "start",
    width: "100%",
  },
  breadcrumbBtn: {
    appearance: "none",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    fontFamily: "inherit",
    fontSize: "inherit",
    paddingBlock: 0,
    paddingInline: 0,
  },
});

function ChevronRightIcon({ expanded }: { expanded: boolean }) {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 16 16"
      fill="none"
      aria-hidden="true"
      {...stylex.props(styles.chevronIcon, expanded && styles.chevronExpanded)}
    >
      <path
        d="M6 3.5L10.5 8L6 12.5"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function DivisionIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M8 1.75L14 4.75L8 7.75L2 4.75L8 1.75Z"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinejoin="round"
      />
      <path
        d="M2 8L8 11L14 8"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M2 11.25L8 14.25L14 11.25"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SubsystemIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M8 2L13.25 5V11L8 14L2.75 11V5L8 2Z"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinejoin="round"
      />
      <path
        d="M8 8V14M8 8L13.25 5M8 8L2.75 5"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function PackageIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <rect
        x="2.75"
        y="2.25"
        width="10.5"
        height="11.5"
        rx="2"
        stroke="currentColor"
        strokeWidth="1.4"
      />
      <path
        d="M5.5 6H10.5M5.5 8.75H10.5M5.5 11.5H8.5"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
      />
    </svg>
  );
}

function SearchIcon({ style }: { style?: StyleOverrideProps["style"] }) {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 16 16"
      fill="none"
      aria-hidden="true"
      {...stylex.props(style)}
    >
      <circle cx="7.25" cy="7.25" r="4.75" stroke="currentColor" strokeWidth="1.5" />
      <path
        d="M10.8 10.8L13.75 13.75"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
      />
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      <path
        d="M2.75 2.75L9.25 9.25M9.25 2.75L2.75 9.25"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
      />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg width="10" height="10" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      <path
        d="M2.5 6.4L5 8.9L9.5 3.5"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function MinusIcon() {
  return (
    <svg width="10" height="10" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      <path d="M2.5 6H9.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

function SortIcon({
  active,
  direction,
}: {
  active: boolean;
  direction: SortDirection;
}) {
  if (!active) {
    return (
      <svg
        width="12"
        height="12"
        viewBox="0 0 12 12"
        fill="none"
        aria-hidden="true"
        {...stylex.props(styles.sortIconMuted)}
      >
        <path
          d="M4 4.5L6 2.5L8 4.5M4 7.5L6 9.5L8 7.5"
          stroke="currentColor"
          strokeWidth="1.3"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    );
  }
  return (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      {direction === "asc" ? (
        <path
          d="M3.5 7.5L6 4.5L8.5 7.5"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      ) : (
        <path
          d="M3.5 4.5L6 7.5L8.5 4.5"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      )}
    </svg>
  );
}

function PlusIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M8 3.25V12.75M3.25 8H12.75"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
      />
    </svg>
  );
}

function DownloadIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M8 2.5V10.25M8 10.25L5 7.25M8 10.25L11 7.25M2.75 12.75H13.25"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function ExpandAllIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M5 6L8 3L11 6M5 10L8 13L11 10"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function CollapseAllIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M5 3.5L8 6.5L11 3.5M5 12.5L8 9.5L11 12.5"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function MoreIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <circle cx="3.5" cy="8" r="1.25" fill="currentColor" />
      <circle cx="8" cy="8" r="1.25" fill="currentColor" />
      <circle cx="12.5" cy="8" r="1.25" fill="currentColor" />
    </svg>
  );
}

function WarningIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M8 2.25L14.25 13H1.75L8 2.25Z"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinejoin="round"
      />
      <path
        d="M8 6.25V9.25M8 11.25V11.35"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
      />
    </svg>
  );
}

export interface TreeTableProps extends StyleOverrideProps {
  /** Program title displayed in the masthead. */
  title?: string;
  /** Subtitle beneath the program heading. */
  subtitle?: string;
  /** Program identifier badge next to the heading. */
  programCode?: string;
  /** Initial hierarchical WBS dataset. */
  initialData?: WbsNode[];
}

export function TreeTable({
  title = "Helios-9 Program Work Breakdown",
  subtitle = "Hierarchical engineering cost rollup, weighted completion, and schedule health across divisions, subsystems, and work packages.",
  programCode = "HLS-WBS-26",
  initialData = DEFAULT_WBS_DATA,
  palette,
  style,
}: TreeTableProps) {
  const [queue] = useState(() => Toast.createToaster());
  const [treeData, setTreeData] = useState<WbsNode[]>(initialData);
  const [extraIndex, setExtraIndex] = useState(0);

  const [query, setQuery] = useState("");
  const [healthFilter, setHealthFilter] = useState<HealthFilter>("all");
  const [sortKey, setSortKey] = useState<SortKey>("wbs");
  const [sortDirection, setSortDirection] = useState<SortDirection>("asc");

  const [manualExpandedIds, setManualExpandedIds] = useState<Set<string>>(
    () => new Set(DEFAULT_EXPANDED_IDS),
  );
  /** Selection tracks leaf work-package IDs; parent checkboxes derive checked / indeterminate state. */
  const [selectedLeafIds, setSelectedLeafIds] = useState<Set<string>>(() => new Set());

  const [focusedRowId, setFocusedRowId] = useState<string | null>(null);
  const [inspectedNodeId, setInspectedNodeId] = useState<string | null>(null);

  const tableContainerRef = useRef<HTMLDivElement>(null);
  const shouldFocusRowRef = useRef(false);

  const needle = query.trim().toLowerCase();
  const isFiltered = needle.length > 0 || healthFilter !== "all";
  const activeFilterCount = (needle.length > 0 ? 1 : 0) + (healthFilter !== "all" ? 1 : 0);

  // Full unfiltered rollups (for totals comparison and branch ID sets)
  const fullRolledUp = useMemo(() => computeRollups(treeData), [treeData]);
  const totalLeafCount = useMemo(
    () => fullRolledUp.reduce((sum, div) => sum + div.leafCount, 0),
    [fullRolledUp],
  );
  const totalNodeCount = useMemo(() => countAllNodes(fullRolledUp), [fullRolledUp]);

  // Prune first, then re-roll so parent rows always agree with their visible descendants.
  const displayedTree = useMemo(() => {
    const pruned = isFiltered ? pruneWbsTree(treeData, needle, healthFilter) : treeData;
    const rolled = computeRollups(pruned);
    return sortWbsTree(rolled, sortKey, sortDirection);
  }, [treeData, isFiltered, needle, healthFilter, sortKey, sortDirection]);

  // While filtering/searching, auto-expand surviving branches without erasing manual state.
  const autoExpandedIds = useMemo(
    () => (isFiltered ? collectBranchIds(displayedTree) : null),
    [isFiltered, displayedTree],
  );
  const effectiveExpandedIds = autoExpandedIds ?? manualExpandedIds;

  const visibleRows = useMemo(
    () => flattenVisibleTree(displayedTree, effectiveExpandedIds),
    [displayedTree, effectiveExpandedIds],
  );

  // Branch sets for depth presets
  const depth1Ids = useMemo(() => new Set<string>(), []);
  const depth2Ids = useMemo(() => collectBranchIds(fullRolledUp, 1), [fullRolledUp]);
  const depth3Ids = useMemo(() => collectBranchIds(fullRolledUp), [fullRolledUp]);

  const activeDepthPreset = useMemo((): DepthPreset | null => {
    if (isFiltered) return "3";
    if (setsEqual(manualExpandedIds, depth1Ids)) return "1";
    if (setsEqual(manualExpandedIds, depth2Ids)) return "2";
    if (setsEqual(manualExpandedIds, depth3Ids)) return "3";
    return null;
  }, [isFiltered, manualExpandedIds, depth1Ids, depth2Ids, depth3Ids]);

  const allBranchesExpanded = useMemo(
    () => depth3Ids.size > 0 && setsEqual(effectiveExpandedIds, depth3Ids),
    [depth3Ids, effectiveExpandedIds],
  );

  // Program-level rollup totals derived from displayed divisions
  const programTotals = useMemo(() => {
    const budgetUsd = displayedTree.reduce((sum, node) => sum + node.budgetUsd, 0);
    const actualUsd = displayedTree.reduce((sum, node) => sum + node.actualUsd, 0);
    const variancePct = budgetUsd > 0 ? ((actualUsd - budgetUsd) / budgetUsd) * 100 : 0;
    const weightedSum = displayedTree.reduce(
      (sum, node) => sum + node.completion * Math.max(node.budgetUsd, 1),
      0,
    );
    const totalWeight = displayedTree.reduce((sum, node) => sum + Math.max(node.budgetUsd, 1), 0);
    const completion = totalWeight > 0 ? Math.round(weightedSum / totalWeight) : 0;
    const leafCount = displayedTree.reduce((sum, node) => sum + node.leafCount, 0);

    let attentionCount = 0;
    const countAttention = (list: ComputedWbsNode[]) => {
      for (const item of list) {
        if (!item.children || item.children.length === 0) {
          if (item.health === "at-risk" || item.health === "over-budget") {
            attentionCount += 1;
          }
        } else {
          countAttention(item.children);
        }
      }
    };
    countAttention(displayedTree);

    return {
      budgetUsd,
      actualUsd,
      variancePct,
      completion,
      leafCount,
      attentionCount,
    };
  }, [displayedTree]);

  // All visible leaf IDs (from displayedTree, including leaves under collapsed visible branches)
  const displayedLeafIds = useMemo(
    () => displayedTree.flatMap((div) => div.leafIds),
    [displayedTree],
  );

  const selectedDisplayedLeafCount = useMemo(
    () => displayedLeafIds.filter((id) => selectedLeafIds.has(id)).length,
    [displayedLeafIds, selectedLeafIds],
  );

  const allDisplayedSelected =
    displayedLeafIds.length > 0 && selectedDisplayedLeafCount === displayedLeafIds.length;
  const someDisplayedSelected =
    selectedDisplayedLeafCount > 0 && !allDisplayedSelected;

  // Compute rolled-up metrics for currently selected work packages (from fullRolledUp)
  const selectedLeafNodes = useMemo(() => {
    const leaves: ComputedWbsNode[] = [];
    const walk = (list: ComputedWbsNode[]) => {
      for (const item of list) {
        if (!item.children || item.children.length === 0) {
          if (selectedLeafIds.has(item.id)) {
            leaves.push(item);
          }
        } else {
          walk(item.children);
        }
      }
    };
    walk(fullRolledUp);
    return leaves;
  }, [fullRolledUp, selectedLeafIds]);

  const selectedSummary = useMemo(() => {
    const budgetUsd = selectedLeafNodes.reduce((sum, leaf) => sum + leaf.budgetUsd, 0);
    const actualUsd = selectedLeafNodes.reduce((sum, leaf) => sum + leaf.actualUsd, 0);
    return { budgetUsd, actualUsd };
  }, [selectedLeafNodes]);

  // Inspected node lookup (always resolves live computed rollups)
  const inspectedEntry = useMemo(() => {
    if (!inspectedNodeId) return null;
    return (
      findNodeWithPath(displayedTree, inspectedNodeId) ??
      findNodeWithPath(fullRolledUp, inspectedNodeId)
    );
  }, [displayedTree, fullRolledUp, inspectedNodeId]);

  const moveFocusToRow = useCallback((id: string) => {
    shouldFocusRowRef.current = true;
    setFocusedRowId(id);
  }, []);

  useEffect(() => {
    if (!shouldFocusRowRef.current || !focusedRowId) return;
    shouldFocusRowRef.current = false;
    tableContainerRef.current
      ?.querySelector<HTMLElement>(`tr[data-row-id="${CSS.escape(focusedRowId)}"]`)
      ?.focus();
  }, [focusedRowId, visibleRows]);

  const toggleExpand = useCallback(
    (id: string) => {
      if (isFiltered) return;
      setManualExpandedIds((prev) => {
        const next = new Set(prev);
        if (next.has(id)) {
          next.delete(id);
        } else {
          next.add(id);
        }
        return next;
      });
    },
    [isFiltered],
  );

  const setExpandedState = useCallback(
    (id: string, shouldExpand: boolean) => {
      if (isFiltered) return;
      setManualExpandedIds((prev) => {
        const next = new Set(prev);
        if (shouldExpand) {
          next.add(id);
        } else {
          next.delete(id);
        }
        return next;
      });
    },
    [isFiltered],
  );

  const applyDepthPreset = useCallback(
    (preset: DepthPreset) => {
      if (preset === "1") {
        setManualExpandedIds(new Set());
      } else if (preset === "2") {
        setManualExpandedIds(new Set(depth2Ids));
      } else {
        setManualExpandedIds(new Set(depth3Ids));
      }
    },
    [depth2Ids, depth3Ids],
  );

  const handleSort = useCallback(
    (key: SortKey) => {
      if (sortKey === key) {
        setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
      } else {
        setSortKey(key);
        setSortDirection(key === "wbs" ? "asc" : "desc");
      }
    },
    [sortKey],
  );

  const getNodeCheckState = useCallback(
    (node: ComputedWbsNode): boolean | "indeterminate" => {
      let selectedCount = 0;
      for (const leafId of node.leafIds) {
        if (selectedLeafIds.has(leafId)) selectedCount += 1;
      }
      if (selectedCount === 0) return false;
      if (selectedCount === node.leafIds.length) return true;
      return "indeterminate";
    },
    [selectedLeafIds],
  );

  const toggleNodeSelection = useCallback((node: ComputedWbsNode) => {
    setSelectedLeafIds((prev) => {
      const next = new Set(prev);
      const allChecked = node.leafIds.every((id) => next.has(id));
      if (allChecked) {
        for (const id of node.leafIds) next.delete(id);
      } else {
        for (const id of node.leafIds) next.add(id);
      }
      return next;
    });
  }, []);

  const toggleAllDisplayedSelection = useCallback(() => {
    setSelectedLeafIds((prev) => {
      const next = new Set(prev);
      if (allDisplayedSelected) {
        for (const id of displayedLeafIds) next.delete(id);
      } else {
        for (const id of displayedLeafIds) next.add(id);
      }
      return next;
    });
  }, [allDisplayedSelected, displayedLeafIds]);

  const clearSelection = useCallback(() => {
    setSelectedLeafIds(new Set());
  }, []);

  const clearAllFilters = useCallback(() => {
    setQuery("");
    setHealthFilter("all");
  }, []);

  const handleBulkHealthChange = useCallback(
    (targetIds: string[], nextHealth: WbsHealth) => {
      const idSet = new Set(targetIds);
      setTreeData((prev) =>
        updateLeafNodes(prev, idSet, (leaf) => ({
          ...leaf,
          health: nextHealth,
          completion: nextHealth === "complete" ? 100 : leaf.completion,
        })),
      );
      queue.success(
        `Updated ${targetIds.length} work ${targetIds.length === 1 ? "package" : "packages"}`,
        {
          description: `Status set to ${HEALTH_LABELS[nextHealth]} and parent rollups recalculated.`,
        },
      );
    },
    [queue],
  );

  const handleAdjustProgress = useCallback(
    (targetIds: string[], delta: number) => {
      const idSet = new Set(targetIds);
      setTreeData((prev) =>
        updateLeafNodes(prev, idSet, (leaf) => {
          const nextPct = Math.max(0, Math.min(100, (leaf.completion ?? 0) + delta));
          const nextHealth: WbsHealth =
            nextPct === 100
              ? "complete"
              : leaf.health === "complete"
                ? "on-track"
                : (leaf.health ?? "on-track");
          return {
            ...leaf,
            completion: nextPct,
            health: nextHealth,
          };
        }),
      );
      queue.info(
        `Adjusted completion by ${delta > 0 ? `+${delta}%` : `${delta}%`}`,
        {
          description: `Weighted completion rolled up across parent subsystems and divisions.`,
        },
      );
    },
    [queue],
  );

  const handleAddWorkPackage = useCallback(() => {
    const nextItem = EXTRA_WORK_PACKAGES[extraIndex % EXTRA_WORK_PACKAGES.length];
    if (!nextItem) return;
    const suffix = extraIndex >= EXTRA_WORK_PACKAGES.length ? `-${extraIndex + 1}` : "";
    const newNode: WbsNode = {
      ...nextItem.node,
      id: `${nextItem.node.id}${suffix}`,
      wbsCode:
        extraIndex >= EXTRA_WORK_PACKAGES.length
          ? `${nextItem.node.wbsCode}.${extraIndex + 1}`
          : nextItem.node.wbsCode,
    };

    setTreeData((prev) => appendChildNode(prev, nextItem.parentId, newNode));
    setExtraIndex((prev) => prev + 1);

    // Ensure the parent branch and division are expanded so the new row is immediately visible.
    const divisionId = nextItem.parentId.split("-").slice(0, 2).join("-");
    setManualExpandedIds((prev) => {
      const next = new Set(prev);
      next.add(divisionId);
      next.add(nextItem.parentId);
      return next;
    });

    queue.success(`Added ${newNode.wbsCode} ${newNode.name}`, {
      description: `Added ${formatUsdMillions(newNode.budgetUsd ?? 0)} to parent subsystem and division rollups.`,
    });
  }, [extraIndex, queue]);

  const handleExportCsv = useCallback(
    (label: string, count: number) => {
      queue.info(`Exported ${count} ${label} to CSV`, {
        description: `${programCode} cost rollup snapshot prepared for download.`,
      });
    },
    [programCode, queue],
  );

  // APG Treegrid keyboard navigation on the table body
  const handleTableKeyDown = useCallback(
    (event: React.KeyboardEvent<HTMLTableElement>) => {
      if (event.defaultPrevented || visibleRows.length === 0) return;
      const target = event.target as HTMLElement | null;
      if (target && ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)) return;

      const currentIndex = visibleRows.findIndex((row) => row.node.id === focusedRowId);
      const current = currentIndex >= 0 ? visibleRows[currentIndex] : undefined;

      let nextId: string | undefined;

      switch (event.key) {
        case "ArrowDown":
          nextId = visibleRows[currentIndex + 1]?.node.id ?? visibleRows[0]?.node.id;
          break;
        case "ArrowUp":
          nextId =
            currentIndex > 0
              ? visibleRows[currentIndex - 1]?.node.id
              : visibleRows[0]?.node.id;
          break;
        case "ArrowRight":
          if (!current) {
            nextId = visibleRows[0]?.node.id;
          } else if (current.hasChildren && !current.isExpanded) {
            setExpandedState(current.node.id, true);
          } else if (current.hasChildren && current.isExpanded) {
            nextId = visibleRows[currentIndex + 1]?.node.id;
          }
          break;
        case "ArrowLeft":
          if (!current) {
            nextId = visibleRows[0]?.node.id;
          } else if (current.hasChildren && current.isExpanded) {
            setExpandedState(current.node.id, false);
          } else if (current.parentId) {
            nextId = current.parentId;
          }
          break;
        case "Home":
          nextId = visibleRows[0]?.node.id;
          break;
        case "End":
          nextId = visibleRows[visibleRows.length - 1]?.node.id;
          break;
        case "Enter":
          if (current && target?.tagName === "TR") {
            event.preventDefault();
            setInspectedNodeId(current.node.id);
          }
          return;
        case " ":
          if (current && target?.tagName === "TR") {
            event.preventDefault();
            toggleNodeSelection(current.node);
          }
          return;
        default:
          return;
      }

      event.preventDefault();
      if (nextId && nextId !== focusedRowId) {
        moveFocusToRow(nextId);
      }
    },
    [visibleRows, focusedRowId, setExpandedState, moveFocusToRow, toggleNodeSelection],
  );

  const effectiveFocusedId =
    focusedRowId && visibleRows.some((row) => row.node.id === focusedRowId)
      ? focusedRowId
      : (visibleRows[0]?.node.id ?? null);

  return (
    <div {...stylex.props(palette, styles.root, style)}>
      <VStack gap="5" style={styles.container}>
        {/* Program masthead and live rollup summary strip */}
        <VStack render={<header />} gap="4">
          <HStack align="start" justify="between" wrap="wrap" gap="4">
            <VStack gap="1.5">
              <HStack wrap="wrap" gap="2.5">
                <Heading render={<h1 />} size="2xl" style={styles.heading}>
                  {title}
                </Heading>
                <Badge variant="subtle" size="sm" palette={accentPalette}>
                  {programCode}
                </Badge>
              </HStack>
              <Text size="sm" variant="muted" style={styles.subtitleMaxWidth}>
                {subtitle}
              </Text>
            </VStack>

            <HStack wrap="wrap" gap="2">
              <Button
                variant="surface"
                size="sm"
                onClick={() =>
                  handleExportCsv(
                    programTotals.leafCount === 1 ? "work package" : "work packages",
                    programTotals.leafCount,
                  )
                }
              >
                <DownloadIcon />
                Export CSV
              </Button>
              <Button
                variant="solid"
                size="sm"
                palette={accentPalette}
                onClick={handleAddWorkPackage}
              >
                <PlusIcon />
                New package
              </Button>
            </HStack>
          </HStack>

          <DataList.Root orientation="vertical" size="sm" style={styles.summaryGrid}>
            <DataList.Item>
              <DataList.ItemLabel>Program budget</DataList.ItemLabel>
              <DataList.ItemValue style={styles.summaryValue}>
                {formatUsdMillions(programTotals.budgetUsd)}
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Actual spend</DataList.ItemLabel>
              <DataList.ItemValue style={styles.summaryValue}>
                {formatUsdMillions(programTotals.actualUsd)}
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Cost variance</DataList.ItemLabel>
              <DataList.ItemValue
                style={[
                  styles.summaryValue,
                  programTotals.variancePct > 0.05
                    ? styles.summaryValueDanger
                    : programTotals.variancePct < -0.05
                      ? styles.summaryValuePositive
                      : undefined,
                ]}
              >
                {formatVariancePct(programTotals.variancePct)}
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Weighted completion</DataList.ItemLabel>
              <DataList.ItemValue>
                <HStack gap="2" style={styles.fullWidth}>
                  <Progress.Root
                    value={programTotals.completion}
                    max={100}
                    size="xs"
                    palette={accentPalette}
                    aria-label="Program weighted completion"
                    style={styles.summaryProgressBar}
                  >
                    <Progress.Track>
                      <Progress.Range />
                    </Progress.Track>
                  </Progress.Root>
                  <Text render={<span />} size="md" weight="semibold" tabular="true">
                    {programTotals.completion}%
                  </Text>
                </HStack>
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Attention needed</DataList.ItemLabel>
              <DataList.ItemValue
                style={[
                  styles.summaryValue,
                  programTotals.attentionCount > 0
                    ? styles.summaryValueWarning
                    : styles.summaryValuePositive,
                ]}
              >
                {programTotals.attentionCount}{" "}
                {programTotals.attentionCount === 1 ? "package" : "packages"}
              </DataList.ItemValue>
            </DataList.Item>
          </DataList.Root>
        </VStack>

        {/* Hierarchy depth controls, expand/collapse, health filter, and tree search */}
        <HStack
          render={<section aria-label="Hierarchy and filter controls" />}
          justify="between"
          wrap="wrap"
          gap="3"
        >
          <HStack wrap="wrap" gap="2">
            <SegmentGroup.Root
              size="sm"
              aria-label="Expand hierarchy to depth level"
              value={activeDepthPreset}
              onValueChange={(next) => {
                if (isFiltered) clearAllFilters();
                applyDepthPreset(next as DepthPreset);
              }}
            >
              {DEPTH_OPTIONS.map((option) => (
                <SegmentGroup.Item key={option.value} value={option.value}>
                  {option.label}
                </SegmentGroup.Item>
              ))}
            </SegmentGroup.Root>

            <Button
              variant="outline"
              size="sm"
              disabled={isFiltered}
              onClick={() => applyDepthPreset(allBranchesExpanded ? "1" : "3")}
            >
              {allBranchesExpanded ? <CollapseAllIcon /> : <ExpandAllIcon />}
              {allBranchesExpanded ? "Collapse all" : "Expand all"}
            </Button>
          </HStack>

          <HStack wrap="wrap" gap="2" style={styles.toolbarEnd}>
            <Select.Root
              size="sm"
              variant="outline"
              items={HEALTH_OPTIONS}
              value={healthFilter}
              onValueChange={(next) => setHealthFilter((next as HealthFilter) ?? "all")}
              style={styles.healthSelect}
            >
              <Select.Control>
                <Select.Trigger aria-label="Filter by health status">
                  <Select.Value placeholder="All health states" />
                </Select.Trigger>
                <Select.IndicatorGroup>
                  <Select.Icon />
                </Select.IndicatorGroup>
              </Select.Control>
              <Select.Content>
                {HEALTH_OPTIONS.map((option) => (
                  <Select.Item key={option.value} value={option.value}>
                    <Select.ItemText>{option.label}</Select.ItemText>
                    <Select.ItemIndicator />
                  </Select.Item>
                ))}
              </Select.Content>
            </Select.Root>

            <div {...stylex.props(styles.searchWrap)}>
              <SearchIcon style={styles.searchIcon} />
              <Input
                size="sm"
                variant="outline"
                type="search"
                aria-label="Search work breakdown nodes, WBS codes, or leads"
                placeholder="Search WBS, package, lead…"
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                style={styles.searchInput}
              />
              {query.length > 0 ? (
                <IconButton
                  type="button"
                  variant="ghost"
                  size="2xs"
                  aria-label="Clear search"
                  onClick={() => setQuery("")}
                  style={styles.searchClearBtn}
                >
                  <CloseIcon />
                </IconButton>
              ) : null}
            </div>

            {activeFilterCount > 0 ? (
              <Button variant="ghost" size="sm" onClick={clearAllFilters}>
                Reset
              </Button>
            ) : null}
          </HStack>
        </HStack>

        {/* Hierarchical Tree Table surface */}
        <VStack render={<section aria-label="Work breakdown tree table" />} gap="4">
          <div {...stylex.props(styles.tableCard)}>
            {visibleRows.length === 0 ? (
              <EmptyState.Root size="md" align="center">
                <EmptyState.Content>
                  <EmptyState.Indicator palette={grayPalette}>
                    <EmptyState.Icon
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.6"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      aria-hidden="true"
                    >
                      <circle cx="11" cy="11" r="7" />
                      <path d="m20 20-3.5-3.5M8.5 11h5" />
                    </EmptyState.Icon>
                  </EmptyState.Indicator>
                  <EmptyState.Title>No matching work packages</EmptyState.Title>
                  <EmptyState.Description>
                    No WBS divisions, subsystems, or work packages match your active search
                    and health filters.
                  </EmptyState.Description>
                  <EmptyState.Actions>
                    <Button variant="surface" size="sm" onClick={clearAllFilters}>
                      Clear filters
                    </Button>
                  </EmptyState.Actions>
                </EmptyState.Content>
              </EmptyState.Root>
            ) : (
              <>
                <HStack justify="between" wrap="wrap" gap="2" style={styles.tableMetaBar}>
                  <Text render={<span />} size="xs" variant="muted">
                    Showing {visibleRows.length} of {totalNodeCount} nodes ({programTotals.leafCount}{" "}
                    of {totalLeafCount} work packages rolled up)
                  </Text>
                  <HStack gap="2" style={styles.tableMetaHints} aria-hidden="true">
                    <span {...stylex.props(styles.kbdChip)}>↑↓</span>
                    <span>Navigate</span>
                    <span {...stylex.props(styles.kbdChip)}>←→</span>
                    <span>Expand / collapse</span>
                    <span {...stylex.props(styles.kbdChip)}>Enter</span>
                    <span>Inspect</span>
                  </HStack>
                </HStack>

                <div ref={tableContainerRef} {...stylex.props(styles.tableScroll)}>
                  <Table.Root
                    variant="line"
                    size="md"
                    role="treegrid"
                    aria-label="Helios-9 Program Work Breakdown Tree Table"
                    onKeyDown={handleTableKeyDown}
                  >
                    <Table.Header>
                      <Table.Row style={styles.tableHeaderRow}>
                        <Table.ColumnHeader
                          style={[styles.tableHeaderCell, styles.checkboxCol]}
                        >
                          <Checkbox.Root size="sm" palette={accentPalette}>
                            <Checkbox.Control
                              aria-label="Select all visible work packages"
                              checked={
                                allDisplayedSelected
                                  ? true
                                  : someDisplayedSelected
                                    ? "indeterminate"
                                    : false
                              }
                              onCheckedChange={toggleAllDisplayedSelection}
                            >
                              <Checkbox.Indicator>
                                {someDisplayedSelected ? <MinusIcon /> : <CheckIcon />}
                              </Checkbox.Indicator>
                            </Checkbox.Control>
                          </Checkbox.Root>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "wbs"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.wbsCol]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("wbs")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "wbs" && styles.sortButtonActive,
                            )}
                          >
                            <span>WBS / Work Package</span>
                            <SortIcon active={sortKey === "wbs"} direction={sortDirection} />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader style={[styles.tableHeaderCell, styles.leadCol]}>
                          Lead Engineer
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "budgetUsd"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.numberCol]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("budgetUsd")}
                            {...stylex.props(
                              styles.sortButton,
                              styles.sortButtonEnd,
                              sortKey === "budgetUsd" && styles.sortButtonActive,
                            )}
                          >
                            <span>Budget</span>
                            <SortIcon
                              active={sortKey === "budgetUsd"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "actualUsd"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.numberCol]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("actualUsd")}
                            {...stylex.props(
                              styles.sortButton,
                              styles.sortButtonEnd,
                              sortKey === "actualUsd" && styles.sortButtonActive,
                            )}
                          >
                            <span>Actual</span>
                            <SortIcon
                              active={sortKey === "actualUsd"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "variancePct"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.numberCol]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("variancePct")}
                            {...stylex.props(
                              styles.sortButton,
                              styles.sortButtonEnd,
                              sortKey === "variancePct" && styles.sortButtonActive,
                            )}
                          >
                            <span>Variance</span>
                            <SortIcon
                              active={sortKey === "variancePct"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "completion"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.progressCol]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("completion")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "completion" && styles.sortButtonActive,
                            )}
                          >
                            <span>Completion</span>
                            <SortIcon
                              active={sortKey === "completion"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "health"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.healthCol]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("health")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "health" && styles.sortButtonActive,
                            )}
                          >
                            <span>Health</span>
                            <SortIcon active={sortKey === "health"} direction={sortDirection} />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          style={[styles.tableHeaderCell, styles.actionsCol]}
                        >
                          <VisuallyHidden>Actions</VisuallyHidden>
                        </Table.ColumnHeader>
                      </Table.Row>
                    </Table.Header>

                    <Table.Body>
                      {visibleRows.map((row) => {
                        const { node, depth, hasChildren, isExpanded } = row;
                        const checkState = getNodeCheckState(node);
                        const isCheckedOrMixed = checkState !== false;
                        const isRowSelected = checkState === true;
                        const isDivision = depth === 0;
                        const isSubsystem = depth === 1;
                        const isFocused = node.id === effectiveFocusedId;

                        return (
                          <Table.Row
                            key={node.id}
                            data-row-id={node.id}
                            data-selected={isRowSelected ? "" : undefined}
                            tabIndex={isFocused ? 0 : -1}
                            aria-level={depth + 1}
                            aria-posinset={row.posInSet}
                            aria-setsize={row.setSize}
                            aria-expanded={hasChildren ? isExpanded : undefined}
                            aria-selected={isRowSelected}
                            onClick={() => setFocusedRowId(node.id)}
                            style={[
                              styles.bodyRow,
                              isDivision && styles.bodyRowDivision,
                              isRowSelected && styles.bodyRowSelected,
                            ]}
                          >
                            {/* Hierarchical indeterminate checkbox */}
                            <Table.Cell style={[styles.bodyCell, styles.checkboxCol]}>
                              <Checkbox.Root size="sm" palette={accentPalette}>
                                <Checkbox.Control
                                  aria-label={`Select ${node.wbsCode} ${node.name}`}
                                  checked={checkState}
                                  onCheckedChange={() => toggleNodeSelection(node)}
                                >
                                  <Checkbox.Indicator>
                                    {checkState === "indeterminate" ? (
                                      <MinusIcon />
                                    ) : (
                                      <CheckIcon />
                                    )}
                                  </Checkbox.Indicator>
                                </Checkbox.Control>
                              </Checkbox.Root>
                            </Table.Cell>

                            {/* Indented tree cell with guide lines, chevron, icon, WBS code & title */}
                            <Table.Cell style={[styles.bodyCellTree, styles.wbsCol]}>
                              <HStack align="stretch" gap="0" style={styles.treeCellInner}>
                                {/* Ancestor continuation tracks */}
                                {row.guideMask.map((hasContinuation, trackIdx) => (
                                  <span
                                    key={trackIdx}
                                    aria-hidden="true"
                                    {...stylex.props(styles.guideTrack)}
                                  >
                                    {hasContinuation ? (
                                      <span {...stylex.props(styles.guideLineFull)} />
                                    ) : null}
                                  </span>
                                ))}

                                {/* Branch connector for child depths */}
                                {depth > 0 ? (
                                  <span aria-hidden="true" {...stylex.props(styles.guideTrack)}>
                                    <span
                                      {...stylex.props(
                                        row.isLastSibling
                                          ? styles.guideLineHalfTop
                                          : styles.guideLineFull,
                                      )}
                                    />
                                    <span {...stylex.props(styles.guideElbow)} />
                                  </span>
                                ) : null}

                                <HStack gap="2" style={styles.treeNodeMain}>
                                  {hasChildren ? (
                                    <IconButton
                                      type="button"
                                      variant="ghost"
                                      size="2xs"
                                      aria-label={
                                        isExpanded
                                          ? `Collapse ${node.name}`
                                          : `Expand ${node.name}`
                                      }
                                      aria-expanded={isExpanded}
                                      disabled={isFiltered}
                                      onClick={(event) => {
                                        event.stopPropagation();
                                        toggleExpand(node.id);
                                      }}
                                      style={styles.expandBtn}
                                    >
                                      <ChevronRightIcon expanded={isExpanded} />
                                    </IconButton>
                                  ) : (
                                    <Square size="xs" render={<span />} aria-hidden="true" />
                                  )}

                                  <Square
                                    size="xs"
                                    render={<span />}
                                    aria-hidden="true"
                                    style={[
                                      styles.levelIconRadius,
                                      isDivision && styles.levelIconDivision,
                                      isSubsystem && styles.levelIconSubsystem,
                                      !hasChildren && styles.levelIconLeaf,
                                    ]}
                                  >
                                    {isDivision ? (
                                      <DivisionIcon />
                                    ) : isSubsystem ? (
                                      <SubsystemIcon />
                                    ) : (
                                      <PackageIcon />
                                    )}
                                  </Square>

                                  <VStack gap="0.5">
                                    <HStack gap="2">
                                      <Text
                                        render={<span />}
                                        variant="mono"
                                        size="xs"
                                        tone="subtle"
                                        weight="medium"
                                        style={styles.noShrink}
                                      >
                                        {node.wbsCode}
                                      </Text>
                                      <button
                                        type="button"
                                        onClick={(event) => {
                                          event.stopPropagation();
                                          setFocusedRowId(node.id);
                                          setInspectedNodeId(node.id);
                                        }}
                                        {...stylex.props(
                                          styles.nodeNameBtn,
                                          isDivision && styles.nodeNameDivision,
                                          !hasChildren && styles.nodeNameLeaf,
                                        )}
                                      >
                                        {node.name}
                                      </button>
                                    </HStack>
                                    <HStack gap="1.5" style={styles.nodeMetaRow}>
                                      {hasChildren ? (
                                        <>
                                          <span>
                                            {node.directChildCount}{" "}
                                            {isDivision
                                              ? node.directChildCount === 1
                                                ? "subsystem"
                                                : "subsystems"
                                              : node.directChildCount === 1
                                                ? "package"
                                                : "packages"}
                                          </span>
                                          {isDivision ? (
                                            <>
                                              <span aria-hidden="true">·</span>
                                              <span>{node.leafCount} pkgs rollup</span>
                                            </>
                                          ) : null}
                                        </>
                                      ) : (
                                        <>
                                          <span>{node.milestone}</span>
                                          <span aria-hidden="true">·</span>
                                          <span>Due {formatIsoDate(node.targetDate)}</span>
                                        </>
                                      )}
                                      {isCheckedOrMixed && hasChildren && !isRowSelected ? (
                                        <>
                                          <span aria-hidden="true">·</span>
                                          <span>Partial selection</span>
                                        </>
                                      ) : null}
                                    </HStack>
                                  </VStack>
                                </HStack>
                              </HStack>
                            </Table.Cell>

                            {/* Lead engineer */}
                            <Table.Cell style={[styles.bodyCell, styles.leadCol]}>
                              <HStack gap="2">
                                <Avatar.Root
                                  size="xs"
                                  variant="subtle"
                                  palette={LEAD_PALETTES[node.lead.tone]}
                                >
                                  <Avatar.Fallback>{node.lead.initials}</Avatar.Fallback>
                                </Avatar.Root>
                                <Text render={<span />} size="sm" truncate="true">
                                  {node.lead.name}
                                </Text>
                              </HStack>
                            </Table.Cell>

                            {/* Budget (rolled up on parents) */}
                            <Table.Cell style={[styles.bodyCell, styles.numberCol]}>
                              <Text
                                render={<span />}
                                size="sm"
                                weight={isDivision ? "semibold" : "medium"}
                                tabular="true"
                                style={styles.nowrap}
                              >
                                {formatUsdMillions(node.budgetUsd)}
                              </Text>
                            </Table.Cell>

                            {/* Actual spend (rolled up on parents) */}
                            <Table.Cell style={[styles.bodyCell, styles.numberCol]}>
                              <Text
                                render={<span />}
                                size="sm"
                                variant="muted"
                                weight={isDivision ? "semibold" : "inherit"}
                                tabular="true"
                                style={styles.nowrap}
                              >
                                {formatUsdMillions(node.actualUsd)}
                              </Text>
                            </Table.Cell>

                            {/* Cost variance % */}
                            <Table.Cell style={[styles.bodyCell, styles.numberCol]}>
                              <Text
                                render={<span />}
                                size="sm"
                                tabular="true"
                                tone={
                                  node.variancePct > 0.05
                                    ? "error"
                                    : node.variancePct < -0.05
                                      ? "success"
                                      : "muted"
                                }
                                weight={
                                  node.variancePct > 0.05
                                    ? "semibold"
                                    : node.variancePct < -0.05
                                      ? "medium"
                                      : "inherit"
                                }
                                style={styles.nowrap}
                              >
                                {formatVariancePct(node.variancePct)}
                              </Text>
                            </Table.Cell>

                            {/* Completion progress (weighted rollup on parents) */}
                            <Table.Cell style={[styles.bodyCell, styles.progressCol]}>
                              <HStack gap="2.5" style={styles.progressCell}>
                                <Progress.Root
                                  value={node.completion}
                                  max={100}
                                  size="xs"
                                  palette={HEALTH_PALETTES[node.health]}
                                  aria-label={`${node.name} completion ${node.completion}%`}
                                  style={styles.progressTrackGrow}
                                >
                                  <Progress.Track>
                                    <Progress.Range />
                                  </Progress.Track>
                                </Progress.Root>
                                <Text
                                  render={<span />}
                                  size="xs"
                                  variant="muted"
                                  weight="medium"
                                  tabular="true"
                                  align="end"
                                  style={styles.progressPct}
                                >
                                  {node.completion}%
                                </Text>
                              </HStack>
                            </Table.Cell>

                            {/* Health status */}
                            <Table.Cell style={[styles.bodyCell, styles.healthCol]}>
                              <Status.Root
                                size="sm"
                                palette={HEALTH_PALETTES[node.health]}
                              >
                                <Status.Indicator />
                                {HEALTH_LABELS[node.health]}
                              </Status.Root>
                            </Table.Cell>

                            {/* Row action menu */}
                            <Table.Cell style={[styles.bodyCell, styles.actionsCol]}>
                              <Menu.Root size="sm">
                                <Menu.Trigger
                                  render={
                                    <IconButton
                                      variant="ghost"
                                      size="xs"
                                      aria-label={`Actions for ${node.wbsCode} ${node.name}`}
                                    />
                                  }
                                >
                                  <MoreIcon />
                                </Menu.Trigger>
                                <Menu.Content align="end" style={styles.menuWidth}>
                                  <Menu.Item onSelect={() => setInspectedNodeId(node.id)}>
                                    <Menu.ItemText>Inspect details</Menu.ItemText>
                                  </Menu.Item>
                                  {hasChildren && !isFiltered ? (
                                    <Menu.Item onSelect={() => toggleExpand(node.id)}>
                                      <Menu.ItemText>
                                        {isExpanded ? "Collapse branch" : "Expand branch"}
                                      </Menu.ItemText>
                                    </Menu.Item>
                                  ) : null}
                                  <Menu.Separator />
                                  <Menu.Item
                                    onSelect={() => handleAdjustProgress(node.leafIds, 10)}
                                  >
                                    <Menu.ItemText>Advance progress +10%</Menu.ItemText>
                                  </Menu.Item>
                                  <Menu.Item
                                    onSelect={() =>
                                      handleBulkHealthChange(node.leafIds, "on-track")
                                    }
                                  >
                                    <Menu.ItemText>Mark on track</Menu.ItemText>
                                  </Menu.Item>
                                  <Menu.Item
                                    onSelect={() =>
                                      handleBulkHealthChange(node.leafIds, "at-risk")
                                    }
                                  >
                                    <Menu.ItemText>Flag at risk</Menu.ItemText>
                                  </Menu.Item>
                                </Menu.Content>
                              </Menu.Root>
                            </Table.Cell>
                          </Table.Row>
                        );
                      })}
                    </Table.Body>

                    <Table.Footer>
                      <Table.Row style={styles.footerRow}>
                        <Table.Cell style={[styles.footerCell, styles.checkboxCol]} />
                        <Table.Cell style={styles.footerCell}>
                          <HStack gap="2" style={styles.footerLabelWrap}>
                            <Text render={<span />} size="sm" weight="semibold">
                              Program Rollup Total
                            </Text>
                            <Text render={<span />} size="xs" variant="muted">
                              ({programTotals.leafCount}{" "}
                              {programTotals.leafCount === 1 ? "package" : "packages"})
                            </Text>
                          </HStack>
                        </Table.Cell>
                        <Table.Cell style={styles.footerCell} />
                        <Table.Cell style={[styles.footerCell, styles.numberCol]}>
                          <Text
                            render={<span />}
                            size="sm"
                            weight="semibold"
                            tabular="true"
                            style={styles.nowrap}
                          >
                            {formatUsdMillions(programTotals.budgetUsd)}
                          </Text>
                        </Table.Cell>
                        <Table.Cell style={[styles.footerCell, styles.numberCol]}>
                          <Text
                            render={<span />}
                            size="sm"
                            weight="semibold"
                            tabular="true"
                            style={styles.nowrap}
                          >
                            {formatUsdMillions(programTotals.actualUsd)}
                          </Text>
                        </Table.Cell>
                        <Table.Cell style={[styles.footerCell, styles.numberCol]}>
                          <Text
                            render={<span />}
                            size="sm"
                            tabular="true"
                            tone={
                              programTotals.variancePct > 0.05
                                ? "error"
                                : programTotals.variancePct < -0.05
                                  ? "success"
                                  : "muted"
                            }
                            weight={
                              programTotals.variancePct > 0.05
                                ? "semibold"
                                : programTotals.variancePct < -0.05
                                  ? "medium"
                                  : "inherit"
                            }
                            style={styles.nowrap}
                          >
                            {formatVariancePct(programTotals.variancePct)}
                          </Text>
                        </Table.Cell>
                        <Table.Cell style={[styles.footerCell, styles.progressCol]}>
                          <HStack gap="2.5" style={styles.progressCell}>
                            <Progress.Root
                              value={programTotals.completion}
                              max={100}
                              size="xs"
                              palette={accentPalette}
                              aria-label="Footer program completion"
                              style={styles.progressTrackGrow}
                            >
                              <Progress.Track>
                                <Progress.Range />
                              </Progress.Track>
                            </Progress.Root>
                            <Text
                              render={<span />}
                              size="xs"
                              variant="muted"
                              weight="medium"
                              tabular="true"
                              align="end"
                              style={styles.progressPct}
                            >
                              {programTotals.completion}%
                            </Text>
                          </HStack>
                        </Table.Cell>
                        <Table.Cell style={styles.footerCell} />
                        <Table.Cell style={[styles.footerCell, styles.actionsCol]} />
                      </Table.Row>
                    </Table.Footer>
                  </Table.Root>
                </div>
              </>
            )}
          </div>

          {/* Filtered rollup notice */}
          {visibleRows.length > 0 && isFiltered ? (
            <Alert.Root
              role="status"
              status="warning"
              variant="subtle"
              size="sm"
              palette={amberPalette}
              style={styles.alertRow}
            >
              <Alert.Indicator>
                <WarningIcon />
              </Alert.Indicator>
              <Alert.Content>
                <HStack justify="between" wrap="wrap" gap="3" style={styles.flexGrow}>
                  <VStack gap="0.5">
                    <Alert.Title>Filtered rollup scope active</Alert.Title>
                    <Alert.Description>
                      Parent division and subsystem figures have been recalculated from the{" "}
                      {programTotals.leafCount} matching work{" "}
                      {programTotals.leafCount === 1 ? "package" : "packages"} (out of{" "}
                      {totalLeafCount} total). Matching ancestor branches are auto-expanded.
                    </Alert.Description>
                  </VStack>
                  <Button variant="surface" size="xs" onClick={clearAllFilters}>
                    Clear filters
                  </Button>
                </HStack>
              </Alert.Content>
            </Alert.Root>
          ) : null}
        </VStack>
      </VStack>

      {/* Floating bulk ActionBar for selected work packages */}
      {selectedLeafNodes.length > 0 ? (
        <ActionBar.Positioner>
          <ActionBar.Content style={styles.actionBarContent}>
            <ActionBar.SelectionTrigger>
              <span>
                {selectedLeafNodes.length}{" "}
                {selectedLeafNodes.length === 1 ? "package" : "packages"}
              </span>
              <span aria-hidden="true">·</span>
              <Text render={<span />} size="xs" weight="semibold" tabular="true">
                {formatUsdMillions(selectedSummary.budgetUsd)}
              </Text>
            </ActionBar.SelectionTrigger>
            <ActionBar.Separator />
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                handleAdjustProgress(
                  selectedLeafNodes.map((leaf) => leaf.id),
                  10,
                )
              }
            >
              +10% progress
            </Button>
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                handleBulkHealthChange(
                  selectedLeafNodes.map((leaf) => leaf.id),
                  "on-track",
                )
              }
            >
              Mark on track
            </Button>
            <Button
              variant="ghost"
              size="xs"
              palette={amberPalette}
              onClick={() =>
                handleBulkHealthChange(
                  selectedLeafNodes.map((leaf) => leaf.id),
                  "at-risk",
                )
              }
            >
              Flag at risk
            </Button>
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                handleExportCsv(
                  selectedLeafNodes.length === 1
                    ? "selected package"
                    : "selected packages",
                  selectedLeafNodes.length,
                )
              }
            >
              Export CSV
            </Button>
            <ActionBar.Separator />
            <Button variant="ghost" size="xs" onClick={clearSelection}>
              Clear
            </Button>
          </ActionBar.Content>
        </ActionBar.Positioner>
      ) : null}

      {/* Node Inspector Drawer */}
      <Drawer.Root
        open={inspectedEntry !== null}
        onOpenChange={(open) => {
          if (!open) setInspectedNodeId(null);
        }}
        placement="end"
        size="sm"
      >
        <Drawer.Backdrop />
        <Drawer.Content>
          {inspectedEntry ? (
            <>
              <Drawer.Header>
                <VStack gap="2" style={styles.drawerHeaderInner}>
                  <Breadcrumb.Root size="sm" aria-label="WBS hierarchy path">
                    <Breadcrumb.List>
                      {inspectedEntry.path.map((crumb, index) => {
                        const isLast = index === inspectedEntry.path.length - 1;
                        return (
                          <Fragment key={crumb.id}>
                            <Breadcrumb.Item>
                              {isLast ? (
                                <Breadcrumb.CurrentLink aria-current="page">
                                  {crumb.wbsCode}
                                </Breadcrumb.CurrentLink>
                              ) : (
                                <button
                                  type="button"
                                  onClick={() => setInspectedNodeId(crumb.id)}
                                  {...stylex.props(styles.breadcrumbBtn)}
                                >
                                  {crumb.wbsCode} {crumb.name}
                                </button>
                              )}
                            </Breadcrumb.Item>
                            {!isLast ? (
                              <Breadcrumb.Separator aria-hidden="true">/</Breadcrumb.Separator>
                            ) : null}
                          </Fragment>
                        );
                      })}
                    </Breadcrumb.List>
                  </Breadcrumb.Root>

                  <HStack wrap="wrap" gap="2">
                    <Drawer.Title>{inspectedEntry.node.name}</Drawer.Title>
                    <Badge variant="subtle" size="sm" palette={grayPalette}>
                      {LEVEL_LABELS[inspectedEntry.node.level]}
                    </Badge>
                  </HStack>
                </VStack>
                <Drawer.Close
                  render={
                    <IconButton variant="ghost" size="xs" aria-label="Close inspector">
                      <CloseIcon />
                    </IconButton>
                  }
                />
              </Drawer.Header>

              <Drawer.Body>
                <VStack gap="5" style={styles.drawerBodyStack}>
                  <Text size="sm" variant="muted">
                    {inspectedEntry.node.notes}
                  </Text>

                  {/* Lead & Health card */}
                  <HStack justify="between" gap="3" style={styles.drawerLeadCard}>
                    <HStack gap="2.5">
                      <Avatar.Root
                        size="sm"
                        variant="subtle"
                        palette={LEAD_PALETTES[inspectedEntry.node.lead.tone]}
                      >
                        <Avatar.Fallback>{inspectedEntry.node.lead.initials}</Avatar.Fallback>
                      </Avatar.Root>
                      <VStack gap="0.5">
                        <Text render={<span />} size="sm" truncate="true">
                          {inspectedEntry.node.lead.name}
                        </Text>
                        <Text render={<span />} size="xs" variant="muted">
                          {inspectedEntry.node.lead.role}
                        </Text>
                      </VStack>
                    </HStack>
                    <Status.Root
                      size="sm"
                      palette={HEALTH_PALETTES[inspectedEntry.node.health]}
                    >
                      <Status.Indicator />
                      {HEALTH_LABELS[inspectedEntry.node.health]}
                    </Status.Root>
                  </HStack>

                  {/* Rolled-up or direct financial facts */}
                  <DataList.Root
                    orientation="vertical"
                    size="sm"
                    style={styles.drawerMetricsGrid}
                  >
                    <DataList.Item>
                      <DataList.ItemLabel>
                        {inspectedEntry.node.children ? "Rolled-up budget" : "Allocated budget"}
                      </DataList.ItemLabel>
                      <DataList.ItemValue style={styles.summaryValue}>
                        {formatUsdMillions(inspectedEntry.node.budgetUsd)}
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel>
                        {inspectedEntry.node.children ? "Rolled-up spend" : "Actual spend"}
                      </DataList.ItemLabel>
                      <DataList.ItemValue style={styles.summaryValue}>
                        {formatUsdMillions(inspectedEntry.node.actualUsd)}
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel>Cost variance</DataList.ItemLabel>
                      <DataList.ItemValue
                        style={[
                          styles.summaryValue,
                          inspectedEntry.node.variancePct > 0.05
                            ? styles.summaryValueDanger
                            : inspectedEntry.node.variancePct < -0.05
                              ? styles.summaryValuePositive
                              : undefined,
                        ]}
                      >
                        {formatVariancePct(inspectedEntry.node.variancePct)}
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel>Remaining margin</DataList.ItemLabel>
                      <DataList.ItemValue style={styles.summaryValue}>
                        {formatUsdMillions(
                          inspectedEntry.node.budgetUsd - inspectedEntry.node.actualUsd,
                        )}
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel>Gate milestone</DataList.ItemLabel>
                      <DataList.ItemValue style={styles.numericPrimary}>
                        {inspectedEntry.node.milestone}
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel>Target date</DataList.ItemLabel>
                      <DataList.ItemValue style={styles.numericPrimary}>
                        {formatIsoDate(inspectedEntry.node.targetDate)}
                      </DataList.ItemValue>
                    </DataList.Item>
                  </DataList.Root>

                  <Separator />

                  {/* Completion & live update controls */}
                  <VStack gap="2.5">
                    <HStack justify="between">
                      <Text render={<h3 />} variant="overline">
                        {inspectedEntry.node.children
                          ? "Weighted completion rollup"
                          : "Package completion"}
                      </Text>
                      <Text render={<span />} size="sm" weight="medium" tabular="true">
                        {inspectedEntry.node.completion}%
                      </Text>
                    </HStack>
                    <Progress.Root
                      value={inspectedEntry.node.completion}
                      max={100}
                      size="sm"
                      palette={HEALTH_PALETTES[inspectedEntry.node.health]}
                      aria-label="Inspected node completion"
                    >
                      <Progress.Track>
                        <Progress.Range />
                      </Progress.Track>
                    </Progress.Root>

                    <HStack wrap="wrap" gap="2">
                      <Button
                        variant="outline"
                        size="xs"
                        onClick={() => handleAdjustProgress(inspectedEntry.node.leafIds, -10)}
                      >
                        -10%
                      </Button>
                      <Button
                        variant="outline"
                        size="xs"
                        onClick={() => handleAdjustProgress(inspectedEntry.node.leafIds, 10)}
                      >
                        +10%
                      </Button>
                      <Button
                        variant="surface"
                        size="xs"
                        palette={greenPalette}
                        onClick={() =>
                          handleBulkHealthChange(inspectedEntry.node.leafIds, "on-track")
                        }
                      >
                        On track
                      </Button>
                      <Button
                        variant="surface"
                        size="xs"
                        palette={amberPalette}
                        onClick={() =>
                          handleBulkHealthChange(inspectedEntry.node.leafIds, "at-risk")
                        }
                      >
                        At risk
                      </Button>
                      <Button
                        variant="surface"
                        size="xs"
                        palette={bluePalette}
                        onClick={() =>
                          handleBulkHealthChange(inspectedEntry.node.leafIds, "complete")
                        }
                      >
                        Mark complete
                      </Button>
                    </HStack>
                  </VStack>

                  {/* Direct children drill-down for Divisions & Subsystems */}
                  {inspectedEntry.node.children && inspectedEntry.node.children.length > 0 ? (
                    <>
                      <Separator />
                      <VStack gap="2.5">
                        <Text render={<h3 />} variant="overline">
                          Direct children ({inspectedEntry.node.children.length})
                        </Text>
                        <VStack gap="2">
                          {inspectedEntry.node.children.map((child) => (
                            <button
                              key={child.id}
                              type="button"
                              onClick={() => setInspectedNodeId(child.id)}
                              {...stylex.props(styles.drawerChildItem)}
                            >
                              <VStack gap="0.5">
                                <Text render={<span />} size="sm" weight="medium" truncate="true">
                                  {child.wbsCode} · {child.name}
                                </Text>
                                <Text render={<span />} size="xs" variant="muted" tabular="true">
                                  {formatUsdMillions(child.actualUsd)} /{" "}
                                  {formatUsdMillions(child.budgetUsd)} ({child.completion}%)
                                </Text>
                              </VStack>
                              <HStack gap="2" style={styles.noShrink}>
                                <Badge
                                  variant="subtle"
                                  size="xs"
                                  palette={HEALTH_PALETTES[child.health]}
                                >
                                  {HEALTH_LABELS[child.health]}
                                </Badge>
                              </HStack>
                            </button>
                          ))}
                        </VStack>
                      </VStack>
                    </>
                  ) : null}
                </VStack>
              </Drawer.Body>

              <Drawer.Footer>
                <Button
                  variant="surface"
                  size="sm"
                  onClick={() => {
                    toggleNodeSelection(inspectedEntry.node);
                  }}
                >
                  {getNodeCheckState(inspectedEntry.node) === true
                    ? "Deselect branch"
                    : "Select branch"}
                </Button>
                <Button
                  variant="solid"
                  size="sm"
                  palette={accentPalette}
                  onClick={() => setInspectedNodeId(null)}
                >
                  Done
                </Button>
              </Drawer.Footer>
            </>
          ) : null}
        </Drawer.Content>
      </Drawer.Root>

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

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