---
title: "Portfolio Dashboard · UI SDK — StyleX Blocks"
description: "Treasury and infrastructure budget portfolio view with a period switcher, KPI summary tiles, historical reserve value curve, interactive allocation slices, stacked breakdown and budget-vs-actual bars, rate benchmark sparklines, and a filterable, sortable cost-center table."
url: "https://stylexblocks.com/block/ui-sdk/portfolio-dashboard/"
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/"
---

# Portfolio Dashboard block

Treasury and infrastructure budget portfolio view with a period switcher, KPI summary tiles, historical reserve value curve, interactive allocation slices, stacked breakdown and budget-vs-actual bars, rate benchmark sparklines, and a filterable, sortable cost-center table.

- Behavior engine: UI SDK
- Category: [Dashboards](https://stylexblocks.com/blocks/dashboards.md)
- Built with: [Avatar](https://stylexblocks.com/components/ui-sdk/avatar.md), [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), [Chart](https://stylexblocks.com/components/ui-sdk/chart.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Link](https://stylexblocks.com/components/ui-sdk/link.md), [Native Select](https://stylexblocks.com/components/ui-sdk/native-select.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), [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)
- HTML page: https://stylexblocks.com/block/ui-sdk/portfolio-dashboard/

## 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 portfolio-dashboard
```

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

## Usage

```tsx
import { PortfolioDashboard } from "#components/blocks/ui-sdk/portfolio-dashboard.tsx";

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

## Source

`components/blocks/ui-sdk/portfolio-dashboard.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { useMemo, useState } from "react";
import { Avatar } from "#components/ui/ui-sdk/avatar.tsx";
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 {
  AreaChart,
  BarChart,
  CategoryBar,
  Sparkline,
  type ChartColorName,
} from "#components/ui/ui-sdk/chart.tsx";
import { Grid } from "#components/ui/ui-sdk/grid.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { Link } from "#components/ui/ui-sdk/link.tsx";
import { NativeSelect } from "#components/ui/ui-sdk/native-select.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, Stack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Stat } from "#components/ui/ui-sdk/stat.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 { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import {
  amberPalette,
  bluePalette,
  grayPalette,
  greenPalette,
  orangePalette,
  purplePalette,
  redPalette,
  tealPalette,
} from "@stylexblocks/ui/themes/palettes.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";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

// ============= CONTAINER BREAKPOINTS =============

const NARROW = "@container portfolio-dashboard (max-width: 1020px)";
const COMPACT = "@container portfolio-dashboard (max-width: 680px)";

// ============= DOMAIN TYPES =============

type PeriodKey = "1M" | "3M" | "YTD" | "1Y";
type CategoryKey = "compute" | "inference" | "storage" | "edge" | "observability" | "reserve";
type ChartTone = "blue" | "purple" | "teal" | "orange" | "green" | "gray";
type SortField = "name" | "allocatedK" | "sharePct" | "periodChangePct" | "driftPct";
type SortDir = "asc" | "desc";

interface KpiCardData {
  key: string;
  label: string;
  value: string;
  change: string;
  positive: boolean;
  helpText: string;
}

interface CurvePoint {
  slot: number;
  label: string;
  actual: number;
  benchmark: number;
}

interface AllocationSlice {
  key: CategoryKey;
  code: string;
  label: string;
  shortLabel: string;
  tone: ChartTone;
  allocatedK: number;
  budgetK: number;
  targetPct: number;
  periodChangePct: number;
}

interface PulseBenchmark {
  id: string;
  name: string;
  ticker: string;
  reading: string;
  change: string;
  positive: boolean;
  sparkData: ReadonlyArray<{ step: number; value: number }>;
}

interface CostCenterRow {
  id: string;
  code: string;
  name: string;
  region: string;
  category: CategoryKey;
  allocatedK: number;
  budgetK: number;
  periodChangePct: number;
  driftPct: number;
  sparkData: ReadonlyArray<{ step: number; value: number }>;
}

interface PeriodConfig {
  key: PeriodKey;
  subtitle: string;
  kpis: readonly KpiCardData[];
  curve: readonly CurvePoint[];
  changeScale: number;
  budgetScale: number;
}

// ============= TONE & PALETTE MAPS =============

const TONE_CHART_COLOR: Record<ChartTone, ChartColorName> = {
  blue: "blue",
  purple: "violet",
  teal: "teal",
  orange: "orange",
  green: "emerald",
  gray: "slate",
};

const TONE_PALETTE = {
  blue: bluePalette,
  purple: purplePalette,
  teal: tealPalette,
  orange: orangePalette,
  green: greenPalette,
  gray: grayPalette,
} as const;

// ============= DETERMINISTIC DATA GENERATORS =============

function buildSparkData(
  seed: number,
  start: number,
  end: number,
  volatility: number,
  count: number,
): Array<{ step: number; value: number }> {
  let s = seed >>> 0;
  const rand = () => {
    s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
    return s / 0x100000000;
  };
  const points: Array<{ step: number; value: number }> = [];
  let drift = 0;
  for (let i = 0; i < count; i++) {
    const t = i / (count - 1);
    const trend = start + (end - start) * t;
    const wave =
      Math.sin(t * Math.PI * 2.4 + seed * 0.17) * volatility * 1.2 +
      Math.sin(t * Math.PI * 6.1 + seed * 0.37) * volatility * 0.65;
    drift = drift * 0.58 + (rand() - 0.5) * volatility * 1.9;
    points.push({ step: i + 1, value: Number((trend + wave + drift).toFixed(2)) });
  }
  return points;
}

function buildCurve(
  anchors: readonly (readonly [number, number])[],
  labels: readonly string[],
  benchStart: number,
  benchEnd: number,
  noiseAmp: number,
): CurvePoint[] {
  const count = labels.length;
  const maxSlot = count - 1;
  const out: CurvePoint[] = [];
  let ai = 0;

  for (let i = 0; i < count; i++) {
    const frac = maxSlot === 0 ? 0 : i / maxSlot;
    while (ai < anchors.length - 2 && frac >= anchors[ai + 1]![0]) {
      ai++;
    }
    const [f0, v0] = anchors[ai]!;
    const [f1, v1] = anchors[ai + 1]!;
    const localT = f1 === f0 ? 0 : (frac - f0) / (f1 - f0);
    const base = v0 + (v1 - v0) * localT;
    const seed = Math.sin((i + 3) * 14.319 + 41.77) * 43758.5453;
    const jitter = i === 0 || i === maxSlot ? 0 : (seed - Math.floor(seed) - 0.5) * noiseAmp;
    const benchmark = Math.round(benchStart + (benchEnd - benchStart) * frac);
    out.push({
      slot: i,
      label: labels[i]!,
      actual: Math.round(base + jitter),
      benchmark,
    });
  }
  return out;
}

// ============= MERIDIAN TREASURY DEMO DATA =============

const LABELS_1M = [
  "Nov 3", "Nov 5", "Nov 7", "Nov 9", "Nov 11", "Nov 13", "Nov 15", "Nov 17",
  "Nov 19", "Nov 21", "Nov 23", "Nov 25", "Nov 27", "Nov 29", "Dec 1",
] as const;

const LABELS_3M = [
  "Sep 4", "Sep 11", "Sep 18", "Sep 25", "Oct 2", "Oct 9", "Oct 16", "Oct 23",
  "Oct 30", "Nov 6", "Nov 13", "Nov 20", "Nov 27", "Dec 1",
] as const;

const LABELS_YTD = [
  "Jan 15", "Feb 1", "Feb 15", "Mar 1", "Mar 15", "Apr 1", "Apr 15", "May 1",
  "May 15", "Jun 1", "Jun 15", "Jul 1", "Jul 15", "Aug 1", "Aug 15", "Sep 1",
  "Sep 15", "Oct 1", "Oct 15", "Nov 1", "Nov 15", "Dec 1",
] as const;

const LABELS_1Y = [
  "Dec '25", "Dec 18", "Jan 4", "Jan 20", "Feb 5", "Feb 20", "Mar 8", "Mar 24",
  "Apr 9", "Apr 25", "May 11", "May 27", "Jun 12", "Jun 28", "Jul 14", "Jul 30",
  "Aug 15", "Aug 31", "Sep 16", "Oct 2", "Oct 18", "Nov 3", "Nov 18", "Dec 1",
] as const;

const PERIOD_CONFIGS: Record<PeriodKey, PeriodConfig> = {
  "1M": {
    key: "1M",
    subtitle: "Trailing 30 days · Nov 3 – Dec 1, 2026",
    kpis: [
      {
        key: "total",
        label: "Total Reserve Value",
        value: "$4.86M",
        change: "+2.9%",
        positive: true,
        helpText: "+$137k vs. Nov 3 opening balance",
      },
      {
        key: "committed",
        label: "Committed Allocation",
        value: "$4.32M",
        change: "88.9%",
        positive: true,
        helpText: "Target band 85%–92% · $540k liquid",
      },
      {
        key: "yield",
        label: "Commitment Savings",
        value: "$49.4k",
        change: "+4.6%",
        positive: true,
        helpText: "30d spot & reserved-instance credits",
      },
      {
        key: "centers",
        label: "Active Cost Centers",
        value: "12",
        change: "2 watch",
        positive: false,
        helpText: "AI Inference +2.6% above monthly cap",
      },
    ],
    curve: buildCurve(
      [
        [0, 4723],
        [0.2, 4748],
        [0.4, 4731],
        [0.65, 4794],
        [0.85, 4832],
        [1, 4860],
      ],
      LABELS_1M,
      4720,
      4815,
      18,
    ),
    changeScale: 0.24,
    budgetScale: 0.99,
  },
  "3M": {
    key: "3M",
    subtitle: "Trailing quarter · Sep 4 – Dec 1, 2026",
    kpis: [
      {
        key: "total",
        label: "Total Reserve Value",
        value: "$4.86M",
        change: "+6.8%",
        positive: true,
        helpText: "+$310k net reserve growth in Q4",
      },
      {
        key: "committed",
        label: "Committed Allocation",
        value: "$4.32M",
        change: "88.9%",
        positive: true,
        helpText: "6 active infrastructure slices funded",
      },
      {
        key: "yield",
        label: "Commitment Savings",
        value: "$148k",
        change: "+9.2%",
        positive: true,
        helpText: "Quarterly reserved capacity rebates",
      },
      {
        key: "centers",
        label: "Active Cost Centers",
        value: "12",
        change: "+1 Q4",
        positive: true,
        helpText: "H200 inference pool added Oct 12",
      },
    ],
    curve: buildCurve(
      [
        [0, 4550],
        [0.22, 4610],
        [0.45, 4585],
        [0.7, 4715],
        [0.88, 4795],
        [1, 4860],
      ],
      LABELS_3M,
      4540,
      4780,
      34,
    ),
    changeScale: 0.56,
    budgetScale: 0.98,
  },
  YTD: {
    key: "YTD",
    subtitle: "Year to date · Jan 1 – Dec 1, 2026",
    kpis: [
      {
        key: "total",
        label: "Total Reserve Value",
        value: "$4.86M",
        change: "+13.4%",
        positive: true,
        helpText: "+$574k vs. Jan 1 opening reserve",
      },
      {
        key: "committed",
        label: "Committed Allocation",
        value: "$4.32M",
        change: "88.9%",
        positive: true,
        helpText: "88.9% deployed · 11.1% T-bill buffer",
      },
      {
        key: "yield",
        label: "Annualized Yield",
        value: "11.4%",
        change: "+1.8 pts",
        positive: true,
        helpText: "Combined commit discount + reserve yield",
      },
      {
        key: "centers",
        label: "Active Cost Centers",
        value: "12",
        change: "+3 YTD",
        positive: true,
        helpText: "Across 4 regions & 6 budget slices",
      },
    ],
    curve: buildCurve(
      [
        [0, 4286],
        [0.15, 4390],
        [0.3, 4195],
        [0.48, 4360],
        [0.65, 4510],
        [0.82, 4720],
        [1, 4860],
      ],
      LABELS_YTD,
      4280,
      4740,
      58,
    ),
    changeScale: 0.92,
    budgetScale: 1,
  },
  "1Y": {
    key: "1Y",
    subtitle: "Trailing 12 months · Dec 2025 – Dec 2026",
    kpis: [
      {
        key: "total",
        label: "Total Reserve Value",
        value: "$4.86M",
        change: "+15.2%",
        positive: true,
        helpText: "+$640k vs. Dec 2025 baseline",
      },
      {
        key: "committed",
        label: "Committed Allocation",
        value: "$4.32M",
        change: "88.9%",
        positive: true,
        helpText: "$4.32M deployed · $540k liquidity reserve",
      },
      {
        key: "yield",
        label: "Efficiency Yield",
        value: "12.1%",
        change: "+$148k/qtr",
        positive: true,
        helpText: "Reserved compute rebates & T-bill interest",
      },
      {
        key: "centers",
        label: "Active Cost Centers",
        value: "12",
        change: "+3 YoY",
        positive: true,
        helpText: "6 portfolio slices · rebalanced quarterly",
      },
    ],
    curve: buildCurve(
      [
        [0, 4220],
        [0.14, 4360],
        [0.28, 4140],
        [0.44, 4310],
        [0.6, 4465],
        [0.76, 4660],
        [0.9, 4790],
        [1, 4860],
      ],
      LABELS_1Y,
      4220,
      4720,
      64,
    ),
    changeScale: 1,
    budgetScale: 1,
  },
};

const BASE_SLICES: readonly AllocationSlice[] = [
  {
    key: "compute",
    code: "CMP",
    label: "Compute",
    shortLabel: "Compute",
    tone: "blue",
    allocatedK: 1410,
    budgetK: 1380,
    targetPct: 28.5,
    periodChangePct: 12.4,
  },
  {
    key: "inference",
    code: "AIN",
    label: "AI Inference",
    shortLabel: "AI Inf.",
    tone: "purple",
    allocatedK: 1120,
    budgetK: 990,
    targetPct: 20.5,
    periodChangePct: 29.8,
  },
  {
    key: "storage",
    code: "STR",
    label: "Storage",
    shortLabel: "Storage",
    tone: "teal",
    allocatedK: 780,
    budgetK: 825,
    targetPct: 17.0,
    periodChangePct: 6.1,
  },
  {
    key: "edge",
    code: "EDG",
    label: "Edge Network",
    shortLabel: "Edge",
    tone: "orange",
    allocatedK: 590,
    budgetK: 610,
    targetPct: 12.5,
    periodChangePct: 9.3,
  },
  {
    key: "observability",
    code: "OBS",
    label: "Observability",
    shortLabel: "Obs.",
    tone: "green",
    allocatedK: 420,
    budgetK: 445,
    targetPct: 9.5,
    periodChangePct: -3.8,
  },
  {
    key: "reserve",
    code: "RSV",
    label: "Treasury Reserve",
    shortLabel: "Reserve",
    tone: "gray",
    allocatedK: 540,
    budgetK: 610,
    targetPct: 12.0,
    periodChangePct: 4.9,
  },
];

const SLICE_BY_KEY = new Map<CategoryKey, AllocationSlice>(BASE_SLICES.map((s) => [s.key, s]));
const TOTAL_RESERVE_K = BASE_SLICES.reduce((sum, s) => sum + s.allocatedK, 0);

const PULSE_BENCHMARKS: readonly PulseBenchmark[] = [
  {
    id: "gpu-spot",
    name: "H200 GPU Spot",
    ticker: "H200-HR",
    reading: "$2.64/hr",
    change: "-6.4%",
    positive: true,
    sparkData: buildSparkData(1107, 2.94, 2.64, 0.08, 36),
  },
  {
    id: "vcpu-pool",
    name: "Core vCPU Pool",
    ticker: "VCPU-U",
    reading: "$0.038/hr",
    change: "-2.1%",
    positive: true,
    sparkData: buildSparkData(2213, 0.041, 0.038, 0.001, 36),
  },
  {
    id: "obj-tier",
    name: "Object Tier Rate",
    ticker: "S3-TB",
    reading: "$18.40/TB",
    change: "-1.5%",
    positive: true,
    sparkData: buildSparkData(3319, 19.1, 18.4, 0.25, 36),
  },
  {
    id: "edge-egress",
    name: "Edge Egress",
    ticker: "CDN-GB",
    reading: "$0.019/GB",
    change: "+3.2%",
    positive: false,
    sparkData: buildSparkData(4421, 0.017, 0.019, 0.0007, 36),
  },
  {
    id: "log-ingest",
    name: "Log Ingestion",
    ticker: "OBS-GB",
    reading: "$0.42/GB",
    change: "+4.8%",
    positive: false,
    sparkData: buildSparkData(5533, 0.39, 0.42, 0.012, 36),
  },
  {
    id: "tbill-yield",
    name: "90d Reserve APY",
    ticker: "UST-90D",
    reading: "4.82%",
    change: "+0.18%",
    positive: true,
    sparkData: buildSparkData(6647, 4.61, 4.82, 0.05, 36),
  },
];

const COST_CENTERS: readonly CostCenterRow[] = [
  {
    id: "cc-1",
    code: "CMP-CORE",
    name: "Core Kubernetes Fleet",
    region: "us-east · eu-central",
    category: "compute",
    allocatedK: 840,
    budgetK: 820,
    periodChangePct: 11.2,
    driftPct: 0.4,
    sparkData: buildSparkData(7101, 740, 840, 18, 28),
  },
  {
    id: "cc-2",
    code: "AIN-H200",
    name: "H200 Inference Clusters",
    region: "us-west · ap-northeast",
    category: "inference",
    allocatedK: 720,
    budgetK: 630,
    periodChangePct: 34.6,
    driftPct: 1.9,
    sparkData: buildSparkData(7209, 535, 720, 24, 28),
  },
  {
    id: "cc-3",
    code: "CMP-BATCH",
    name: "Batch Worker Pools",
    region: "us-east · us-central",
    category: "compute",
    allocatedK: 570,
    budgetK: 560,
    periodChangePct: 14.1,
    driftPct: 0.2,
    sparkData: buildSparkData(7317, 495, 570, 14, 28),
  },
  {
    id: "cc-4",
    code: "STR-OBJ",
    name: "Multi-Region Object Store",
    region: "global-tier",
    category: "storage",
    allocatedK: 490,
    budgetK: 520,
    periodChangePct: 5.4,
    driftPct: -0.6,
    sparkData: buildSparkData(7423, 462, 490, 9, 28),
  },
  {
    id: "cc-5",
    code: "AIN-EVAL",
    name: "Model Eval Sandboxes",
    region: "us-west",
    category: "inference",
    allocatedK: 400,
    budgetK: 360,
    periodChangePct: 21.8,
    driftPct: 0.8,
    sparkData: buildSparkData(7531, 326, 400, 16, 28),
  },
  {
    id: "cc-6",
    code: "EDG-POP",
    name: "Global Edge PoP Mesh",
    region: "42 PoPs",
    category: "edge",
    allocatedK: 370,
    budgetK: 380,
    periodChangePct: 8.7,
    driftPct: -0.2,
    sparkData: buildSparkData(7643, 338, 370, 8, 28),
  },
  {
    id: "cc-7",
    code: "RSV-TBILL",
    name: "90-Day T-Bill Liquidity",
    region: "treasury-custody",
    category: "reserve",
    allocatedK: 360,
    budgetK: 410,
    periodChangePct: 4.8,
    driftPct: -1.0,
    sparkData: buildSparkData(7751, 344, 360, 4, 28),
  },
  {
    id: "cc-8",
    code: "STR-NVME",
    name: "NVMe Block Volumes",
    region: "us-east · eu-west",
    category: "storage",
    allocatedK: 290,
    budgetK: 305,
    periodChangePct: 7.3,
    driftPct: -0.3,
    sparkData: buildSparkData(7867, 268, 290, 7, 28),
  },
  {
    id: "cc-9",
    code: "OBS-LOG",
    name: "Distributed Log Ingestion",
    region: "us-east · eu-central",
    category: "observability",
    allocatedK: 255,
    budgetK: 270,
    periodChangePct: -4.6,
    driftPct: -0.3,
    sparkData: buildSparkData(7973, 272, 255, 8, 28),
  },
  {
    id: "cc-10",
    code: "EDG-EGR",
    name: "Cross-Region Backbone",
    region: "global-transit",
    category: "edge",
    allocatedK: 220,
    budgetK: 230,
    periodChangePct: 10.4,
    driftPct: -0.2,
    sparkData: buildSparkData(8089, 198, 220, 7, 28),
  },
  {
    id: "cc-11",
    code: "RSV-BURST",
    name: "Peak Capacity Buffer",
    region: "reserve-vault",
    category: "reserve",
    allocatedK: 180,
    budgetK: 200,
    periodChangePct: 5.1,
    driftPct: -0.4,
    sparkData: buildSparkData(8191, 171, 180, 3, 28),
  },
  {
    id: "cc-12",
    code: "OBS-TRC",
    name: "Tracing & APM Retention",
    region: "us-west · eu-west",
    category: "observability",
    allocatedK: 165,
    budgetK: 175,
    periodChangePct: -2.4,
    driftPct: -0.2,
    sparkData: buildSparkData(8311, 171, 165, 5, 28),
  },
];

// ============= HELPERS =============

function formatK(valueK: number): string {
  if (valueK >= 1000) {
    return `$${(valueK / 1000).toFixed(2)}M`;
  }
  return `$${Math.round(valueK).toLocaleString()}k`;
}

function formatChartK(valueK: number): string {
  return valueK === 0 ? "$0" : formatK(valueK);
}

function formatSignedPct(value: number, digits = 1): string {
  const sign = value > 0 ? "+" : "";
  return `${sign}${value.toFixed(digits)}%`;
}

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

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "portfolio-dashboard",
    containerType: "inline-size",
    display: "flex",
    flexDirection: "column",
    fontFamily: fonts.body,
    height: "100%",
    minHeight: 0,
    overflowY: "auto",
    width: "100%",
  },
  content: {
    paddingBlock: spacing._6,
    paddingInline: spacing._6,
    width: "100%",
  },
  headerBar: {
    alignItems: { default: "center", [COMPACT]: "stretch" },
    flexDirection: { default: "row", [COMPACT]: "column" },
  },
  pageHeading: {
    marginBlock: 0,
  },
  metricBody: {
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },
  deltaIcon: {
    alignItems: "center",
    display: "inline-flex",
  },
  heroSplit: {
    gridTemplateColumns: {
      default: "minmax(0, 2.65fr) minmax(18rem, 1fr)",
      [NARROW]: "minmax(0, 1fr)",
    },
  },
  twoColGrid: {
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      [NARROW]: "minmax(0, 1fr)",
    },
  },
  cardInner: {
    height: "100%",
    paddingBlock: spacing._5,
    paddingInline: spacing._5,
  },
  sectionHeading: {
    marginBlock: 0,
  },
  swatch: {
    borderRadius: "2px",
    display: "inline-block",
    flexShrink: 0,
    height: "0.625rem",
    width: "0.625rem",
  },
  sliceButton: {
    alignItems: "center",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.interactionHover,
    },
    borderColor: "transparent",
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    fontFamily: fonts.body,
    gap: spacing._3,
    justifyContent: "space-between",
    paddingBlock: spacing._2,
    paddingInline: spacing._2,
    textAlign: "start",
    width: "100%",
  },
  sliceButtonActive: {
    backgroundColor: semanticColors.interactionSelected,
    borderColor: semanticColors.accentBorder,
  },
  sliceEnd: {
    flexShrink: 0,
  },
  avatarCode: {
    fontFamily: fonts.mono,
    fontSize: "0.6875rem",
    fontWeight: fontWeights.semibold,
    letterSpacing: "0.02em",
  },
  segmentLegend: {
    gridTemplateColumns: "repeat(auto-fit, minmax(8.5rem, 1fr))",
  },
  segmentFilterButton: {
    alignItems: "center",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: semanticColors.fg,
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: fonts.body,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    gap: spacing._1_5,
    paddingBlock: 0,
    paddingInline: 0,
  },
  pulseGrid: {
    gridTemplateColumns: "repeat(auto-fit, minmax(12rem, 1fr))",
  },
  pulseBody: {
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },
  searchWrap: {
    minWidth: "13.5rem",
    position: "relative",
  },
  searchIcon: {
    color: semanticColors.fgMuted,
    insetInlineStart: spacing._2_5,
    pointerEvents: "none",
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineStart: spacing._8,
  },
  selectWrap: {
    minWidth: "10.5rem",
    width: "auto",
  },
  tableScroll: {
    overflowX: "auto",
    width: "100%",
  },
  sortButton: {
    alignItems: "center",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: "inherit",
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: "inherit",
    fontSize: "inherit",
    fontWeight: fontWeights.medium,
    gap: spacing._1,
    paddingBlock: 0,
    paddingInline: 0,
  },
  progressCell: {
    minWidth: "6.5rem",
  },
  sparkCellHost: {
    minWidth: "5.25rem",
    width: "5.5rem",
  },
  emptyState: {
    paddingBlock: spacing._8,
    textAlign: "center",
  },
});

const toneBg = stylex.create({
  blue: { backgroundColor: semanticColors.blueSolid },
  purple: { backgroundColor: semanticColors.violetSolid },
  teal: { backgroundColor: semanticColors.tealSolid },
  orange: { backgroundColor: semanticColors.orangeSolid },
  green: { backgroundColor: semanticColors.emeraldSolid },
  gray: { backgroundColor: semanticColors.graySolid },
});

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

function ArrowUpIcon() {
  return (
    <svg
      width="13"
      height="13"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.25"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <line x1="12" y1="19" x2="12" y2="5" />
      <polyline points="5 12 12 5 19 12" />
    </svg>
  );
}

function ArrowDownIcon() {
  return (
    <svg
      width="13"
      height="13"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.25"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <line x1="12" y1="5" x2="12" y2="19" />
      <polyline points="19 12 12 19 5 12" />
    </svg>
  );
}

function RebalanceIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.9"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M12 3v18" />
      <path d="M5 7h14" />
      <path d="M3 14l2-7 2 7a2 2 0 0 1-4 0Z" />
      <path d="M17 14l2-7 2 7a2 2 0 0 1-4 0Z" />
    </svg>
  );
}

function DownloadIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.9"
      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 SearchIcon({ style }: StyleOverrideProps) {
  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(style)}
    >
      <circle cx="11" cy="11" r="8" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

function SortIcon({ active, dir }: { active: boolean; dir: SortDir }) {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {active ? (
        dir === "asc" ? (
          <path d="M4.5 10 8 6.5 11.5 10" />
        ) : (
          <path d="M4.5 6 8 9.5 11.5 6" />
        )
      ) : (
        <>
          <path d="M5 6.25 8 3.5l3 2.75" opacity="0.55" />
          <path d="M5 9.75 8 12.5l3-2.75" opacity="0.55" />
        </>
      )}
    </svg>
  );
}

// ============= CHART CARDS =============

function AllocationStackedBarCard({
  slices,
  onSelectCategory,
}: {
  slices: readonly AllocationSlice[];
  onSelectCategory: (cat: CategoryKey) => void;
}) {
  const totalK = slices.reduce((sum, s) => sum + s.allocatedK, 0);

  return (
    <Card.Root variant="outline">
      <VStack gap="4" style={styles.cardInner}>
        <HStack justify="between" align="center" wrap="wrap" gap="2">
          <VStack gap="0.5">
            <Heading render={<h3 />} size="sm" style={styles.sectionHeading}>
              Allocation Breakdown
            </Heading>
            <Text size="xs" tone="muted">
              {formatK(totalK)} distributed across 6 treasury slices
            </Text>
          </VStack>
          <Badge variant="subtle" size="sm" palette={greenPalette}>
            Within policy band
          </Badge>
        </HStack>

        <CategoryBar
          values={slices.map((s) => s.allocatedK)}
          labels={slices.map((s) => s.label)}
          colors={slices.map((s) => TONE_CHART_COLOR[s.tone])}
          showLabels={false}
          valueFormatter={formatK}
          ariaLabel="Reserve allocation breakdown across infrastructure categories"
        />

        <Grid gap="3" style={styles.segmentLegend}>
          {slices.map((seg) => {
            const sharePct = ((seg.allocatedK / totalK) * 100).toFixed(1);
            return (
              <VStack key={seg.key} gap="0.5">
                <button
                  type="button"
                  onClick={() => onSelectCategory(seg.key)}
                  {...stylex.props(styles.segmentFilterButton)}
                >
                  <span {...stylex.props(styles.swatch, toneBg[seg.tone])} />
                  <span>{seg.label}</span>
                </button>
                <Text render={<span />} variant="mono" size="xs" tone="muted" tabular="true">
                  {formatK(seg.allocatedK)} · {sharePct}%
                </Text>
              </VStack>
            );
          })}
        </Grid>
      </VStack>
    </Card.Root>
  );
}

function CategoryComparisonCard({
  slices,
  period,
}: {
  slices: readonly AllocationSlice[];
  period: PeriodKey;
}) {
  const chartData = useMemo(
    () =>
      slices.map((slice) => ({
        category: slice.shortLabel,
        "Planned Budget": slice.budgetK,
        "Allocated Spend": slice.allocatedK,
      })),
    [slices],
  );

  return (
    <Card.Root variant="outline">
      <VStack gap="4" style={styles.cardInner}>
        <VStack gap="0.5">
          <Heading render={<h3 />} size="sm" style={styles.sectionHeading}>
            Budget vs. Allocated Spend
          </Heading>
          <Text size="xs" tone="muted">
            Category variance across {period} allocation window
          </Text>
        </VStack>

        <BarChart
          data={chartData}
          index="category"
          categories={["Planned Budget", "Allocated Spend"]}
          colors={["blue", "teal"]}
          type="grouped"
          height={216}
          valueFormatter={formatChartK}
          ariaLabel={`Planned budget versus allocated spend by category for ${period}`}
        />
      </VStack>
    </Card.Root>
  );
}

// ============= MAIN COMPONENT =============

export interface PortfolioDashboardProps extends StyleOverrideProps {}

/**
 * PortfolioDashboard — treasury & infrastructure budget portfolio screen powered
 * by UI SDK Chart primitives: period switcher, KPI summary tiles, historical
 * reserve value area chart paired with top allocation slices, category-bar
 * allocation breakdown, grouped budget-vs-actual bars, operational rate
 * sparkline cards, and a searchable, sortable cost-center breakdown table.
 */
export function PortfolioDashboard({ palette, style }: PortfolioDashboardProps) {
  const queue = useMemo(() => Toast.createToaster(), []);
  const [period, setPeriod] = useState<PeriodKey>("1Y");
  const [categoryFilter, setCategoryFilter] = useState<CategoryKey | "all">("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [sortField, setSortField] = useState<SortField>("allocatedK");
  const [sortDir, setSortDir] = useState<SortDir>("desc");

  const config = PERIOD_CONFIGS[period];

  const reserveChartData = useMemo(
    () =>
      config.curve.map((pt) => ({
        label: pt.label,
        "Reserve Value": pt.actual,
        "Target Plan": pt.benchmark,
      })),
    [config.curve],
  );

  const periodSlices = useMemo<AllocationSlice[]>(
    () =>
      BASE_SLICES.map((slice) => ({
        ...slice,
        budgetK: Math.round(slice.budgetK * config.budgetScale),
        periodChangePct: Number((slice.periodChangePct * config.changeScale).toFixed(1)),
      })),
    [config.budgetScale, config.changeScale],
  );

  const filteredRows = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    const rows = COST_CENTERS.map((row) => ({
      ...row,
      sharePct: (row.allocatedK / TOTAL_RESERVE_K) * 100,
      scaledChangePct: Number((row.periodChangePct * config.changeScale).toFixed(1)),
    })).filter((row) => {
      if (categoryFilter !== "all" && row.category !== categoryFilter) {
        return false;
      }
      if (!q) return true;
      const sliceLabel = SLICE_BY_KEY.get(row.category)?.label.toLowerCase() ?? "";
      return (
        row.code.toLowerCase().includes(q) ||
        row.name.toLowerCase().includes(q) ||
        row.region.toLowerCase().includes(q) ||
        sliceLabel.includes(q)
      );
    });

    rows.sort((a, b) => {
      const mul = sortDir === "asc" ? 1 : -1;
      if (sortField === "name") {
        return a.name.localeCompare(b.name) * mul;
      }
      if (sortField === "allocatedK") {
        return (a.allocatedK - b.allocatedK) * mul;
      }
      if (sortField === "sharePct") {
        return (a.sharePct - b.sharePct) * mul;
      }
      if (sortField === "periodChangePct") {
        return (a.scaledChangePct - b.scaledChangePct) * mul;
      }
      return (a.driftPct - b.driftPct) * mul;
    });

    return rows;
  }, [categoryFilter, searchQuery, sortField, sortDir, config.changeScale]);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortDir(field === "name" ? "asc" : "desc");
    }
  };

  const toggleCategoryFilter = (cat: CategoryKey) => {
    setCategoryFilter((prev) => (prev === cat ? "all" : cat));
  };

  const maxRowAllocation = Math.max(...COST_CENTERS.map((r) => r.allocatedK));

  return (
    <div {...stylex.props(styles.root, palette, style)}>
      <VStack render={<main />} gap="6" style={styles.content}>
        {/* Header bar */}
        <Stack
          render={<header />}
          justify="between"
          wrap="wrap"
          gap="4"
          style={styles.headerBar}
        >
          <VStack gap="1">
            <Heading render={<h1 />} size="2xl" style={styles.pageHeading}>
              Meridian Treasury
            </Heading>
            <HStack align="center" wrap="wrap" gap="2">
              <Text render={<span />} size="sm" tone="muted">
                Cloud &amp; Infrastructure Reserve Portfolio
              </Text>
              <Text render={<span />} size="sm" tone="muted" aria-hidden="true">
                ·
              </Text>
              <Text render={<span />} size="sm" tone="muted">
                {config.subtitle}
              </Text>
            </HStack>
          </VStack>

          <HStack align="center" wrap="wrap" gap="2.5">
            <SegmentGroup.Root
              size="sm"
              value={period}
              aria-label="Reporting period"
              onValueChange={(next) => {
                if (next === "1M" || next === "3M" || next === "YTD" || next === "1Y") {
                  setPeriod(next);
                }
              }}
            >
              <SegmentGroup.Item value="1M">1M</SegmentGroup.Item>
              <SegmentGroup.Item value="3M">3M</SegmentGroup.Item>
              <SegmentGroup.Item value="YTD">YTD</SegmentGroup.Item>
              <SegmentGroup.Item value="1Y">1Y</SegmentGroup.Item>
            </SegmentGroup.Root>

            <Button
              variant="surface"
              size="sm"
              onClick={() =>
                queue.info("Treasury snapshot exported", {
                  description: `${filteredRows.length} cost centers (${period}) packaged as CSV.`,
                })
              }
            >
              <DownloadIcon />
              Export
            </Button>

            <Button
              variant="solid"
              size="sm"
              palette={bluePalette}
              onClick={() =>
                queue.success("Rebalance proposal queued", {
                  description:
                    "Trimming AI Inference by $110k to replenish Storage and 90-day T-Bill liquidity.",
                })
              }
            >
              <RebalanceIcon />
              Rebalance
            </Button>
          </HStack>
        </Stack>

        {/* Row 1: KPI summary metrics */}
        <Grid render={<section aria-label="Portfolio headline metrics" />} columns="autoFit" gap="4">
          {config.kpis.map((kpi) => (
            <Card.Root key={kpi.key} variant="outline">
              <VStack gap="1" style={styles.metricBody}>
                <Stat.Root size="md">
                  <Stat.Label>{kpi.label}</Stat.Label>
                  <HStack align="baseline" wrap="wrap" gap="2">
                    <Stat.ValueText>{kpi.value}</Stat.ValueText>
                    <HStack render={<span />} align="center" gap="0.5">
                      <Text
                        render={<span />}
                        size="sm"
                        weight="medium"
                        tone={kpi.positive ? "success" : "error"}
                        style={styles.deltaIcon}
                      >
                        {kpi.positive ? <ArrowUpIcon /> : <ArrowDownIcon />}
                      </Text>
                      <Text render={<span />} size="sm" weight="medium" tone="muted" tabular="true">
                        {kpi.change}
                      </Text>
                    </HStack>
                  </HStack>
                  <Stat.HelpText>{kpi.helpText}</Stat.HelpText>
                </Stat.Root>
              </VStack>
            </Card.Root>
          ))}
        </Grid>

        {/* Row 2: Historical Reserve Value Curve + Top Allocation Slices */}
        <Grid
          render={<section aria-label="Reserve performance and top allocations" />}
          gap="4"
          style={styles.heroSplit}
        >
          <Card.Root variant="outline">
            <VStack gap="4" style={styles.cardInner}>
              <HStack justify="between" align="center" wrap="wrap" gap="2">
                <VStack gap="0.5">
                  <Heading render={<h2 />} size="md" style={styles.sectionHeading}>
                    Reserve Value
                  </Heading>
                  <Text size="xs" tone="muted">
                    Allocated infrastructure value vs. quarterly target plan ({period})
                  </Text>
                </VStack>
                <Link
                  href="#reserve-ledger"
                  onClick={(e) => {
                    e.preventDefault();
                    queue.info("Reserve ledger audit", {
                      description: `Showing reconciled daily reserve balances for ${period}.`,
                    });
                  }}
                >
                  View ledger
                </Link>
              </HStack>

              <AreaChart
                data={reserveChartData}
                index="label"
                categories={["Reserve Value", "Target Plan"]}
                colors={["emerald", "slate"]}
                height={292}
                curve="linear"
                valueFormatter={formatChartK}
                ariaLabel={`Meridian Treasury reserve value curve over ${config.key}`}
              />
            </VStack>
          </Card.Root>

          <Card.Root variant="outline">
            <VStack gap="4" style={styles.cardInner}>
              <HStack justify="between" align="center" wrap="wrap" gap="2">
                <VStack gap="0.5">
                  <Heading render={<h2 />} size="md" style={styles.sectionHeading}>
                    Top Allocations
                  </Heading>
                  <Text size="xs" tone="muted">
                    Click a slice to filter cost centers
                  </Text>
                </VStack>
                {categoryFilter !== "all" ? (
                  <Link
                    href="#clear-slice"
                    onClick={(e) => {
                      e.preventDefault();
                      setCategoryFilter("all");
                    }}
                  >
                    Show all
                  </Link>
                ) : (
                  <Link
                    href="#rebalance-targets"
                    onClick={(e) => {
                      e.preventDefault();
                      queue.info("Policy weights", {
                        description: "Target weights are reviewed at the close of each quarter.",
                      });
                    }}
                  >
                    Targets
                  </Link>
                )}
              </HStack>

              <VStack gap="1.5">
                {periodSlices.map((slice) => {
                  const sharePct = ((slice.allocatedK / TOTAL_RESERVE_K) * 100).toFixed(1);
                  const isActive = categoryFilter === slice.key;
                  const isPositive = slice.periodChangePct >= 0;
                  return (
                    <button
                      key={slice.key}
                      type="button"
                      aria-pressed={isActive}
                      onClick={() => toggleCategoryFilter(slice.key)}
                      {...stylex.props(styles.sliceButton, isActive && styles.sliceButtonActive)}
                    >
                      <HStack align="center" gap="2.5">
                        <Avatar.Root
                          size="sm"
                          shape="rounded"
                          variant="subtle"
                          palette={TONE_PALETTE[slice.tone]}
                        >
                          <Avatar.Fallback>
                            <span {...stylex.props(styles.avatarCode)}>{slice.code}</span>
                          </Avatar.Fallback>
                        </Avatar.Root>
                        <VStack gap="0">
                          <Text render={<span />} size="sm" weight="medium" truncate="true">
                            {slice.label}
                          </Text>
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            tone="muted"
                            tabular="true"
                          >
                            {sharePct}% · target {slice.targetPct}%
                          </Text>
                        </VStack>
                      </HStack>

                      <VStack align="end" gap="0.5" style={styles.sliceEnd}>
                        <Text
                          render={<span />}
                          variant="mono"
                          size="sm"
                          weight="semibold"
                          tabular="true"
                        >
                          {formatK(slice.allocatedK)}
                        </Text>
                        <Badge
                          size="xs"
                          variant="subtle"
                          palette={isPositive ? greenPalette : redPalette}
                        >
                          {formatSignedPct(slice.periodChangePct)}
                        </Badge>
                      </VStack>
                    </button>
                  );
                })}
              </VStack>
            </VStack>
          </Card.Root>
        </Grid>

        {/* Row 3: CategoryBar Allocation Breakdown + Grouped Budget vs. Actual Bars */}
        <Grid
          render={<section aria-label="Allocation breakdown and budget comparison" />}
          gap="4"
          style={styles.twoColGrid}
        >
          <AllocationStackedBarCard
            slices={periodSlices}
            onSelectCategory={toggleCategoryFilter}
          />
          <CategoryComparisonCard slices={periodSlices} period={period} />
        </Grid>

        <Separator />

        {/* Row 4: Infrastructure Rate Pulse (sparkline index cards) */}
        <section aria-label="Infrastructure rate benchmarks">
          <HStack justify="between" align="center" wrap="wrap" gap="3">
            <VStack gap="0.5">
              <Heading render={<h2 />} size="lg" style={styles.sectionHeading}>
                Rate Benchmarks
              </Heading>
              <Text size="xs" tone="muted">
                Unit-cost telemetry and liquidity yield over the trailing 30 days
              </Text>
            </VStack>
            <Button
              variant="surface"
              size="sm"
              onClick={() =>
                queue.info("Benchmark feed synced", {
                  description: "All 6 infrastructure unit-cost feeds are up to date.",
                })
              }
            >
              Sync rates
            </Button>
          </HStack>
        </section>

        <Grid
          render={<section aria-label="Rate benchmark cards" />}
          gap="4"
          style={styles.pulseGrid}
        >
          {PULSE_BENCHMARKS.map((item) => (
            <Card.Root key={item.id} variant="outline">
              <VStack gap="2.5" style={styles.pulseBody}>
                <VStack gap="0">
                  <Text render={<span />} size="sm" weight="semibold">
                    {item.name}
                  </Text>
                  <Text render={<span />} variant="mono" size="xs" tone="muted">
                    {item.ticker}
                  </Text>
                </VStack>
                <Sparkline
                  data={item.sparkData}
                  categories={["value"]}
                  colors={[item.positive ? "emerald" : "rose"]}
                  height={38}
                  curve="linear"
                  ariaLabel={`${item.name} trend`}
                />
                <HStack justify="between" align="baseline" wrap="wrap" gap="2">
                  <Text
                    render={<span />}
                    variant="mono"
                    size="md"
                    weight="semibold"
                    tabular="true"
                  >
                    {item.reading}
                  </Text>
                  <HStack render={<span />} align="center" gap="0.5">
                    <Text
                      render={<span />}
                      size="sm"
                      weight="medium"
                      tone={item.positive ? "success" : "error"}
                      style={styles.deltaIcon}
                    >
                      {item.change.startsWith("-") ? <ArrowDownIcon /> : <ArrowUpIcon />}
                    </Text>
                    <Text render={<span />} size="sm" weight="medium" tone="muted" tabular="true">
                      {item.change}
                    </Text>
                  </HStack>
                </HStack>
              </VStack>
            </Card.Root>
          ))}
        </Grid>

        {/* Row 5: Filterable & Sortable Cost-Center Breakdown Table */}
        <section aria-label="Cost center breakdown">
          <Card.Root variant="outline">
            <VStack gap="4" style={styles.cardInner}>
              <HStack justify="between" align="center" wrap="wrap" gap="2">
                <VStack gap="0.5">
                  <Heading render={<h2 />} size="md" style={styles.sectionHeading}>
                    Cost-Center Holdings
                  </Heading>
                  <Text size="xs" tone="muted">
                    Showing {filteredRows.length} of {COST_CENTERS.length} active reserve
                    allocations
                  </Text>
                </VStack>

                <HStack align="center" wrap="wrap" gap="2.5">
                  <div {...stylex.props(styles.searchWrap)}>
                    <SearchIcon style={styles.searchIcon} />
                    <Input
                      size="sm"
                      variant="outline"
                      type="search"
                      aria-label="Filter cost centers by code, name, or region"
                      placeholder="Filter cost centers…"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      style={styles.searchInput}
                    />
                  </div>

                  <NativeSelect.Root size="sm" variant="outline" style={styles.selectWrap}>
                    <NativeSelect.Field
                      aria-label="Filter by reserve slice"
                      value={categoryFilter}
                      onChange={(e) =>
                        setCategoryFilter(e.target.value as CategoryKey | "all")
                      }
                    >
                      <option value="all">All slices</option>
                      {BASE_SLICES.map((slice) => (
                        <option key={slice.key} value={slice.key}>
                          {slice.label}
                        </option>
                      ))}
                    </NativeSelect.Field>
                    <NativeSelect.Indicator />
                  </NativeSelect.Root>
                </HStack>
              </HStack>

              {filteredRows.length === 0 ? (
                <VStack align="center" gap="2.5" style={styles.emptyState}>
                  <Text size="sm" tone="muted">
                    No cost centers match the current filter criteria.
                  </Text>
                  <Button
                    variant="surface"
                    size="sm"
                    onClick={() => {
                      setSearchQuery("");
                      setCategoryFilter("all");
                    }}
                  >
                    Clear filters
                  </Button>
                </VStack>
              ) : (
                <div {...stylex.props(styles.tableScroll)}>
                  <Table.Root size="sm">
                    <Table.Header>
                      <Table.Row>
                        <Table.ColumnHeader
                          aria-sort={
                            sortField === "name"
                              ? sortDir === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("name")}
                            {...stylex.props(styles.sortButton)}
                          >
                            Cost Center
                            <SortIcon active={sortField === "name"} dir={sortDir} />
                          </button>
                        </Table.ColumnHeader>
                        <Table.ColumnHeader>Slice</Table.ColumnHeader>
                        <Table.ColumnHeader
                          aria-sort={
                            sortField === "allocatedK"
                              ? sortDir === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("allocatedK")}
                            {...stylex.props(styles.sortButton)}
                          >
                            Allocation
                            <SortIcon active={sortField === "allocatedK"} dir={sortDir} />
                          </button>
                        </Table.ColumnHeader>
                        <Table.ColumnHeader
                          aria-sort={
                            sortField === "sharePct"
                              ? sortDir === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("sharePct")}
                            {...stylex.props(styles.sortButton)}
                          >
                            Reserve Share
                            <SortIcon active={sortField === "sharePct"} dir={sortDir} />
                          </button>
                        </Table.ColumnHeader>
                        <Table.ColumnHeader
                          aria-sort={
                            sortField === "periodChangePct"
                              ? sortDir === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("periodChangePct")}
                            {...stylex.props(styles.sortButton)}
                          >
                            {period} Chg
                            <SortIcon active={sortField === "periodChangePct"} dir={sortDir} />
                          </button>
                        </Table.ColumnHeader>
                        <Table.ColumnHeader
                          aria-sort={
                            sortField === "driftPct"
                              ? sortDir === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("driftPct")}
                            {...stylex.props(styles.sortButton)}
                          >
                            Target Drift
                            <SortIcon active={sortField === "driftPct"} dir={sortDir} />
                          </button>
                        </Table.ColumnHeader>
                        <Table.ColumnHeader>Trend</Table.ColumnHeader>
                      </Table.Row>
                    </Table.Header>
                    <Table.Body>
                      {filteredRows.map((row) => {
                        const slice = SLICE_BY_KEY.get(row.category);
                        const sliceTone = slice?.tone ?? "blue";
                        const driftAbs = Math.abs(row.driftPct);
                        const driftPalette =
                          driftAbs >= 1.5
                            ? redPalette
                            : driftAbs >= 0.7
                              ? amberPalette
                              : greenPalette;

                        return (
                          <Table.Row key={row.id}>
                            <Table.Cell>
                              <VStack gap="0">
                                <HStack align="center" gap="2">
                                  <Text render={<span />} variant="mono" size="xs" weight="semibold">
                                    {row.code}
                                  </Text>
                                  <Text render={<span />} size="sm" weight="medium">
                                    {row.name}
                                  </Text>
                                </HStack>
                                <Text render={<span />} size="xs" tone="muted">
                                  {row.region}
                                </Text>
                              </VStack>
                            </Table.Cell>
                            <Table.Cell>
                              <Badge
                                size="sm"
                                variant="subtle"
                                palette={TONE_PALETTE[sliceTone]}
                              >
                                {slice?.label ?? row.category}
                              </Badge>
                            </Table.Cell>
                            <Table.Cell>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                weight="medium"
                                tabular="true"
                              >
                                {formatK(row.allocatedK)}
                              </Text>
                            </Table.Cell>
                            <Table.Cell>
                              <VStack gap="1" style={styles.progressCell}>
                                <Progress.Root
                                  value={row.allocatedK}
                                  max={maxRowAllocation}
                                  size="xs"
                                  palette={TONE_PALETTE[sliceTone]}
                                  aria-label={`${row.name} share of reserve`}
                                >
                                  <Progress.Track>
                                    <Progress.Range />
                                  </Progress.Track>
                                </Progress.Root>
                                <Text render={<span />} size="xs" tone="muted" tabular="true">
                                  {row.sharePct.toFixed(1)}%
                                </Text>
                              </VStack>
                            </Table.Cell>
                            <Table.Cell>
                              <Badge
                                size="sm"
                                variant="subtle"
                                palette={row.scaledChangePct >= 0 ? greenPalette : redPalette}
                              >
                                {formatSignedPct(row.scaledChangePct)}
                              </Badge>
                            </Table.Cell>
                            <Table.Cell>
                              <Badge size="sm" variant="subtle" palette={driftPalette}>
                                {row.driftPct >= 0 ? "+" : ""}
                                {row.driftPct.toFixed(1)} pts
                              </Badge>
                            </Table.Cell>
                            <Table.Cell>
                              <div {...stylex.props(styles.sparkCellHost)}>
                                <Sparkline
                                  data={row.sparkData}
                                  categories={["value"]}
                                  colors={[row.scaledChangePct >= 0 ? "emerald" : "rose"]}
                                  height={24}
                                  curve="linear"
                                  ariaLabel={`${row.name} trend`}
                                />
                              </div>
                            </Table.Cell>
                          </Table.Row>
                        );
                      })}
                    </Table.Body>
                  </Table.Root>
                </div>
              )}
            </VStack>
          </Card.Root>
        </section>
      </VStack>

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

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