---
title: "Collapsible Table · UI SDK — StyleX Blocks"
description: "Heterogeneous infrastructure spend and usage ledger organized into three collapsible schema-specific table cards (Compute & Inference Clusters, Storage & Data Lakes, Third-Party Integrations & APIs) with a shared global time-range selector, cross-section search, expand/collapse-all controls, per-section column sorting, and expandable rows revealing a TanStack Charts run-rate trajectory."
url: "https://stylexblocks.com/block/ui-sdk/collapsible-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/"
---

# Collapsible Table block

Heterogeneous infrastructure spend and usage ledger organized into three collapsible schema-specific table cards (Compute & Inference Clusters, Storage & Data Lakes, Third-Party Integrations & APIs) with a shared global time-range selector, cross-section search, expand/collapse-all controls, per-section column sorting, and expandable rows revealing a TanStack Charts run-rate trajectory.

- Behavior engine: UI SDK
- Category: [Data tables](https://stylexblocks.com/blocks/tables.md)
- Built with: [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Card](https://stylexblocks.com/components/ui-sdk/card.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Chart](https://stylexblocks.com/components/ui-sdk/chart.md), [Collapsible](https://stylexblocks.com/components/ui-sdk/collapsible.md), [Empty State](https://stylexblocks.com/components/ui-sdk/empty-state.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Progress](https://stylexblocks.com/components/ui-sdk/progress.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Stat](https://stylexblocks.com/components/ui-sdk/stat.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/collapsible-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 collapsible-table
```

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

## Usage

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

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

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, Fragment, useContext, useMemo, useState } from "react";
import { Badge } from "#components/ui/ui-sdk/badge.tsx";
import { Button } from "#components/ui/ui-sdk/button.tsx";
import { Card } from "#components/ui/ui-sdk/card.tsx";
import { Center } from "#components/ui/ui-sdk/center.tsx";
import { AreaChart } from "#components/ui/ui-sdk/chart.tsx";
import { Collapsible } from "#components/ui/ui-sdk/collapsible.tsx";
import { EmptyState } from "#components/ui/ui-sdk/empty-state.tsx";
import { Grid } from "#components/ui/ui-sdk/grid.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { Progress } from "#components/ui/ui-sdk/progress.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";
import { Separator } from "#components/ui/ui-sdk/separator.tsx";
import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Stat } from "#components/ui/ui-sdk/stat.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 type { StyleOverrideProps } from "#lib/recipe-props.ts";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import {
  amberPalette,
  bluePalette,
  grayPalette,
  greenPalette,
  indigoPalette,
  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 { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";

// ============= CONTAINER QUERIES =============

const NARROW = "@container collapsible-table (max-width: 920px)";
const COMPACT = "@container collapsible-table (max-width: 640px)";

// ============= SHARED TYPES & DATA =============

type GroupId = "compute" | "storage" | "integrations";
type RangeId = "7D" | "30D" | "90D" | "YTD" | "1Y";
type SortDirection = "asc" | "desc";

interface SortState<K extends string> {
  key: K;
  direction: SortDirection;
}

interface ResourceBase {
  id: string;
  name: string;
  subtitle: string;
  /** Integer cents representing current monthly run-rate spend. */
  monthlySpendCents: number;
  /** Daily fractional drift driving deterministic spend history. */
  drift: number;
  /** Resource owner / cost center shown in expanded detail panel. */
  owner: string;
  /** Highlight note shown in expanded detail panel. */
  detailLabel: string;
  detailValue: string;
}

export interface ComputeCluster extends ResourceBase {
  region: string;
  utilizationPct: number;
  capacityCount: number;
  capacityUnit: "GPUs" | "vCPUs";
}

export interface StorageLake extends ResourceBase {
  tier: "Hot NVMe" | "Standard" | "Infrequent" | "Cold Archive";
  storedTb: number;
  egressTb: number;
}

export type IntegrationHealth = "healthy" | "elevated" | "throttled";

export interface ThirdPartyIntegration extends ResourceBase {
  authScheme: string;
  quotaUsedPct: number;
  health: IntegrationHealth;
  requestsMillions: number;
  errorRatePct: number;
}

const GROUP_IDS: readonly GroupId[] = ["compute", "storage", "integrations"];
const RANGE_IDS: readonly RangeId[] = ["7D", "30D", "90D", "YTD", "1Y"];

const RANGE_DAYS: Record<RangeId, number> = {
  "7D": 7,
  "30D": 30,
  "90D": 90,
  YTD: 334,
  "1Y": 365,
};

/** Pinned UTC anchor so dates and deterministic curves never drift across renders. */
const ANCHOR_UTC = Date.UTC(2026, 10, 30);
const FULL_SERIES_DAYS = RANGE_DAYS["1Y"];

const COMPUTE_CLUSTERS: ComputeCluster[] = [
  {
    id: "cmp-1",
    name: "us-east-ml-01",
    subtitle: "8× H200 · SXM5 inference pool",
    region: "us-east-1",
    utilizationPct: 84,
    capacityCount: 64,
    capacityUnit: "GPUs",
    monthlySpendCents: 4_862_000,
    drift: 0.0014,
    owner: "Applied Inference",
    detailLabel: "Reserved Coverage",
    detailValue: "72% 1yr RI",
  },
  {
    id: "cmp-2",
    name: "eu-central-batch-04",
    subtitle: "c7i.16xlarge · Spot worker fleet",
    region: "eu-central-1",
    utilizationPct: 61,
    capacityCount: 512,
    capacityUnit: "vCPUs",
    monthlySpendCents: 1_489_000,
    drift: -0.0011,
    owner: "Data Platform",
    detailLabel: "Spot Mix",
    detailValue: "88% preemptible",
  },
  {
    id: "cmp-3",
    name: "us-west-realtime-02",
    subtitle: "4× L40S · TensorRT low-latency",
    region: "us-west-2",
    utilizationPct: 72,
    capacityCount: 32,
    capacityUnit: "GPUs",
    monthlySpendCents: 2_234_000,
    drift: 0.0006,
    owner: "Edge Serving",
    detailLabel: "Autoscaler Band",
    detailValue: "24 – 48 GPUs",
  },
  {
    id: "cmp-4",
    name: "ap-northeast-api-03",
    subtitle: "m7g.8xlarge · Graviton3 gateway",
    region: "ap-northeast-1",
    utilizationPct: 48,
    capacityCount: 256,
    capacityUnit: "vCPUs",
    monthlySpendCents: 948_000,
    drift: -0.0008,
    owner: "Core Runtime",
    detailLabel: "Savings Plan",
    detailValue: "100% covered",
  },
];

const STORAGE_LAKES: StorageLake[] = [
  {
    id: "stg-1",
    name: "telemetry-iceberg-prod",
    subtitle: "Apache Iceberg · Multi-AZ NVMe",
    tier: "Hot NVMe",
    storedTb: 418.4,
    egressTb: 64.2,
    monthlySpendCents: 1_894_000,
    drift: 0.0009,
    owner: "Observability",
    detailLabel: "Compression",
    detailValue: "4.6× Zstd-L6",
  },
  {
    id: "stg-2",
    name: "checkpoint-weights-s3",
    subtitle: "Object Store · Cross-region sync",
    tier: "Standard",
    storedTb: 1240.0,
    egressTb: 28.5,
    monthlySpendCents: 2_912_000,
    drift: 0.0004,
    owner: "Model Training",
    detailLabel: "Lifecycle Rule",
    detailValue: "Tier after 45d",
  },
  {
    id: "stg-3",
    name: "clickstream-parquet-eu",
    subtitle: "Columnar Lake · Partitioned daily",
    tier: "Infrequent",
    storedTb: 892.5,
    egressTb: 6.8,
    monthlySpendCents: 765_000,
    drift: -0.0013,
    owner: "Analytics",
    detailLabel: "Compaction",
    detailValue: "Nightly 256 MB",
  },
  {
    id: "stg-4",
    name: "audit-worm-vault",
    subtitle: "Immutable Archive · 7yr compliance",
    tier: "Cold Archive",
    storedTb: 2610.0,
    egressTb: 0.4,
    monthlySpendCents: 418_000,
    drift: 0.0001,
    owner: "Security & Trust",
    detailLabel: "Object Lock",
    detailValue: "WORM enforced",
  },
];

const INTEGRATIONS: ThirdPartyIntegration[] = [
  {
    id: "int-1",
    name: "Vektor Search API",
    subtitle: "Dedicated index · v3/hybrid-query",
    authScheme: "OAuth2",
    quotaUsedPct: 74,
    health: "healthy",
    requestsMillions: 142.8,
    errorRatePct: 0.04,
    monthlySpendCents: 1_245_000,
    drift: 0.0012,
    owner: "Discovery",
    detailLabel: "P95 Latency",
    detailValue: "38 ms",
  },
  {
    id: "int-2",
    name: "Kestrel Telemetry",
    subtitle: "Enterprise logs, traces & profiling",
    authScheme: "API Key",
    quotaUsedPct: 89,
    health: "elevated",
    requestsMillions: 91.2,
    errorRatePct: 0.19,
    monthlySpendCents: 1_680_000,
    drift: 0.0016,
    owner: "Site Reliability",
    detailLabel: "Ingest Cap",
    detailValue: "100M events/mo",
  },
  {
    id: "int-3",
    name: "Helios Geocoding",
    subtitle: "Edge routing · batch + live lookup",
    authScheme: "mTLS",
    quotaUsedPct: 41,
    health: "healthy",
    requestsMillions: 38.4,
    errorRatePct: 0.02,
    monthlySpendCents: 492_000,
    drift: -0.0009,
    owner: "Logistics",
    detailLabel: "Cache Hit Rate",
    detailValue: "93.4%",
  },
  {
    id: "int-4",
    name: "Solstice Webhook Relay",
    subtitle: "Signed fanout · automatic backoff",
    authScheme: "HMAC",
    quotaUsedPct: 96,
    health: "throttled",
    requestsMillions: 12.6,
    errorRatePct: 1.38,
    monthlySpendCents: 314_000,
    drift: -0.0005,
    owner: "Developer Platform",
    detailLabel: "Retry Queue",
    detailValue: "1,420 pending",
  },
];

const ALL_RESOURCES: readonly ResourceBase[] = [
  ...COMPUTE_CLUSTERS,
  ...STORAGE_LAKES,
  ...INTEGRATIONS,
];

const ALL_ROW_IDS = ALL_RESOURCES.map((item) => item.id);

// ============= DETERMINISTIC SPEND HISTORY =============

function seedFromId(id: string): number {
  let hash = 2166136261;
  for (let i = 0; i < id.length; i++) {
    hash ^= id.charCodeAt(i);
    hash = Math.imul(hash, 16777619);
  }
  return hash >>> 0;
}

function buildSpendHistory<T extends ResourceBase>(
  rows: readonly T[],
  volatility: number,
): Array<[string, number[]]> {
  return rows.map((row) => {
    let state = seedFromId(row.id) || 1;
    const nextNoise = () => {
      state ^= state << 13;
      state ^= state >>> 17;
      state ^= state << 5;
      return ((state >>> 0) % 10000) / 10000 - 0.5;
    };

    const points = new Array<number>(FULL_SERIES_DAYS);
    let value = row.monthlySpendCents;
    points[FULL_SERIES_DAYS - 1] = value;

    for (let day = FULL_SERIES_DAYS - 2; day >= 0; day--) {
      value /= 1 + row.drift + nextNoise() * volatility;
      points[day] = Math.max(10_000, Math.round(value));
    }

    return [row.id, points];
  });
}

const SPEND_HISTORY: Record<string, number[]> = Object.fromEntries([
  ...buildSpendHistory(COMPUTE_CLUSTERS, 0.022),
  ...buildSpendHistory(STORAGE_LAKES, 0.011),
  ...buildSpendHistory(INTEGRATIONS, 0.032),
]);

function historyWindowFor(id: string, range: RangeId): number[] {
  const full = SPEND_HISTORY[id] ?? [];
  return full.slice(-RANGE_DAYS[range]);
}

function trendPercentFor(id: string, range: RangeId): number {
  const window = historyWindowFor(id, range);
  if (window.length < 2 || window[0] === 0) return 0;
  return ((window[window.length - 1] - window[0]) / Math.abs(window[0])) * 100;
}

// ============= FORMATTERS =============

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

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

const oneDecimal = new Intl.NumberFormat("en-US", {
  minimumFractionDigits: 1,
  maximumFractionDigits: 1,
});

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

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

function formatCents(cents: number): string {
  return currencyExact.format(cents / 100);
}

function formatWholeDollars(dollars: number): string {
  return currencyWhole.format(dollars);
}

function dateLabelDaysAgo(daysAgo: number): string {
  const date = new Date(ANCHOR_UTC);
  date.setUTCDate(date.getUTCDate() - daysAgo);
  return dayFormatter.format(date);
}

function sumCents<T extends ResourceBase>(rows: readonly T[]): number {
  return rows.reduce((total, row) => total + row.monthlySpendCents, 0);
}

// ============= CONTEXT & PALETTE MAPS =============

const RangeContext = createContext<RangeId>("90D");
const useRange = () => useContext(RangeContext);

const TIER_PALETTES = {
  "Hot NVMe": indigoPalette,
  Standard: bluePalette,
  Infrequent: tealPalette,
  "Cold Archive": grayPalette,
} as const;

const TIER_ORDER: Record<StorageLake["tier"], number> = {
  "Hot NVMe": 0,
  Standard: 1,
  Infrequent: 2,
  "Cold Archive": 3,
};

const HEALTH_META: Record<
  IntegrationHealth,
  { label: string; palette: typeof greenPalette; rank: number }
> = {
  healthy: { label: "Healthy", palette: greenPalette, rank: 2 },
  elevated: { label: "Elevated", palette: amberPalette, rank: 1 },
  throttled: { label: "Throttled", palette: redPalette, rank: 0 },
};

const RANGE_LABELS: Record<RangeId, string> = {
  "7D": "7-day",
  "30D": "30-day",
  "90D": "90-day",
  YTD: "YTD",
  "1Y": "12-month",
};

// ============= INLINE SVG ICONS =============

function ChevronRightIcon({ rotated }: { rotated: boolean }) {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      {...stylex.props(styles.chevron, rotated && styles.chevronOpen)}
    >
      <polyline points="9 18 15 12 9 6" />
    </svg>
  );
}

function CpuIcon() {
  return (
    <svg
      width="15"
      height="15"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.9"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="6" y="6" width="12" height="12" rx="2" />
      <rect x="9" y="9" width="6" height="6" />
      <path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4" />
    </svg>
  );
}

function DatabaseIcon() {
  return (
    <svg
      width="15"
      height="15"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.9"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <ellipse cx="12" cy="5" rx="8" ry="3" />
      <path d="M4 5v14c0 1.66 3.58 3 8 3s8-1.34 8-3V5" />
      <path d="M4 12c0 1.66 3.58 3 8 3s8-1.34 8-3" />
    </svg>
  );
}

function PlugIcon() {
  return (
    <svg
      width="15"
      height="15"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.9"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M12 22v-5" />
      <path d="M9 8V2" />
      <path d="M15 8V2" />
      <path d="M18 8v5a6 6 0 0 1-12 0V8Z" />
    </svg>
  );
}

function SearchIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      {...stylex.props(styles.searchIcon)}
    >
      <circle cx="11" cy="11" r="7" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

function ClearIcon() {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <line x1="18" y1="6" x2="6" y2="18" />
      <line x1="6" y1="6" x2="18" y2="18" />
    </svg>
  );
}

function DownloadIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="7 10 12 15 17 10" />
      <line x1="12" y1="15" x2="12" y2="3" />
    </svg>
  );
}

function SortIcon({ direction }: { direction: SortDirection | null }) {
  if (direction === "asc") {
    return (
      <svg
        width="12"
        height="12"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2.2"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <path d="m18 15-6-6-6 6" />
      </svg>
    );
  }
  if (direction === "desc") {
    return (
      <svg
        width="12"
        height="12"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2.2"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    );
  }
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      {...stylex.props(styles.sortIconIdle)}
    >
      <path d="m7 15 5 5 5-5" />
      <path d="m7 9 5-5 5 5" />
    </svg>
  );
}

function EmptyLedgerIcon() {
  return (
    <svg
      width="28"
      height="28"
      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" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
      <line x1="8" y1="11" x2="14" y2="11" />
    </svg>
  );
}

// ============= STYLES =============

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "collapsible-table",
    containerType: "inline-size",
    fontFamily: fonts.body,
    minHeight: "100%",
    paddingBlock: {
      default: spacing._8,
      [COMPACT]: spacing._5,
    },
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
    width: "100%",
  },
  container: {
    marginInline: "auto",
    maxWidth: "74rem",
    width: "100%",
  },
  heading: {
    marginBlock: 0,
  },
  subtitleMaxWidth: {
    maxWidth: "60ch",
  },
  kpiGrid: {
    gridTemplateColumns: {
      default: "repeat(4, minmax(0, 1fr))",
      [NARROW]: "repeat(2, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
  },
  kpiCardBody: {
    gap: spacing._1,
  },
  tabular: {
    fontVariantNumeric: "tabular-nums",
  },
  searchWrap: {
    flexGrow: {
      default: 0,
      [COMPACT]: 1,
    },
    minWidth: "14rem",
    position: "relative",
    width: {
      default: "20rem",
      [COMPACT]: "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,
  },
  clearButton: {
    color: semanticColors.fgMuted,
    insetInlineEnd: spacing._1,
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
  },
  sectionCard: {
    overflowX: "hidden",
    overflowY: "hidden",
  },
  triggerButton: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    borderStyle: "none",
    borderWidth: 0,
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    flexWrap: "wrap",
    fontFamily: fonts.body,
    gap: spacing._3,
    justifyContent: "space-between",
    outlineColor: {
      default: "transparent",
      ":focus-visible": semanticColors.accentFocusRing,
    },
    outlineOffset: "-2px",
    outlineStyle: {
      default: "none",
      ":focus-visible": "solid",
    },
    outlineWidth: {
      default: 0,
      ":focus-visible": "2px",
    },
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
    textAlign: "start",
    transitionDuration: durations.fast,
    transitionProperty: "background-color",
    width: "100%",
  },
  iconTile: {
    borderRadius: semanticRadii.control,
    flexShrink: 0,
    height: "1.75rem",
    width: "1.75rem",
  },
  iconTileCompute: {
    backgroundColor: semanticColors.indigoMuted,
    color: semanticColors.indigoFg,
  },
  iconTileStorage: {
    backgroundColor: semanticColors.tealMuted,
    color: semanticColors.tealFg,
  },
  iconTileIntegrations: {
    backgroundColor: semanticColors.purpleMuted,
    color: semanticColors.purpleFg,
  },
  triggerEnd: {
    marginInlineStart: "auto",
  },
  chevron: {
    color: semanticColors.fgMuted,
    flexShrink: 0,
    transform: "rotate(0deg)",
    transitionDuration: durations.fast,
    transitionProperty: "transform",
  },
  chevronOpen: {
    transform: "rotate(90deg)",
  },
  panelWrap: {
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
  },
  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",
  },
  tableBodyRow: {
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    cursor: "pointer",
    transitionDuration: durations.fast,
    transitionProperty: "background-color",
  },
  tableBodyRowExpanded: {
    backgroundColor: semanticColors.bgSubtle,
  },
  tableBodyCell: {
    borderBottomColor: semanticColors.borderMuted,
    borderBottomStyle: "solid",
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
    verticalAlign: "middle",
  },
  expandCol: {
    paddingInlineEnd: spacing._1,
    paddingInlineStart: spacing._4,
    width: "2.5rem",
  },
  primaryCol: {
    minWidth: "14rem",
  },
  metricCol: {
    minWidth: "7.5rem",
    whiteSpace: "nowrap",
  },
  utilCol: {
    minWidth: "9.5rem",
  },
  spendCol: {
    minWidth: "8.25rem",
    textAlign: "end",
    whiteSpace: "nowrap",
  },
  trendCol: {
    minWidth: "6.75rem",
    paddingInlineEnd: spacing._4,
    textAlign: "end",
    whiteSpace: "nowrap",
  },
  alignEnd: {
    textAlign: "end",
  },
  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%",
  },
  sortIconIdle: {
    opacity: 0.45,
  },
  utilProgress: {
    flexGrow: 1,
    minWidth: "4.5rem",
  },
  utilValue: {
    minWidth: "2.25rem",
  },
  expandedRow: {
    backgroundColor: semanticColors.bgMuted,
  },
  expandedCell: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },
  detailPanel: {
    gridTemplateColumns: {
      default: "minmax(0, 1.8fr) minmax(15rem, 1fr)",
      [NARROW]: "minmax(0, 1fr)",
    },
  },
  chartPane: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  summaryPane: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  emptyCard: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
  },
});

// ============= HELPER UI COMPONENTS =============

function TrendBadge({ id }: { id: string }) {
  const range = useRange();
  const pct = trendPercentFor(id, range);
  const isIncrease = pct > 0.05;
  const isDecrease = pct < -0.05;
  // For infrastructure spend, lower spend is favorable (green), higher spend is cost growth (red).
  const palette = isDecrease ? greenPalette : isIncrease ? redPalette : grayPalette;
  const sign = isIncrease ? "+" : isDecrease ? "−" : "";
  return (
    <HStack justify="end">
      <Badge variant="subtle" size="sm" palette={palette}>
        {sign}
        {oneDecimal.format(Math.abs(pct))}%
      </Badge>
    </HStack>
  );
}

interface SortHeaderProps<K extends string> {
  label: string;
  columnKey: K;
  sort: SortState<K> | null;
  onSort: (key: K) => void;
  align?: "start" | "end";
}

function SortHeader<K extends string>({
  label,
  columnKey,
  sort,
  onSort,
  align = "start",
}: SortHeaderProps<K>) {
  const isActive = sort?.key === columnKey;
  const direction = isActive ? sort.direction : null;

  return (
    <button
      type="button"
      onClick={() => onSort(columnKey)}
      {...stylex.props(
        styles.sortButton,
        isActive && styles.sortButtonActive,
        align === "end" && styles.sortButtonEnd,
      )}
    >
      <span>{label}</span>
      <SortIcon direction={direction} />
    </button>
  );
}

// ============= EXPANDED ROW DETAIL PANEL =============

function SpendDetailPanel({
  resource,
  onInspectAction,
}: {
  resource: ResourceBase;
  onInspectAction: (resource: ResourceBase) => void;
}) {
  const range = useRange();
  const points = useMemo(() => historyWindowFor(resource.id, range), [resource.id, range]);

  const openCents = points[0] ?? resource.monthlySpendCents;
  const currentCents = points[points.length - 1] ?? resource.monthlySpendCents;
  const deltaCents = currentCents - openCents;
  const peakCents = useMemo(
    () => points.reduce((max, value) => (value > max ? value : max), currentCents),
    [points, currentCents],
  );
  const lowCents = useMemo(
    () => points.reduce((min, value) => (value < min ? value : min), currentCents),
    [points, currentCents],
  );

  // Spend dropping or flat is favorable (green); spend climbing is unfavorable (red).
  const isFavorable = deltaCents <= 0;
  const seriesColor = isFavorable ? semanticColors.greenSolid : semanticColors.redSolid;

  const chartData = useMemo(
    () =>
      points.map((cents, day) => ({
        label: dateLabelDaysAgo(points.length - 1 - day),
        "Run-rate": cents / 100,
      })),
    [points],
  );

  const openDollars = openCents / 100;
  const minDollars = lowCents / 100;
  const maxDollars = peakCents / 100;
  const spread = Math.max(maxDollars - minDollars, maxDollars * 0.08, 100);
  const yMin = Math.max(0, Math.floor((minDollars - spread * 0.18) / 100) * 100);
  const yMax = Math.ceil((maxDollars + spread * 0.14) / 100) * 100;

  const deltaSign = deltaCents > 0 ? "+" : deltaCents < 0 ? "−" : "";

  return (
    <Grid gap="5" style={styles.detailPanel}>
      <VStack gap="2.5" style={styles.chartPane}>
        <HStack justify="between" align="center" wrap="wrap" gap="2">
          <Text render={<span />} size="xs" weight="semibold">
            {RANGE_LABELS[range]} run-rate trajectory
          </Text>
          <Text render={<span />} size="xs" tone="muted">
            Dashed line marks window open ({formatWholeDollars(openDollars)})
          </Text>
        </HStack>

        <AreaChart
          data={chartData}
          index="label"
          categories={["Run-rate"]}
          colors={[seriesColor]}
          height={148}
          curve="linear"
          showLegend={false}
          showGrid={false}
          yDomain={[yMin, yMax]}
          referenceLine={{ value: openDollars, label: "Window open" }}
          valueFormatter={formatWholeDollars}
          ariaLabel={`${resource.name} ${RANGE_LABELS[range]} monthly spend run-rate history`}
        />
      </VStack>

      <VStack justify="between" gap="3" style={styles.summaryPane}>
        <Grid columns="2" gap="3">
          <VStack gap="0.5">
            <Text render={<span />} size="xs" tone="muted">
              Window Open
            </Text>
            <Text render={<span />} size="sm" weight="semibold" tabular="true">
              {formatCents(openCents)}
            </Text>
          </VStack>
          <VStack gap="0.5">
            <Text render={<span />} size="xs" tone="muted">
              Window Net Delta
            </Text>
            <Text
              render={<span />}
              size="sm"
              weight="semibold"
              tabular="true"
              tone={isFavorable ? "success" : "error"}
            >
              {deltaSign}
              {formatCents(Math.abs(deltaCents))}
            </Text>
          </VStack>
          <VStack gap="0.5">
            <Text render={<span />} size="xs" tone="muted">
              Peak Run-Rate
            </Text>
            <Text render={<span />} size="sm" weight="semibold" tabular="true">
              {formatCents(peakCents)}
            </Text>
          </VStack>
          <VStack gap="0.5">
            <Text render={<span />} size="xs" tone="muted">
              {resource.detailLabel}
            </Text>
            <Text render={<span />} size="sm" weight="semibold" tabular="true">
              {resource.detailValue}
            </Text>
          </VStack>
        </Grid>

        <Separator decorative />

        <HStack justify="between" align="center" wrap="wrap" gap="2">
          <Text render={<span />} size="xs" tone="muted">
            Owner · {resource.owner}
          </Text>
          <Button
            variant="outline"
            size="xs"
            onClick={(event) => {
              event.stopPropagation();
              onInspectAction(resource);
            }}
          >
            Export breakdown
          </Button>
        </HStack>
      </VStack>
    </Grid>
  );
}

// ============= COLLAPSIBLE SECTION SHELL =============

interface CollapsibleSectionProps {
  id: GroupId;
  title: string;
  description: string;
  icon: React.ReactNode;
  iconTileStyle: stylex.StyleXStyles;
  count: number;
  summaryLabel: string;
  summaryValue: string;
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  children: React.ReactNode;
}

function CollapsibleSection({
  id,
  title,
  description,
  icon,
  iconTileStyle,
  count,
  summaryLabel,
  summaryValue,
  isOpen,
  onOpenChange,
  children,
}: CollapsibleSectionProps) {
  return (
    <Card.Root variant="outline" data-section={id} style={styles.sectionCard}>
      <Collapsible.Root open={isOpen} onOpenChange={onOpenChange}>
        <Collapsible.Trigger
          render={<button type="button" {...stylex.props(styles.triggerButton)} />}
        >
          <HStack align="center" gap="2.5">
            <ChevronRightIcon rotated={isOpen} />
            <Center display="inline" render={<span />} style={[styles.iconTile, iconTileStyle]}>
              {icon}
            </Center>
            <VStack gap="0.5">
              <HStack align="center" wrap="wrap" gap="2">
                <Text render={<span />} size="sm" weight="semibold">
                  {title}
                </Text>
                <Badge variant="surface" size="xs" palette={grayPalette}>
                  {count}
                </Badge>
              </HStack>
              <Text render={<span />} size="xs" tone="muted">
                {description}
              </Text>
            </VStack>
          </HStack>

          <HStack align="center" gap="3" style={styles.triggerEnd}>
            <VStack align="end" gap="0.5">
              <Text render={<span />} size="xs" tone="muted">
                {summaryLabel}
              </Text>
              <Text render={<span />} size="sm" weight="semibold" tabular="true">
                {summaryValue}
              </Text>
            </VStack>
          </HStack>
        </Collapsible.Trigger>

        <Collapsible.Panel>
          <div {...stylex.props(styles.panelWrap)}>{children}</div>
        </Collapsible.Panel>
      </Collapsible.Root>
    </Card.Root>
  );
}

// ============= SORT HELPERS =============

function toggleSortState<K extends string>(
  current: SortState<K> | null,
  key: K,
): SortState<K> {
  if (current?.key === key) {
    return { key, direction: current.direction === "asc" ? "desc" : "asc" };
  }
  return { key, direction: "desc" };
}

// ============= TABLE 1 — COMPUTE & INFERENCE CLUSTERS =============

type ComputeSortKey = "name" | "region" | "utilization" | "capacity" | "spend" | "trend";

function ComputeSectionTable({
  rows,
  expandedRows,
  onToggleRow,
  onInspectAction,
}: {
  rows: readonly ComputeCluster[];
  expandedRows: ReadonlySet<string>;
  onToggleRow: (id: string) => void;
  onInspectAction: (resource: ResourceBase) => void;
}) {
  const range = useRange();
  const [sort, setSort] = useState<SortState<ComputeSortKey> | null>({
    key: "spend",
    direction: "desc",
  });

  const sorted = useMemo(() => {
    const list = [...rows];
    if (!sort) return list;
    const factor = sort.direction === "asc" ? 1 : -1;
    list.sort((a, b) => {
      switch (sort.key) {
        case "name":
          return factor * a.name.localeCompare(b.name);
        case "region":
          return factor * a.region.localeCompare(b.region);
        case "utilization":
          return factor * (a.utilizationPct - b.utilizationPct);
        case "capacity":
          return factor * (a.capacityCount - b.capacityCount);
        case "spend":
          return factor * (a.monthlySpendCents - b.monthlySpendCents);
        case "trend":
          return factor * (trendPercentFor(a.id, range) - trendPercentFor(b.id, range));
      }
    });
    return list;
  }, [rows, sort, range]);

  const handleSort = (key: ComputeSortKey) => setSort((prev) => toggleSortState(prev, key));

  return (
    <div {...stylex.props(styles.tableScroll)}>
      <Table.Root variant="line" size="md">
        <Table.Header>
          <Table.Row style={styles.tableHeaderRow}>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.expandCol]}>
              <VisuallyHidden>Expand</VisuallyHidden>
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.primaryCol]}>
              <SortHeader label="Cluster" columnKey="name" sort={sort} onSort={handleSort} />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.metricCol]}>
              <SortHeader label="Region" columnKey="region" sort={sort} onSort={handleSort} />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.utilCol]}>
              <SortHeader
                label="Utilization"
                columnKey="utilization"
                sort={sort}
                onSort={handleSort}
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader
              style={[styles.tableHeaderCell, styles.metricCol, styles.alignEnd]}
            >
              <SortHeader
                label="Active Capacity"
                columnKey="capacity"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.spendCol]}>
              <SortHeader
                label="Monthly Spend"
                columnKey="spend"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.trendCol]}>
              <SortHeader
                label={`Trend (${range})`}
                columnKey="trend"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          {sorted.map((cluster) => {
            const isExpanded = expandedRows.has(cluster.id);
            return (
              <Fragment key={cluster.id}>
                <Table.Row
                  onClick={() => onToggleRow(cluster.id)}
                  style={[styles.tableBodyRow, isExpanded && styles.tableBodyRowExpanded]}
                >
                  <Table.Cell style={[styles.tableBodyCell, styles.expandCol]}>
                    <IconButton
                      variant="ghost"
                      size="2xs"
                      aria-expanded={isExpanded}
                      aria-label={`${isExpanded ? "Collapse" : "Expand"} ${cluster.name} spend history`}
                      onClick={(event) => {
                        event.stopPropagation();
                        onToggleRow(cluster.id);
                      }}
                    >
                      <ChevronRightIcon rotated={isExpanded} />
                    </IconButton>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.primaryCol]}>
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        {cluster.name}
                      </Text>
                      <Text render={<span />} size="xs" tone="muted">
                        {cluster.subtitle}
                      </Text>
                    </VStack>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol]}>
                    <Text render={<span />} variant="mono" size="xs" tabular="true">
                      {cluster.region}
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.utilCol]}>
                    <HStack align="center" gap="2.5">
                      <Progress.Root
                        value={cluster.utilizationPct}
                        max={100}
                        size="xs"
                        shape="full"
                        palette={grayPalette}
                        aria-label={`${cluster.name} utilization ${cluster.utilizationPct}%`}
                        style={styles.utilProgress}
                      >
                        <Progress.Track>
                          <Progress.Range />
                        </Progress.Track>
                      </Progress.Root>
                      <Text
                        render={<span />}
                        size="xs"
                        weight="medium"
                        tabular="true"
                        align="end"
                        style={styles.utilValue}
                      >
                        {cluster.utilizationPct}%
                      </Text>
                    </HStack>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol, styles.alignEnd]}>
                    <Text render={<span />} size="sm" tone="muted" tabular="true">
                      {cluster.capacityCount} {cluster.capacityUnit}
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.spendCol]}>
                    <Text render={<span />} size="sm" weight="medium" tabular="true">
                      {formatCents(cluster.monthlySpendCents)}
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.trendCol]}>
                    <TrendBadge id={cluster.id} />
                  </Table.Cell>
                </Table.Row>

                {isExpanded ? (
                  <Table.Row style={styles.expandedRow}>
                    <Table.Cell colSpan={7} style={styles.expandedCell}>
                      <SpendDetailPanel resource={cluster} onInspectAction={onInspectAction} />
                    </Table.Cell>
                  </Table.Row>
                ) : null}
              </Fragment>
            );
          })}
        </Table.Body>
      </Table.Root>
    </div>
  );
}

// ============= TABLE 2 — STORAGE & DATA LAKES =============

type StorageSortKey = "name" | "tier" | "storedTb" | "egressTb" | "spend" | "trend";

function StorageSectionTable({
  rows,
  expandedRows,
  onToggleRow,
  onInspectAction,
}: {
  rows: readonly StorageLake[];
  expandedRows: ReadonlySet<string>;
  onToggleRow: (id: string) => void;
  onInspectAction: (resource: ResourceBase) => void;
}) {
  const range = useRange();
  const [sort, setSort] = useState<SortState<StorageSortKey> | null>({
    key: "spend",
    direction: "desc",
  });

  const sorted = useMemo(() => {
    const list = [...rows];
    if (!sort) return list;
    const factor = sort.direction === "asc" ? 1 : -1;
    list.sort((a, b) => {
      switch (sort.key) {
        case "name":
          return factor * a.name.localeCompare(b.name);
        case "tier":
          return factor * (TIER_ORDER[a.tier] - TIER_ORDER[b.tier]);
        case "storedTb":
          return factor * (a.storedTb - b.storedTb);
        case "egressTb":
          return factor * (a.egressTb - b.egressTb);
        case "spend":
          return factor * (a.monthlySpendCents - b.monthlySpendCents);
        case "trend":
          return factor * (trendPercentFor(a.id, range) - trendPercentFor(b.id, range));
      }
    });
    return list;
  }, [rows, sort, range]);

  const handleSort = (key: StorageSortKey) => setSort((prev) => toggleSortState(prev, key));

  return (
    <div {...stylex.props(styles.tableScroll)}>
      <Table.Root variant="line" size="md">
        <Table.Header>
          <Table.Row style={styles.tableHeaderRow}>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.expandCol]}>
              <VisuallyHidden>Expand</VisuallyHidden>
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.primaryCol]}>
              <SortHeader
                label="Bucket / Lake"
                columnKey="name"
                sort={sort}
                onSort={handleSort}
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.metricCol]}>
              <SortHeader label="Tier" columnKey="tier" sort={sort} onSort={handleSort} />
            </Table.ColumnHeader>
            <Table.ColumnHeader
              style={[styles.tableHeaderCell, styles.metricCol, styles.alignEnd]}
            >
              <SortHeader
                label="Stored TB"
                columnKey="storedTb"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader
              style={[styles.tableHeaderCell, styles.metricCol, styles.alignEnd]}
            >
              <SortHeader
                label="Egress / mo"
                columnKey="egressTb"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.spendCol]}>
              <SortHeader
                label="Monthly Spend"
                columnKey="spend"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.trendCol]}>
              <SortHeader
                label={`Trend (${range})`}
                columnKey="trend"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          {sorted.map((lake) => {
            const isExpanded = expandedRows.has(lake.id);
            return (
              <Fragment key={lake.id}>
                <Table.Row
                  onClick={() => onToggleRow(lake.id)}
                  style={[styles.tableBodyRow, isExpanded && styles.tableBodyRowExpanded]}
                >
                  <Table.Cell style={[styles.tableBodyCell, styles.expandCol]}>
                    <IconButton
                      variant="ghost"
                      size="2xs"
                      aria-expanded={isExpanded}
                      aria-label={`${isExpanded ? "Collapse" : "Expand"} ${lake.name} spend history`}
                      onClick={(event) => {
                        event.stopPropagation();
                        onToggleRow(lake.id);
                      }}
                    >
                      <ChevronRightIcon rotated={isExpanded} />
                    </IconButton>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.primaryCol]}>
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        {lake.name}
                      </Text>
                      <Text render={<span />} size="xs" tone="muted">
                        {lake.subtitle}
                      </Text>
                    </VStack>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol]}>
                    <Badge variant="subtle" size="sm" palette={TIER_PALETTES[lake.tier]}>
                      {lake.tier}
                    </Badge>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol, styles.alignEnd]}>
                    <Text render={<span />} size="sm" tone="muted" tabular="true">
                      {oneDecimal.format(lake.storedTb)} TB
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol, styles.alignEnd]}>
                    <Text render={<span />} size="sm" tone="muted" tabular="true">
                      {oneDecimal.format(lake.egressTb)} TB
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.spendCol]}>
                    <Text render={<span />} size="sm" weight="medium" tabular="true">
                      {formatCents(lake.monthlySpendCents)}
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.trendCol]}>
                    <TrendBadge id={lake.id} />
                  </Table.Cell>
                </Table.Row>

                {isExpanded ? (
                  <Table.Row style={styles.expandedRow}>
                    <Table.Cell colSpan={7} style={styles.expandedCell}>
                      <SpendDetailPanel resource={lake} onInspectAction={onInspectAction} />
                    </Table.Cell>
                  </Table.Row>
                ) : null}
              </Fragment>
            );
          })}
        </Table.Body>
      </Table.Root>
    </div>
  );
}

// ============= TABLE 3 — THIRD-PARTY INTEGRATIONS & APIS =============

type IntegrationSortKey =
  | "name"
  | "quota"
  | "requests"
  | "errorRate"
  | "spend"
  | "trend";

function IntegrationsSectionTable({
  rows,
  expandedRows,
  onToggleRow,
  onInspectAction,
}: {
  rows: readonly ThirdPartyIntegration[];
  expandedRows: ReadonlySet<string>;
  onToggleRow: (id: string) => void;
  onInspectAction: (resource: ResourceBase) => void;
}) {
  const range = useRange();
  const [sort, setSort] = useState<SortState<IntegrationSortKey> | null>({
    key: "spend",
    direction: "desc",
  });

  const sorted = useMemo(() => {
    const list = [...rows];
    if (!sort) return list;
    const factor = sort.direction === "asc" ? 1 : -1;
    list.sort((a, b) => {
      switch (sort.key) {
        case "name":
          return factor * a.name.localeCompare(b.name);
        case "quota":
          return factor * (a.quotaUsedPct - b.quotaUsedPct);
        case "requests":
          return factor * (a.requestsMillions - b.requestsMillions);
        case "errorRate":
          return factor * (a.errorRatePct - b.errorRatePct);
        case "spend":
          return factor * (a.monthlySpendCents - b.monthlySpendCents);
        case "trend":
          return factor * (trendPercentFor(a.id, range) - trendPercentFor(b.id, range));
      }
    });
    return list;
  }, [rows, sort, range]);

  const handleSort = (key: IntegrationSortKey) => setSort((prev) => toggleSortState(prev, key));

  return (
    <div {...stylex.props(styles.tableScroll)}>
      <Table.Root variant="line" size="md">
        <Table.Header>
          <Table.Row style={styles.tableHeaderRow}>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.expandCol]}>
              <VisuallyHidden>Expand</VisuallyHidden>
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.primaryCol]}>
              <SortHeader label="Provider" columnKey="name" sort={sort} onSort={handleSort} />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.utilCol]}>
              <SortHeader
                label="Auth & Quota"
                columnKey="quota"
                sort={sort}
                onSort={handleSort}
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader
              style={[styles.tableHeaderCell, styles.metricCol, styles.alignEnd]}
            >
              <SortHeader
                label="Requests / mo"
                columnKey="requests"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader
              style={[styles.tableHeaderCell, styles.metricCol, styles.alignEnd]}
            >
              <SortHeader
                label="Error Rate"
                columnKey="errorRate"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.spendCol]}>
              <SortHeader
                label="Monthly Spend"
                columnKey="spend"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
            <Table.ColumnHeader style={[styles.tableHeaderCell, styles.trendCol]}>
              <SortHeader
                label={`Trend (${range})`}
                columnKey="trend"
                sort={sort}
                onSort={handleSort}
                align="end"
              />
            </Table.ColumnHeader>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          {sorted.map((integration) => {
            const isExpanded = expandedRows.has(integration.id);
            const healthMeta = HEALTH_META[integration.health];
            const isHighError = integration.errorRatePct >= 0.5;
            return (
              <Fragment key={integration.id}>
                <Table.Row
                  onClick={() => onToggleRow(integration.id)}
                  style={[styles.tableBodyRow, isExpanded && styles.tableBodyRowExpanded]}
                >
                  <Table.Cell style={[styles.tableBodyCell, styles.expandCol]}>
                    <IconButton
                      variant="ghost"
                      size="2xs"
                      aria-expanded={isExpanded}
                      aria-label={`${isExpanded ? "Collapse" : "Expand"} ${integration.name} spend history`}
                      onClick={(event) => {
                        event.stopPropagation();
                        onToggleRow(integration.id);
                      }}
                    >
                      <ChevronRightIcon rotated={isExpanded} />
                    </IconButton>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.primaryCol]}>
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        {integration.name}
                      </Text>
                      <Text render={<span />} size="xs" tone="muted">
                        {integration.subtitle}
                      </Text>
                    </VStack>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.utilCol]}>
                    <VStack gap="0.5">
                      <Status.Root size="sm" palette={healthMeta.palette}>
                        <Status.Indicator />
                        {healthMeta.label}
                      </Status.Root>
                      <Text render={<span />} size="xs" tone="muted" tabular="true">
                        {integration.authScheme} · {integration.quotaUsedPct}% quota
                      </Text>
                    </VStack>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol, styles.alignEnd]}>
                    <Text render={<span />} size="sm" tone="muted" tabular="true">
                      {oneDecimal.format(integration.requestsMillions)}M
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.metricCol, styles.alignEnd]}>
                    <Text
                      render={<span />}
                      size="sm"
                      tabular="true"
                      tone={isHighError ? "error" : "muted"}
                      weight={isHighError ? "semibold" : "normal"}
                    >
                      {twoDecimals.format(integration.errorRatePct)}%
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.spendCol]}>
                    <Text render={<span />} size="sm" weight="medium" tabular="true">
                      {formatCents(integration.monthlySpendCents)}
                    </Text>
                  </Table.Cell>
                  <Table.Cell style={[styles.tableBodyCell, styles.trendCol]}>
                    <TrendBadge id={integration.id} />
                  </Table.Cell>
                </Table.Row>

                {isExpanded ? (
                  <Table.Row style={styles.expandedRow}>
                    <Table.Cell colSpan={7} style={styles.expandedCell}>
                      <SpendDetailPanel
                        resource={integration}
                        onInspectAction={onInspectAction}
                      />
                    </Table.Cell>
                  </Table.Row>
                ) : null}
              </Fragment>
            );
          })}
        </Table.Body>
      </Table.Root>
    </div>
  );
}

// ============= MAIN BLOCK =============

export interface CollapsibleTableProps extends StyleOverrideProps {
  /** Initial global time range driving all trend columns and row charts. */
  defaultRange?: RangeId;
}

export function CollapsibleTable({
  defaultRange = "90D",
  palette,
  style,
}: CollapsibleTableProps) {
  const [toaster] = useState(() => Toast.createToaster());
  const [range, setRange] = useState<RangeId>(defaultRange);
  const [query, setQuery] = useState("");
  const [openGroups, setOpenGroups] = useState<Set<GroupId>>(() => new Set(GROUP_IDS));
  const [expandedRows, setExpandedRows] = useState<Set<string>>(() => new Set(["cmp-1"]));

  const normalizedQuery = query.trim().toLowerCase();

  const filteredCompute = useMemo(() => {
    if (!normalizedQuery) return COMPUTE_CLUSTERS;
    return COMPUTE_CLUSTERS.filter(
      (c) =>
        c.name.toLowerCase().includes(normalizedQuery) ||
        c.subtitle.toLowerCase().includes(normalizedQuery) ||
        c.region.toLowerCase().includes(normalizedQuery) ||
        c.owner.toLowerCase().includes(normalizedQuery),
    );
  }, [normalizedQuery]);

  const filteredStorage = useMemo(() => {
    if (!normalizedQuery) return STORAGE_LAKES;
    return STORAGE_LAKES.filter(
      (s) =>
        s.name.toLowerCase().includes(normalizedQuery) ||
        s.subtitle.toLowerCase().includes(normalizedQuery) ||
        s.tier.toLowerCase().includes(normalizedQuery) ||
        s.owner.toLowerCase().includes(normalizedQuery),
    );
  }, [normalizedQuery]);

  const filteredIntegrations = useMemo(() => {
    if (!normalizedQuery) return INTEGRATIONS;
    return INTEGRATIONS.filter(
      (item) =>
        item.name.toLowerCase().includes(normalizedQuery) ||
        item.subtitle.toLowerCase().includes(normalizedQuery) ||
        item.authScheme.toLowerCase().includes(normalizedQuery) ||
        item.health.toLowerCase().includes(normalizedQuery) ||
        item.owner.toLowerCase().includes(normalizedQuery),
    );
  }, [normalizedQuery]);

  const visibleRowIds = useMemo(
    () => [
      ...filteredCompute.map((r) => r.id),
      ...filteredStorage.map((r) => r.id),
      ...filteredIntegrations.map((r) => r.id),
    ],
    [filteredCompute, filteredStorage, filteredIntegrations],
  );

  const visibleGroupIds = useMemo(() => {
    const ids: GroupId[] = [];
    if (filteredCompute.length > 0) ids.push("compute");
    if (filteredStorage.length > 0) ids.push("storage");
    if (filteredIntegrations.length > 0) ids.push("integrations");
    return ids;
  }, [filteredCompute.length, filteredStorage.length, filteredIntegrations.length]);

  const totals = useMemo(() => {
    const compute = sumCents(filteredCompute);
    const storage = sumCents(filteredStorage);
    const integrations = sumCents(filteredIntegrations);
    const combined = compute + storage + integrations;

    const visibleResources: ResourceBase[] = [
      ...filteredCompute,
      ...filteredStorage,
      ...filteredIntegrations,
    ];
    const openingCombined = visibleResources.reduce((acc, item) => {
      const window = historyWindowFor(item.id, range);
      return acc + (window[0] ?? item.monthlySpendCents);
    }, 0);

    const overallDeltaPct =
      openingCombined > 0 ? ((combined - openingCombined) / openingCombined) * 100 : 0;

    return {
      compute,
      storage,
      integrations,
      combined,
      overallDeltaPct,
      totalCount: visibleResources.length,
    };
  }, [filteredCompute, filteredStorage, filteredIntegrations, range]);

  const isEverythingOpen =
    visibleGroupIds.length > 0 &&
    visibleGroupIds.every((id) => openGroups.has(id)) &&
    visibleRowIds.every((id) => expandedRows.has(id));

  const toggleGroup = (id: GroupId) => (open: boolean) => {
    setOpenGroups((prev) => {
      const next = new Set(prev);
      if (open) {
        next.add(id);
      } else {
        next.delete(id);
      }
      return next;
    });
  };

  const toggleRow = (rowId: string) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(rowId)) {
        next.delete(rowId);
      } else {
        next.add(rowId);
      }
      return next;
    });
  };

  const handleToggleEverything = () => {
    const shouldExpand = !isEverythingOpen;
    setOpenGroups(shouldExpand ? new Set(GROUP_IDS) : new Set());
    setExpandedRows(shouldExpand ? new Set(ALL_ROW_IDS) : new Set());
  };

  const handleExportLedger = () => {
    toaster({
      title: "Spend ledger exported",
      description: `Prepared ${totals.totalCount} Stratos Cloud resources (${RANGE_LABELS[range]} window) as CSV.`,
      type: "success",
    });
  };

  const handleInspectResource = (resource: ResourceBase) => {
    toaster({
      title: `${resource.name} telemetry queued`,
      description: `Exporting ${RANGE_LABELS[range]} daily spend breakdown for ${resource.owner}.`,
      type: "info",
    });
  };

  const overallIsIncrease = totals.overallDeltaPct > 0.05;
  const overallIsDecrease = totals.overallDeltaPct < -0.05;
  const overallBadgePalette = overallIsDecrease
    ? greenPalette
    : overallIsIncrease
      ? redPalette
      : grayPalette;
  const overallSign = overallIsIncrease ? "+" : overallIsDecrease ? "−" : "";

  const shareOf = (part: number) =>
    totals.combined > 0 ? `${Math.round((part / totals.combined) * 100)}% of ledger` : "0% of ledger";

  return (
    <RangeContext.Provider value={range}>
      <div {...stylex.props(styles.root, palette, style)}>
        <VStack gap="6" style={styles.container}>
          <VStack render={<header />} gap="4">
            <HStack justify="between" align="start" wrap="wrap" gap="4">
              <VStack gap="1.5">
                <HStack align="center" wrap="wrap" gap="2.5">
                  <Heading render={<h1 />} size="2xl" style={styles.heading}>
                    Infrastructure Spend &amp; Usage Ledger
                  </Heading>
                  <Badge variant="subtle" size="sm" palette={bluePalette}>
                    Stratos Cloud
                  </Badge>
                </HStack>
                <Text size="sm" tone="muted" style={styles.subtitleMaxWidth}>
                  Heterogeneous cost groups organized into collapsible schema-specific tables. Click
                  any row to inspect its {RANGE_LABELS[range]} run-rate trajectory.
                </Text>
              </VStack>

              <HStack align="center" wrap="wrap" gap="2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleToggleEverything}
                  disabled={visibleGroupIds.length === 0}
                >
                  {isEverythingOpen ? "Collapse all" : "Expand all"}
                </Button>
                <Button variant="surface" size="sm" onClick={handleExportLedger}>
                  <DownloadIcon />
                  Export CSV
                </Button>
              </HStack>
            </HStack>

            <Grid gap="3" style={styles.kpiGrid}>
              <Card.Root variant="outline" size="sm">
                <Card.Body style={styles.kpiCardBody}>
                  <Stat.Root size="sm">
                    <HStack justify="between" align="center" gap="2">
                      <Stat.Label>Total Monthly Run-Rate</Stat.Label>
                      <Badge variant="subtle" size="xs" palette={overallBadgePalette}>
                        {overallSign}
                        {oneDecimal.format(Math.abs(totals.overallDeltaPct))}%
                      </Badge>
                    </HStack>
                    <Stat.ValueText style={styles.tabular}>
                      {formatCents(totals.combined)}
                    </Stat.ValueText>
                    <Stat.HelpText>
                      Across {totals.totalCount} active resources ({RANGE_LABELS[range]} delta)
                    </Stat.HelpText>
                  </Stat.Root>
                </Card.Body>
              </Card.Root>

              <Card.Root variant="outline" size="sm">
                <Card.Body style={styles.kpiCardBody}>
                  <Stat.Root size="sm">
                    <Stat.Label>Compute &amp; Inference</Stat.Label>
                    <Stat.ValueText style={styles.tabular}>
                      {formatCents(totals.compute)}
                    </Stat.ValueText>
                    <Stat.HelpText>
                      {filteredCompute.length} clusters · {shareOf(totals.compute)}
                    </Stat.HelpText>
                  </Stat.Root>
                </Card.Body>
              </Card.Root>

              <Card.Root variant="outline" size="sm">
                <Card.Body style={styles.kpiCardBody}>
                  <Stat.Root size="sm">
                    <Stat.Label>Storage &amp; Data Lakes</Stat.Label>
                    <Stat.ValueText style={styles.tabular}>
                      {formatCents(totals.storage)}
                    </Stat.ValueText>
                    <Stat.HelpText>
                      {filteredStorage.length} buckets · {shareOf(totals.storage)}
                    </Stat.HelpText>
                  </Stat.Root>
                </Card.Body>
              </Card.Root>

              <Card.Root variant="outline" size="sm">
                <Card.Body style={styles.kpiCardBody}>
                  <Stat.Root size="sm">
                    <Stat.Label>Third-Party APIs</Stat.Label>
                    <Stat.ValueText style={styles.tabular}>
                      {formatCents(totals.integrations)}
                    </Stat.ValueText>
                    <Stat.HelpText>
                      {filteredIntegrations.length} providers · {shareOf(totals.integrations)}
                    </Stat.HelpText>
                  </Stat.Root>
                </Card.Body>
              </Card.Root>
            </Grid>
          </VStack>

          <HStack justify="between" align="center" wrap="wrap" gap="3">
            <div {...stylex.props(styles.searchWrap)}>
              <SearchIcon />
              <Input
                size="sm"
                type="search"
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                placeholder="Filter clusters, buckets, regions, or providers…"
                aria-label="Filter infrastructure resources"
                style={styles.searchInput}
              />
              {query ? (
                <IconButton
                  variant="ghost"
                  size="2xs"
                  aria-label="Clear search query"
                  onClick={() => setQuery("")}
                  style={styles.clearButton}
                >
                  <ClearIcon />
                </IconButton>
              ) : null}
            </div>

            <HStack align="center" wrap="wrap" gap="2.5">
              <Text render={<span />} size="xs" weight="medium" tone="muted">
                Window
              </Text>
              <SegmentGroup.Root
                size="sm"
                value={range}
                onValueChange={(next) => setRange(next as RangeId)}
                aria-label="Global spend history time range"
              >
                {RANGE_IDS.map((id) => (
                  <SegmentGroup.Item key={id} value={id}>
                    {id}
                  </SegmentGroup.Item>
                ))}
              </SegmentGroup.Root>
            </HStack>
          </HStack>

          {totals.totalCount === 0 ? (
            <div {...stylex.props(styles.emptyCard)}>
              <EmptyState.Root size="md" align="center">
                <EmptyState.Indicator>
                  <EmptyLedgerIcon />
                </EmptyState.Indicator>
                <EmptyState.Content>
                  <EmptyState.Title>No matching infrastructure resources</EmptyState.Title>
                  <EmptyState.Description>
                    No compute clusters, storage lakes, or API providers matched &ldquo;{query}
                    &rdquo;.
                  </EmptyState.Description>
                </EmptyState.Content>
                <EmptyState.Actions>
                  <Button variant="surface" size="sm" onClick={() => setQuery("")}>
                    Reset search
                  </Button>
                </EmptyState.Actions>
              </EmptyState.Root>
            </div>
          ) : (
            <VStack gap="4">
              {filteredCompute.length > 0 ? (
                <CollapsibleSection
                  id="compute"
                  title="Compute & Inference Clusters"
                  description="GPU inference pools and auto-scaled compute fleets tracked by regional utilization"
                  icon={<CpuIcon />}
                  iconTileStyle={styles.iconTileCompute}
                  count={filteredCompute.length}
                  summaryLabel="Monthly subtotal"
                  summaryValue={formatCents(totals.compute)}
                  isOpen={openGroups.has("compute")}
                  onOpenChange={toggleGroup("compute")}
                >
                  <ComputeSectionTable
                    rows={filteredCompute}
                    expandedRows={expandedRows}
                    onToggleRow={toggleRow}
                    onInspectAction={handleInspectResource}
                  />
                </CollapsibleSection>
              ) : null}

              {filteredStorage.length > 0 ? (
                <CollapsibleSection
                  id="storage"
                  title="Storage & Data Lakes"
                  description="Columnar lakes, object checkpoints, and archival vaults tracked by tier and egress"
                  icon={<DatabaseIcon />}
                  iconTileStyle={styles.iconTileStorage}
                  count={filteredStorage.length}
                  summaryLabel="Monthly subtotal"
                  summaryValue={formatCents(totals.storage)}
                  isOpen={openGroups.has("storage")}
                  onOpenChange={toggleGroup("storage")}
                >
                  <StorageSectionTable
                    rows={filteredStorage}
                    expandedRows={expandedRows}
                    onToggleRow={toggleRow}
                    onInspectAction={handleInspectResource}
                  />
                </CollapsibleSection>
              ) : null}

              {filteredIntegrations.length > 0 ? (
                <CollapsibleSection
                  id="integrations"
                  title="Third-Party Integrations & APIs"
                  description="External search, observability, routing, and relay APIs tracked by quota and error rate"
                  icon={<PlugIcon />}
                  iconTileStyle={styles.iconTileIntegrations}
                  count={filteredIntegrations.length}
                  summaryLabel="Monthly subtotal"
                  summaryValue={formatCents(totals.integrations)}
                  isOpen={openGroups.has("integrations")}
                  onOpenChange={toggleGroup("integrations")}
                >
                  <IntegrationsSectionTable
                    rows={filteredIntegrations}
                    expandedRows={expandedRows}
                    onToggleRow={toggleRow}
                    onInspectAction={handleInspectResource}
                  />
                </CollapsibleSection>
              ) : null}
            </VStack>
          )}
        </VStack>

        <Toaster toaster={toaster} />
      </div>
    </RangeContext.Provider>
  );
}
```

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