---
title: "Inbox Table · UI SDK — StyleX Blocks"
description: "Two-pane resizable partner support and security triage queue pairing an adaptive container-query inbox table—with folder scope controls, search, bulk selection ActionBar, unread indicators, star toggles, and hover quick-actions—with a collapsible message thread reader and live reply / internal-note composer."
url: "https://stylexblocks.com/block/ui-sdk/inbox-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/"
---

# Inbox Table block

Two-pane resizable partner support and security triage queue pairing an adaptive container-query inbox table—with folder scope controls, search, bulk selection ActionBar, unread indicators, star toggles, and hover quick-actions—with a collapsible message thread reader and live reply / internal-note composer.

- Behavior engine: UI SDK
- Category: [Data tables](https://stylexblocks.com/blocks/tables.md)
- Built with: [Action Bar](https://stylexblocks.com/components/ui-sdk/action-bar.md), [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), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Collapsible](https://stylexblocks.com/components/ui-sdk/collapsible.md), [Empty State](https://stylexblocks.com/components/ui-sdk/empty-state.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [Select](https://stylexblocks.com/components/ui-sdk/select.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Splitter](https://stylexblocks.com/components/ui-sdk/splitter.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [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), [Textarea](https://stylexblocks.com/components/ui-sdk/textarea.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/inbox-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 inbox-table
```

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

## Usage

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

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

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActionBar } from "#components/ui/ui-sdk/action-bar.tsx";
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 { Center } from "#components/ui/ui-sdk/center.tsx";
import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";
import { Collapsible } from "#components/ui/ui-sdk/collapsible.tsx";
import { EmptyState } from "#components/ui/ui-sdk/empty-state.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { Icon } from "#components/ui/ui-sdk/icon.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";
import { Select } from "#components/ui/ui-sdk/select.tsx";
import { Separator } from "#components/ui/ui-sdk/separator.tsx";
import { Splitter } from "#components/ui/ui-sdk/splitter.tsx";
import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { 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 { Textarea } from "#components/ui/ui-sdk/textarea.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 {
  accentPalette,
  amberPalette,
  bluePalette,
  cyanPalette,
  grayPalette,
  greenPalette,
  indigoPalette,
  orangePalette,
  purplePalette,
  redPalette,
  rosePalette,
  tealPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { durations } from "@stylexblocks/ui/tokens/durations.stylex.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";
import { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

const NARROW_SURFACE = "@container inbox-table (max-width: 860px)";
const QUEUE_MEDIUM = "@container inbox-queue (max-width: 680px)";
const QUEUE_COMPACT = "@container inbox-queue (max-width: 500px)";
const COMPOSER_COMPACT = "@container inbox-reader (max-width: 520px)";

export type ThreadPriority = "urgent" | "high" | "normal";
export type ThreadStatus = "open" | "waiting" | "resolved" | "archived";
export type QueueFolder = "all" | "unread" | "starred" | "snoozed";
type StatusFilter = "active" | ThreadStatus;
type ComposerMode = "reply" | "note";
type AvatarTone =
  | "indigo"
  | "teal"
  | "purple"
  | "blue"
  | "orange"
  | "green"
  | "rose"
  | "cyan";

export interface ThreadAttachment {
  id: string;
  name: string;
  sizeLabel: string;
}

export interface ThreadMessage {
  id: string;
  author: string;
  authorEmail: string;
  authorInitials: string;
  authorTone: AvatarTone;
  isTeam: boolean;
  isInternalNote?: boolean;
  sentAt: string;
  body: string[];
  attachments?: ThreadAttachment[];
}

export interface InboxThread {
  id: string;
  ticketNumber: string;
  sender: string;
  senderEmail: string;
  senderOrg: string;
  senderInitials: string;
  senderTone: AvatarTone;
  subject: string;
  preview: string;
  labels: string[];
  priority: ThreadPriority;
  status: ThreadStatus;
  assignee: string | null;
  isUnread: boolean;
  isStarred: boolean;
  isSnoozed: boolean;
  updatedAt: string;
  messages: ThreadMessage[];
}

const ASSIGNEES = [
  "Unassigned",
  "Clara Reyes",
  "Toby Lind",
  "Rohan Patel",
  "You (Desk Lead)",
] as const;

const PRIORITY_LABEL: Record<ThreadPriority, string> = {
  urgent: "Urgent",
  high: "High",
  normal: "Normal",
};

const PRIORITY_PALETTE = {
  urgent: redPalette,
  high: amberPalette,
  normal: grayPalette,
} as const;

const STATUS_LABEL: Record<ThreadStatus, string> = {
  open: "Open",
  waiting: "Waiting",
  resolved: "Resolved",
  archived: "Archived",
};

const STATUS_PALETTE = {
  open: bluePalette,
  waiting: amberPalette,
  resolved: greenPalette,
  archived: grayPalette,
} as const;

const AVATAR_PALETTE = {
  indigo: indigoPalette,
  teal: tealPalette,
  purple: purplePalette,
  blue: bluePalette,
  orange: orangePalette,
  green: greenPalette,
  rose: rosePalette,
  cyan: cyanPalette,
} as const;

const LABEL_PALETTES: Record<string, typeof grayPalette> = {
  Security: redPalette,
  Webhooks: indigoPalette,
  Identity: purplePalette,
  SSO: purplePalette,
  API: bluePalette,
  "Rate Limits": orangePalette,
  Billing: tealPalette,
  Compliance: cyanPalette,
  Migration: bluePalette,
  Exports: greenPalette,
  Bug: rosePalette,
  Ops: grayPalette,
  Network: cyanPalette,
};

const STATUS_FILTER_OPTIONS: Array<{ value: StatusFilter; label: string }> = [
  { value: "active", label: "Active queue" },
  { value: "open", label: "Open" },
  { value: "waiting", label: "Waiting" },
  { value: "resolved", label: "Resolved" },
  { value: "archived", label: "Archived" },
];

const THREAD_STATUS_OPTIONS: Array<{ value: ThreadStatus; label: string }> = [
  { value: "open", label: "Open" },
  { value: "waiting", label: "Waiting" },
  { value: "resolved", label: "Resolved" },
  { value: "archived", label: "Archived" },
];

const PRIORITY_OPTIONS: Array<{ value: ThreadPriority; label: string }> = [
  { value: "urgent", label: "Urgent" },
  { value: "high", label: "High" },
  { value: "normal", label: "Normal" },
];

const INITIAL_THREADS: InboxThread[] = [
  {
    id: "thr-1042",
    ticketNumber: "ND-1042",
    sender: "Camille Laurent",
    senderEmail: "c.laurent@veridianpay.io",
    senderOrg: "Veridian Pay",
    senderInitials: "CL",
    senderTone: "indigo",
    subject: "Webhook HMAC-SHA256 signature mismatch after key rotation",
    preview:
      "After enabling dual-key rotation in eu-west-2, roughly 18% of settlement webhooks fail signature validation.",
    labels: ["Webhooks", "Security"],
    priority: "urgent",
    status: "open",
    assignee: "Clara Reyes",
    isUnread: true,
    isStarred: true,
    isSnoozed: false,
    updatedAt: "9:48 AM",
    messages: [
      {
        id: "m-1042-1",
        author: "Camille Laurent",
        authorEmail: "c.laurent@veridianpay.io",
        authorInitials: "CL",
        authorTone: "indigo",
        isTeam: false,
        sentAt: "Today, 9:12 AM",
        body: [
          "We triggered a scheduled webhook signing-key rotation on our eu-west-2 settlement listener at 08:45 UTC with the 24-hour overlap flag enabled.",
          "Since then, about one in five incoming payloads returns a digest that matches neither the primary nor the previous secret in our verifier.",
        ],
        attachments: [
          { id: "att-1042-1", name: "hmac-signature-trace.log", sizeLabel: "42 KB" },
        ],
      },
      {
        id: "m-1042-2",
        author: "Clara Reyes",
        authorEmail: "clara.reyes@northwind-dispatch.io",
        authorInitials: "CR",
        authorTone: "teal",
        isTeam: true,
        isInternalNote: true,
        sentAt: "Today, 9:29 AM",
        body: [
          "Checked dispatch-signer-eu2 logs: two worker pods held a stale secret cache until the 09:30 refresh tick, and they emitted the v2 header prefix with a trailing whitespace character in the timestamp field.",
        ],
      },
      {
        id: "m-1042-3",
        author: "Camille Laurent",
        authorEmail: "c.laurent@veridianpay.io",
        authorInitials: "CL",
        authorTone: "indigo",
        isTeam: false,
        sentAt: "Today, 9:48 AM",
        body: [
          "Adding another sample from 09:41 UTC — the X-Northwind-Signature header now lists two comma-separated v1 digests, and both fail when we hash the raw body.",
          "Could you confirm whether the canonical timestamp delimiter changed between key versions, or if an edge worker is still serving the retired secret?",
        ],
        attachments: [
          { id: "att-1042-2", name: "raw-webhook-headers.txt", sizeLabel: "8 KB" },
        ],
      },
    ],
  },
  {
    id: "thr-1041",
    ticketNumber: "ND-1041",
    sender: "Henrik Solberg",
    senderEmail: "h.solberg@fjordbank.no",
    senderOrg: "FjordBank",
    senderInitials: "HS",
    senderTone: "blue",
    subject: "SAML 2.0 SSO IdP metadata certificate rotation window",
    preview:
      "Can we coordinate a 15-minute live cutover Thursday at 06:00 UTC and verify the SHA-256 thumbprint beforehand?",
    labels: ["Identity", "SSO"],
    priority: "high",
    status: "open",
    assignee: "Toby Lind",
    isUnread: true,
    isStarred: true,
    isSnoozed: false,
    updatedAt: "9:21 AM",
    messages: [
      {
        id: "m-1041-1",
        author: "Henrik Solberg",
        authorEmail: "h.solberg@fjordbank.no",
        authorInitials: "HS",
        authorTone: "blue",
        isTeam: false,
        sentAt: "Yesterday, 4:10 PM",
        body: [
          "Our Entra ID signing certificate for FjordBank's production tenant expires on November 27. We have staged the replacement X.509 certificate in our secondary metadata feed.",
          "Please confirm whether Northwind Dispatch supports dual active IdP certificates simultaneously so our 1,400 analysts experience zero sign-in interruption.",
        ],
        attachments: [
          { id: "att-1041-1", name: "fjordbank-idp-2026.xml", sizeLabel: "19 KB" },
        ],
      },
      {
        id: "m-1041-2",
        author: "Toby Lind",
        authorEmail: "toby.lind@northwind-dispatch.io",
        authorInitials: "TL",
        authorTone: "purple",
        isTeam: true,
        sentAt: "Today, 8:35 AM",
        body: [
          "Hi Henrik — yes, we accept up to two active X.509 signing certificates per SAML connection during rotation.",
          "I have pre-validated your uploaded XML against our staging SP and confirmed the SHA-256 thumbprint ends in 9E:44:C2. Let us know your preferred cutover window.",
        ],
      },
      {
        id: "m-1041-3",
        author: "Henrik Solberg",
        authorEmail: "h.solberg@fjordbank.no",
        authorInitials: "HS",
        authorTone: "blue",
        isTeam: false,
        sentAt: "Today, 9:21 AM",
        body: [
          "Thumbprint 9E:44:C2 matches our HSM export. Let us lock Thursday at 06:00 UTC for the primary switch and keep the retiring certificate active for 48 hours after cutover.",
          "Can you keep an engineer on standby in this thread during that 15-minute window?",
        ],
      },
    ],
  },
  {
    id: "thr-1040",
    ticketNumber: "ND-1040",
    sender: "Kenji Watanabe",
    senderEmail: "k.watanabe@soralogistics.jp",
    senderOrg: "Sora Logistics",
    senderInitials: "KW",
    senderTone: "orange",
    subject: "Burst 429 rate-limit spike on /v2/events/batch endpoint",
    preview:
      "Retry-After headers jumped to 90s during Tokyo morning dispatch even though we stayed under 450 req/min.",
    labels: ["API", "Rate Limits"],
    priority: "urgent",
    status: "open",
    assignee: null,
    isUnread: true,
    isStarred: false,
    isSnoozed: false,
    updatedAt: "8:54 AM",
    messages: [
      {
        id: "m-1040-1",
        author: "Kenji Watanabe",
        authorEmail: "k.watanabe@soralogistics.jp",
        authorInitials: "KW",
        authorTone: "orange",
        isTeam: false,
        sentAt: "Today, 8:20 AM",
        body: [
          "At 00:05 UTC (09:05 JST), our telemetry ingestor began receiving 429 responses on POST /v2/events/batch.",
          "Our Enterprise contract includes 600 requests/min with a 150-request burst bucket, yet our Prometheus counter never crossed 438 requests/min.",
        ],
        attachments: [
          { id: "att-1040-1", name: "batch-429-window.json", sizeLabel: "64 KB" },
        ],
      },
      {
        id: "m-1040-2",
        author: "Kenji Watanabe",
        authorEmail: "k.watanabe@soralogistics.jp",
        authorInitials: "KW",
        authorTone: "orange",
        isTeam: false,
        sentAt: "Today, 8:54 AM",
        body: [
          "Update: we noticed each batch payload contained 250 sub-events. Is the token bucket now metering per-event units rather than per-HTTP-request?",
          "We temporarily halved our batch size to 100 and errors dropped by 60%, so an urgent clarification on the quota formula would help us stabilize dispatch.",
        ],
      },
    ],
  },
  {
    id: "thr-1039",
    ticketNumber: "ND-1039",
    sender: "Beatriz Alencar",
    senderEmail: "finance@cajuhealth.com.br",
    senderOrg: "Caju Health",
    senderInitials: "BA",
    senderTone: "teal",
    subject: "Q4 enterprise invoice seat reconciliation & proration credit",
    preview:
      "We decommissioned 34 contractor accounts on Oct 12, but invoice #NW-8841 still reflects the September peak.",
    labels: ["Billing"],
    priority: "high",
    status: "waiting",
    assignee: "Rohan Patel",
    isUnread: true,
    isStarred: false,
    isSnoozed: false,
    updatedAt: "8:16 AM",
    messages: [
      {
        id: "m-1039-1",
        author: "Beatriz Alencar",
        authorEmail: "finance@cajuhealth.com.br",
        authorInitials: "BA",
        authorTone: "teal",
        isTeam: false,
        sentAt: "Yesterday, 2:45 PM",
        body: [
          "Hello Billing Desk — our AP audit flagged invoice #NW-8841 for 214 active seats, whereas our SCIM directory exported 180 provisioned users after October 12.",
          "Attached is our signed Okta deactivation report. Could you issue a credit memo before our Friday payment batch?",
        ],
        attachments: [
          { id: "att-1039-1", name: "q4-seat-ledger.csv", sizeLabel: "28 KB" },
        ],
      },
      {
        id: "m-1039-2",
        author: "Rohan Patel",
        authorEmail: "rohan.patel@northwind-dispatch.io",
        authorInitials: "RP",
        authorTone: "cyan",
        isTeam: true,
        sentAt: "Yesterday, 5:18 PM",
        body: [
          "Thanks Beatriz. I confirmed the 34 accounts were suspended in Okta on October 12, but still held active API tokens so our metering job counted them as active service seats.",
          "Once your security admin revokes those tokens, I can apply the $3,910 proration credit directly to #NW-8841.",
        ],
      },
      {
        id: "m-1039-3",
        author: "Beatriz Alencar",
        authorEmail: "finance@cajuhealth.com.br",
        authorInitials: "BA",
        authorTone: "teal",
        isTeam: false,
        sentAt: "Today, 8:16 AM",
        body: [
          "Our IT lead just revoked all 34 contractor tokens (audit job #TOK-992). Please go ahead with the revised PDF invoice and credit memo whenever ready.",
        ],
      },
    ],
  },
  {
    id: "thr-1038",
    ticketNumber: "ND-1038",
    sender: "David Kowalski",
    senderEmail: "d.kowalski@ironcladbio.com",
    senderOrg: "Ironclad Bio",
    senderInitials: "DK",
    senderTone: "purple",
    subject: "Annual SOC 2 Type II bridge letter and SIG Lite questionnaire",
    preview:
      "Procurement needs the signed Q4 bridge letter plus section 7 encryption-at-rest answers for our renewal.",
    labels: ["Compliance", "Security"],
    priority: "normal",
    status: "open",
    assignee: "Clara Reyes",
    isUnread: false,
    isStarred: true,
    isSnoozed: false,
    updatedAt: "Yesterday",
    messages: [
      {
        id: "m-1038-1",
        author: "David Kowalski",
        authorEmail: "d.kowalski@ironcladbio.com",
        authorInitials: "DK",
        authorTone: "purple",
        isTeam: false,
        sentAt: "Mon, 11:04 AM",
        body: [
          "As part of Ironclad Bio's annual vendor security review, could you share your latest SOC 2 Type II report, Q4 bridge letter, and completed SIG Lite workbook?",
          "Our procurement gate closes December 5 so any early turnaround is appreciated.",
        ],
        attachments: [
          { id: "att-1038-1", name: "sig-lite-2026.xlsx", sizeLabel: "312 KB" },
        ],
      },
      {
        id: "m-1038-2",
        author: "Clara Reyes",
        authorEmail: "clara.reyes@northwind-dispatch.io",
        authorInitials: "CR",
        authorTone: "teal",
        isTeam: true,
        sentAt: "Mon, 3:40 PM",
        body: [
          "Hi David — I have granted your email access to our Trust Portal with the 2026 SOC 2 Type II audit report and latest penetration test executive summary.",
          "Our Security Assurance team is finalizing the SIG Lite responses and Q4 bridge letter now.",
        ],
      },
      {
        id: "m-1038-3",
        author: "David Kowalski",
        authorEmail: "d.kowalski@ironcladbio.com",
        authorInitials: "DK",
        authorTone: "purple",
        isTeam: false,
        sentAt: "Yesterday, 3:55 PM",
        body: [
          "Downloaded the SOC 2 package cleanly, thank you. One small follow-up for Section 7: please include the KMS key rotation cadence for EU replica buckets in the workbook notes.",
        ],
      },
    ],
  },
  {
    id: "thr-1037",
    ticketNumber: "ND-1037",
    sender: "Nadia Benali",
    senderEmail: "nadia@atlasfreight.eu",
    senderOrg: "Atlas Freight",
    senderInitials: "NB",
    senderTone: "cyan",
    subject: "Deprecation migration path for legacy /v1/webhooks/subscribe API",
    preview:
      "We still have 14 warehouse integrations pinned to v1. Does the v2 endpoint preserve custom retry headers?",
    labels: ["API", "Migration"],
    priority: "normal",
    status: "waiting",
    assignee: "You (Desk Lead)",
    isUnread: false,
    isStarred: false,
    isSnoozed: false,
    updatedAt: "Yesterday",
    messages: [
      {
        id: "m-1037-1",
        author: "Nadia Benali",
        authorEmail: "nadia@atlasfreight.eu",
        authorInitials: "NB",
        authorTone: "cyan",
        isTeam: false,
        sentAt: "Mon, 9:18 AM",
        body: [
          "We received the February sunset notice for /v1/webhooks/subscribe. Our regional ERP connectors rely on the legacy X-Retry-Attempt header to deduplicate customs events.",
          "Does /v2/subscriptions emit that same header, or do we need to parse delivery_attempt from the JSON envelope?",
        ],
      },
      {
        id: "m-1037-2",
        author: "You (Desk Lead)",
        authorEmail: "desk-lead@northwind-dispatch.io",
        authorInitials: "YD",
        authorTone: "green",
        isTeam: true,
        sentAt: "Yesterday, 1:12 PM",
        body: [
          "Hi Nadia — in v2, the attempt count is delivered in both the X-Northwind-Delivery-Attempt header and the envelope metadata. We can also enable a 60-day compatibility shim that mirrors X-Retry-Attempt while your connectors roll out.",
          "Reply with your workspace IDs if you would like us to activate the shim on staging first.",
        ],
      },
    ],
  },
  {
    id: "thr-1036",
    ticketNumber: "ND-1036",
    sender: "Lukas Weber",
    senderEmail: "l.weber@rheinwerk.de",
    senderOrg: "Rheinwerk Systems",
    senderInitials: "LW",
    senderTone: "green",
    subject: "EU-central data residency audit log export format inquiry",
    preview:
      "Our SIEM ingests NDJSON over S3. Can scheduled exports stay strictly within eu-central-1 Frankfurt?",
    labels: ["Compliance", "Exports"],
    priority: "normal",
    status: "open",
    assignee: null,
    isUnread: true,
    isStarred: false,
    isSnoozed: false,
    updatedAt: "Yesterday",
    messages: [
      {
        id: "m-1036-1",
        author: "Lukas Weber",
        authorEmail: "l.weber@rheinwerk.de",
        authorInitials: "LW",
        authorTone: "green",
        isTeam: false,
        sentAt: "Yesterday, 10:02 AM",
        body: [
          "We are preparing to pipe Northwind Dispatch audit logs into our Frankfurt SIEM cluster. The docs mention hourly CSV and NDJSON exports, but do not clarify whether the export worker ever stages files in us-east-1.",
        ],
      },
      {
        id: "m-1036-2",
        author: "Lukas Weber",
        authorEmail: "l.weber@rheinwerk.de",
        authorInitials: "LW",
        authorTone: "green",
        isTeam: false,
        sentAt: "Yesterday, 11:47 AM",
        body: [
          "Also, if we provide a customer-managed KMS ARN in eu-central-1, can the hourly export encrypt objects directly with our key before writing to the bucket?",
        ],
      },
    ],
  },
  {
    id: "thr-1035",
    ticketNumber: "ND-1035",
    sender: "Farah Al-Mansoor",
    senderEmail: "farah@crescentgrid.ae",
    senderOrg: "Crescent Grid",
    senderInitials: "FA",
    senderTone: "rose",
    subject: "Custom mTLS client certificate pinning on sandbox gateway",
    preview:
      "Waiting on our internal PKI team to re-issue the intermediate chain; let's revisit after Monday's test.",
    labels: ["Security", "Identity"],
    priority: "high",
    status: "waiting",
    assignee: "Toby Lind",
    isUnread: false,
    isStarred: false,
    isSnoozed: true,
    updatedAt: "Tue",
    messages: [
      {
        id: "m-1035-1",
        author: "Farah Al-Mansoor",
        authorEmail: "farah@crescentgrid.ae",
        authorInitials: "FA",
        authorTone: "rose",
        isTeam: false,
        sentAt: "Mon, 1:30 PM",
        body: [
          "Our sandbox mTLS handshakes are failing with SSL_ERROR_BAD_CERT_ALERT after we uploaded our private root CA bundle.",
          "Could you check whether the gateway expects the full intermediate chain in PEM order leaf-to-root?",
        ],
      },
      {
        id: "m-1035-2",
        author: "Toby Lind",
        authorEmail: "toby.lind@northwind-dispatch.io",
        authorInitials: "TL",
        authorTone: "purple",
        isTeam: true,
        sentAt: "Tue, 10:15 AM",
        body: [
          "Confirmed — the trust store needs the intermediate CA concatenated right above the root CA, and the leaf cert must include Extended Key Usage: clientAuth.",
          "Snoozing this thread until Monday while your PKI team re-issues the bundle.",
        ],
      },
    ],
  },
  {
    id: "thr-1034",
    ticketNumber: "ND-1034",
    sender: "Owen McAllister",
    senderEmail: "omcallister@caledoniacapital.co.uk",
    senderOrg: "Caledonia Capital",
    senderInitials: "OM",
    senderTone: "indigo",
    subject: "SCIM 2.0 group deprovisioning leaving orphaned read-only tokens",
    preview:
      "Removing a user from the Dispatch-Auditors group revoked UI access, yet personal API keys stayed active for 4h.",
    labels: ["Identity", "Bug"],
    priority: "high",
    status: "open",
    assignee: "Clara Reyes",
    isUnread: false,
    isStarred: true,
    isSnoozed: false,
    updatedAt: "Tue",
    messages: [
      {
        id: "m-1034-1",
        author: "Owen McAllister",
        authorEmail: "omcallister@caledoniacapital.co.uk",
        authorInitials: "OM",
        authorTone: "indigo",
        isTeam: false,
        sentAt: "Mon, 4:05 PM",
        body: [
          "During our quarterly offboarding drill, we removed a test user from our SCIM-synced Dispatch-Auditors group. Browser sessions terminated immediately, but a read-only PAT continued returning 200 OK for nearly four hours.",
        ],
        attachments: [
          { id: "att-1034-1", name: "scim-audit-diff.json", sizeLabel: "14 KB" },
        ],
      },
      {
        id: "m-1034-2",
        author: "Clara Reyes",
        authorEmail: "clara.reyes@northwind-dispatch.io",
        authorInitials: "CR",
        authorTone: "teal",
        isTeam: true,
        isInternalNote: true,
        sentAt: "Tue, 9:05 AM",
        body: [
          "Reproduced in staging: PATCH /scim/v2/Groups/{id} invalidates session cookies immediately, whereas PAT revocation runs on the 4-hour permission-cache sweep unless the user itself is set active=false.",
        ],
      },
      {
        id: "m-1034-3",
        author: "Clara Reyes",
        authorEmail: "clara.reyes@northwind-dispatch.io",
        authorInitials: "CR",
        authorTone: "teal",
        isTeam: true,
        sentAt: "Tue, 11:22 AM",
        body: [
          "Hi Owen — great catch. We confirmed group-membership removals were waiting for the periodic PAT scope cache TTL rather than pushing an immediate invalidation event.",
          "Identity engineering has a hotfix queued for today's 17:00 UTC release; I will follow up as soon as it is live on your tenant.",
        ],
      },
    ],
  },
  {
    id: "thr-1033",
    ticketNumber: "ND-1033",
    sender: "Mei-Hua Chen",
    senderEmail: "meihua@pacificport.sg",
    senderOrg: "PacificPort",
    senderInitials: "MC",
    senderTone: "teal",
    subject: "Dedicated IP egress allowlist additions for ap-southeast-1 failover",
    preview:
      "Both new Singapore static NAT CIDRs are live on our firewall and passing synthetic health probes.",
    labels: ["Ops", "Network"],
    priority: "normal",
    status: "resolved",
    assignee: "Rohan Patel",
    isUnread: false,
    isStarred: false,
    isSnoozed: false,
    updatedAt: "Mon",
    messages: [
      {
        id: "m-1033-1",
        author: "Mei-Hua Chen",
        authorEmail: "meihua@pacificport.sg",
        authorInitials: "MC",
        authorTone: "teal",
        isTeam: false,
        sentAt: "Mon, 7:15 AM",
        body: [
          "We are standing up an active-passive failover cluster in Singapore and need the official static egress IPv4 ranges for ap-southeast-1 webhook delivery.",
        ],
      },
      {
        id: "m-1033-2",
        author: "Rohan Patel",
        authorEmail: "rohan.patel@northwind-dispatch.io",
        authorInitials: "RP",
        authorTone: "cyan",
        isTeam: true,
        sentAt: "Mon, 8:02 AM",
        body: [
          "Hi Mei-Hua — our dedicated ap-southeast-1 egress blocks are 203.0.113.128/28 and 198.51.100.64/28. I also triggered a synthetic ping suite against your staging webhook URL once you apply the ACL.",
        ],
      },
      {
        id: "m-1033-3",
        author: "Mei-Hua Chen",
        authorEmail: "meihua@pacificport.sg",
        authorInitials: "MC",
        authorTone: "teal",
        isTeam: false,
        sentAt: "Mon, 1:48 PM",
        body: [
          "Both new Singapore static NAT CIDRs are live on our firewall and passing synthetic health probes with sub-40ms latency. Feel free to close this out — thanks for the fast turnaround!",
        ],
      },
    ],
  },
  {
    id: "thr-1032",
    ticketNumber: "ND-1032",
    sender: "Samuel Okafor",
    senderEmail: "s.okafor@kora-commerce.com",
    senderOrg: "Kora Commerce",
    senderInitials: "SO",
    senderTone: "blue",
    subject: "Re: Partner sandbox quota increase for peak holiday load test",
    preview:
      "Load test completed cleanly at 2,400 events/sec with zero dropped callbacks. Ready to restore defaults.",
    labels: ["Rate Limits", "Ops"],
    priority: "normal",
    status: "resolved",
    assignee: "You (Desk Lead)",
    isUnread: false,
    isStarred: false,
    isSnoozed: false,
    updatedAt: "Nov 29",
    messages: [
      {
        id: "m-1032-1",
        author: "Samuel Okafor",
        authorEmail: "s.okafor@kora-commerce.com",
        authorInitials: "SO",
        authorTone: "blue",
        isTeam: false,
        sentAt: "Nov 28, 3:10 PM",
        body: [
          "Requesting a temporary 48-hour sandbox throughput ceiling of 2,500 events/sec so we can validate our checkout surge pipeline before December.",
        ],
      },
      {
        id: "m-1032-2",
        author: "Samuel Okafor",
        authorEmail: "s.okafor@kora-commerce.com",
        authorInitials: "SO",
        authorTone: "blue",
        isTeam: false,
        sentAt: "Nov 29, 6:05 PM",
        body: [
          "Load test completed cleanly at 2,400 events/sec with zero dropped callbacks and p95 dispatch under 180ms. You can revert our sandbox quota to standard limits now.",
        ],
      },
    ],
  },
  {
    id: "thr-1031",
    ticketNumber: "ND-1031",
    sender: "Elena Popescu",
    senderEmail: "legal@carpathia-ai.ro",
    senderOrg: "Carpathia AI",
    senderInitials: "EP",
    senderTone: "purple",
    subject: "Automated DPA countersignature & subprocessor RSS notification feed",
    preview:
      "Legal counsel approved the SCC addendum; pausing until December 3 when our VP signs the final PDF.",
    labels: ["Compliance", "Billing"],
    priority: "normal",
    status: "waiting",
    assignee: "Rohan Patel",
    isUnread: false,
    isStarred: false,
    isSnoozed: true,
    updatedAt: "Nov 28",
    messages: [
      {
        id: "m-1031-1",
        author: "Elena Popescu",
        authorEmail: "legal@carpathia-ai.ro",
        authorInitials: "EP",
        authorTone: "purple",
        isTeam: false,
        sentAt: "Nov 27, 2:14 PM",
        body: [
          "Could you confirm the Atom/RSS URL for 30-day advance subprocessor change notices and send the pre-signed EU Standard Contractual Clauses PDF for counter-execution?",
        ],
      },
      {
        id: "m-1031-2",
        author: "Rohan Patel",
        authorEmail: "rohan.patel@northwind-dispatch.io",
        authorInitials: "RP",
        authorTone: "cyan",
        isTeam: true,
        sentAt: "Nov 28, 9:40 AM",
        body: [
          "Hi Elena — our subprocessor feed is published at trust.northwind-dispatch.io/subprocessors.rss, and I have sent the pre-signed SCC packet via DocuSign. Snoozing until December 3 per your counsel's signing window.",
        ],
        attachments: [
          { id: "att-1031-1", name: "northwind-dpa-scc-2026.pdf", sizeLabel: "248 KB" },
        ],
      },
    ],
  },
];

const INTERACTIVE_ROW_SELECTOR =
  'button, input, a, label, textarea, select, [role="checkbox"], [role="button"], [role="menuitem"]';

function isRowSelfClick(event: {
  target: EventTarget | null;
  currentTarget: EventTarget | null;
}): boolean {
  const control = (event.target as HTMLElement | null)?.closest(INTERACTIVE_ROW_SELECTOR);
  const row = event.currentTarget as HTMLElement | null;
  if (!row) return false;
  return !control || control === row || !row.contains(control);
}

function getLabelPalette(label: string) {
  return LABEL_PALETTES[label] ?? grayPalette;
}

function hasAttachments(thread: InboxThread): boolean {
  return thread.messages.some((m) => (m.attachments?.length ?? 0) > 0);
}

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "inbox-table",
    containerType: "inline-size",
    fontFamily: fonts.body,
    height: "100%",
    minHeight: "42rem",
    overflow: "hidden",
    width: "100%",
  },
  header: {
    backgroundColor: semanticColors.bgSurface,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._2_5,
    paddingInline: spacing._4,
  },
  brandMark: {
    backgroundColor: semanticColors.bgInverted,
    borderRadius: radii.md,
    color: semanticColors.fgInverted,
    flexShrink: 0,
    height: "1.75rem",
    width: "1.75rem",
  },
  headerTitle: {
    marginBlock: 0,
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  noShrink: {
    flexShrink: 0,
  },
  noShrinkNowrap: {
    flexShrink: 0,
    whiteSpace: "nowrap",
  },
  telemetryStat: {
    alignItems: "center",
    color: semanticColors.fgMuted,
    display: "inline-flex",
    fontSize: fontSizes.xs,
    fontVariantNumeric: "tabular-nums",
    gap: spacing._1_5,
    whiteSpace: "nowrap",
  },
  telemetryStrong: {
    color: semanticColors.fg,
    fontWeight: fontWeights.semibold,
  },
  workspace: {
    display: "flex",
    flexGrow: 1,
    minHeight: 0,
    width: "100%",
  },
  queuePane: {
    backgroundColor: semanticColors.bg,
    containerName: "inbox-queue",
    containerType: "inline-size",
    display: "flex",
    flexDirection: "column",
    height: "100%",
    minHeight: 0,
    minWidth: 0,
  },
  queuePaneHiddenMobile: {
    display: {
      default: "flex",
      [NARROW_SURFACE]: "none",
    },
  },
  splitterHandle: {
    display: {
      default: "grid",
      [NARROW_SURFACE]: "none",
    },
  },
  readerPane: {
    backgroundColor: semanticColors.bgSurface,
    containerName: "inbox-reader",
    containerType: "inline-size",
    display: {
      default: "flex",
      [NARROW_SURFACE]: "none",
    },
    flexDirection: "column",
    height: "100%",
    minHeight: 0,
    minWidth: 0,
    overflow: "hidden",
  },
  readerPaneOpenMobile: {
    display: "flex",
  },
  filterBar: {
    backgroundColor: semanticColors.bgSurface,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
  },
  folderStripScroll: {
    maxWidth: "100%",
    overflowX: "auto",
    scrollbarWidth: "none",
  },
  folderCount: {
    marginInlineStart: spacing._1,
  },
  queueCountText: {
    marginInlineStart: "auto",
    whiteSpace: "nowrap",
  },
  searchWrap: {
    flexBasis: "12rem",
    flexGrow: 1,
    minWidth: "9rem",
    position: "relative",
  },
  searchIcon: {
    color: semanticColors.fgSubtle,
    insetInlineStart: spacing._2_5,
    pointerEvents: "none",
    position: "absolute",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineEnd: spacing._8,
    paddingInlineStart: spacing._8,
  },
  searchClearBtn: {
    color: semanticColors.fgMuted,
    insetInlineEnd: spacing._1,
    position: "absolute",
  },
  statusSelectWrap: {
    flexShrink: 0,
    width: "8.75rem",
  },
  tableScroll: {
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    width: "100%",
  },
  queueTable: {
    tableLayout: "fixed",
    width: "100%",
  },
  tableHeader: {
    backgroundColor: semanticColors.bgMuted,
    position: "sticky",
    top: 0,
    zIndex: 2,
  },
  headerCell: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.semibold,
    letterSpacing: "0.02em",
    paddingBlock: spacing._2,
    paddingInline: spacing._2,
    textTransform: "uppercase",
    whiteSpace: "nowrap",
  },
  colCheck: {
    paddingInlineEnd: spacing._1,
    paddingInlineStart: spacing._3,
    width: "4.5rem",
  },
  colSender: {
    display: {
      default: "table-cell",
      [QUEUE_COMPACT]: "none",
    },
    width: "10.5rem",
  },
  colSubject: {
    width: "auto",
  },
  colLabels: {
    display: {
      default: "table-cell",
      [QUEUE_MEDIUM]: "none",
    },
    width: "9.5rem",
  },
  colTime: {
    display: {
      default: "table-cell",
      [QUEUE_COMPACT]: "none",
    },
    paddingInlineEnd: spacing._3,
    textAlign: "end",
    width: "7.25rem",
  },
  queueRow: {
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.interactionHover,
    },
    cursor: "pointer",
    outlineColor: {
      default: "transparent",
      ":focus-visible": semanticColors.accentFocusRing,
    },
    outlineOffset: "-2px",
    outlineStyle: {
      default: "none",
      ":focus-visible": "solid",
    },
    outlineWidth: {
      default: 0,
      ":focus-visible": "2px",
    },
    transitionDuration: durations.fast,
    transitionProperty: "background-color",
    "--row-actions-opacity": {
      default: "0",
      ":hover": "1",
      ":focus-within": "1",
    },
    "--row-actions-scale": {
      default: "scale(0.001)",
      ":hover": "scale(1)",
      ":focus-within": "scale(1)",
    },
    "--row-time-opacity": {
      default: "1",
      ":hover": "0",
      ":focus-within": "0",
    },
  },
  queueRowUnread: {
    backgroundColor: {
      default: semanticColors.bgSurface,
      ":hover": semanticColors.interactionHover,
    },
  },
  queueRowSelected: {
    backgroundColor: {
      default: semanticColors.accentMuted,
      ":hover": semanticColors.accentMuted,
    },
  },
  queueRowActive: {
    backgroundColor: {
      default: semanticColors.interactionSelected,
      ":hover": semanticColors.interactionSelected,
    },
    boxShadow: `inset 2px 0 0 0 ${semanticColors.accentSolid}`,
  },
  bodyCell: {
    borderBottomColor: semanticColors.borderSubtle,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._2,
    verticalAlign: "middle",
  },
  unreadDotSlot: {
    flexShrink: 0,
    width: "0.5rem",
  },
  unreadDot: {
    backgroundColor: semanticColors.accentSolid,
    borderRadius: radii.full,
    height: "0.4375rem",
    width: "0.4375rem",
  },
  starButton: {
    color: {
      default: semanticColors.fgSubtle,
      ":hover": semanticColors.amberFg,
    },
  },
  starButtonActive: {
    color: semanticColors.amberSolid,
  },
  compactHeaderRow: {
    display: {
      default: "none",
      [QUEUE_COMPACT]: "flex",
    },
  },
  msgCountChip: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.borderSubtle,
    borderRadius: radii.full,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fgMuted,
    flexShrink: 0,
    fontSize: "0.6875rem",
    fontVariantNumeric: "tabular-nums",
    lineHeight: 1.2,
    paddingBlock: "1px",
    paddingInline: spacing._1_5,
  },
  inlineBadgesRow: {
    display: {
      default: "none",
      [QUEUE_MEDIUM]: "flex",
    },
    marginBlockStart: spacing._1,
  },
  trailingCellInner: {
    height: "1.75rem",
    position: "relative",
    width: "100%",
  },
  timeDisplay: {
    alignItems: "center",
    color: semanticColors.fgMuted,
    display: "inline-flex",
    fontSize: fontSizes.xs,
    fontVariantNumeric: "tabular-nums",
    gap: spacing._1,
    opacity: {
      default: "var(--row-time-opacity, 1)",
      "@media (hover: none)": 1,
    },
    transitionDuration: durations.fast,
    transitionProperty: "opacity",
    whiteSpace: "nowrap",
  },
  timeDisplayUnread: {
    color: semanticColors.fg,
    fontWeight: fontWeights.semibold,
  },
  hoverActions: {
    display: {
      default: "inline-flex",
      "@media (hover: none)": "none",
    },
    insetInlineEnd: 0,
    opacity: "var(--row-actions-opacity, 0)",
    position: "absolute",
    transform: "var(--row-actions-scale, scale(0.001))",
    transformOrigin: "right center",
    transitionDuration: durations.fast,
    transitionProperty: "opacity",
  },
  rowIconBtn: {
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
  },
  readerHeader: {
    backgroundColor: semanticColors.bgSurface,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  backButton: {
    display: {
      default: "none",
      [NARROW_SURFACE]: "inline-flex",
    },
  },
  readerSubject: {
    marginBlock: 0,
  },
  triageBar: {
    backgroundColor: semanticColors.bgMuted,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._2,
    paddingInline: spacing._4,
  },
  triageSelectStatus: {
    width: "7.25rem",
  },
  triageSelectAssignee: {
    width: "9.5rem",
  },
  triageSelectPriority: {
    width: "6.5rem",
  },
  threadScroll: {
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  messageCard: {
    backgroundColor: semanticColors.bg,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    overflow: "hidden",
  },
  messageCardNote: {
    backgroundColor: semanticColors.amberMuted,
    borderColor: semanticColors.amberBorder,
  },
  messageTrigger: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.interactionHover,
    },
    borderStyle: "none",
    borderWidth: 0,
    color: "inherit",
    cursor: "pointer",
    display: "flex",
    fontFamily: fonts.body,
    gap: spacing._2_5,
    justifyContent: "space-between",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    textAlign: "start",
    width: "100%",
  },
  messageTriggerLead: {
    flexGrow: 1,
  },
  messageTriggerTrail: {
    color: semanticColors.fgSubtle,
    flexShrink: 0,
    fontSize: fontSizes.xs,
    fontVariantNumeric: "tabular-nums",
    whiteSpace: "nowrap",
  },
  chevronIcon: {
    transitionDuration: durations.fast,
    transitionProperty: "transform",
  },
  chevronIconOpen: {
    transform: "rotate(180deg)",
  },
  messageBodyOuter: {
    borderTopColor: semanticColors.borderSubtle,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    paddingBlockEnd: spacing._3_5,
    paddingBlockStart: spacing._3,
    paddingInlineEnd: spacing._4,
    paddingInlineStart: "3.25rem",
  },
  messageBodyCopy: {
    lineHeight: lineHeights.md,
    maxWidth: "66ch",
  },
  attachmentStrip: {
    marginBlockStart: spacing._3,
  },
  attachmentChip: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: {
      default: semanticColors.bgMuted,
      ":hover": semanticColors.interactionHover,
    },
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    gap: spacing._1_5,
    paddingBlock: spacing._1,
    paddingInline: spacing._2,
  },
  attachmentSize: {
    color: semanticColors.fgSubtle,
    fontFamily: fonts.body,
  },
  composerShell: {
    backgroundColor: semanticColors.bgSurface,
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  composerShellNote: {
    backgroundColor: semanticColors.amberMuted,
  },
  composerTextarea: {
    backgroundColor: semanticColors.bg,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    minHeight: "4.5rem",
    resize: "vertical",
  },
  composerHint: {
    display: {
      default: "inline",
      [COMPOSER_COMPACT]: "none",
    },
  },
  composerSubmitGroup: {
    marginInlineStart: "auto",
  },
  actionBarContent: {
    flexWrap: "wrap",
  },
  checkIconSvg: {
    height: "100%",
    width: "100%",
  },
});

function DispatchLogoIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M3 5.5A1.5 1.5 0 0 1 4.5 4h11A1.5 1.5 0 0 1 17 5.5v9a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 3 14.5v-9Z" />
      <path d="M3.5 10.5h3.2l1.6 2h3.4l1.6-2h3.2" />
    </Icon>
  );
}

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

function CloseIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="M4.2 4.2 11.8 11.8M11.8 4.2 4.2 11.8" />
    </Icon>
  );
}

function StarIcon({ filled }: { filled: boolean }) {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill={filled ? "currentColor" : "none"}
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="m8 2 1.85 3.75 4.15.6-3 2.92.71 4.13L8 11.45 4.29 13.4 5 9.27 2 6.35l4.15-.6L8 2Z" />
    </Icon>
  );
}

function ArchiveIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="2" y="2.5" width="12" height="3" rx="0.8" />
      <path d="M3.2 5.5v7.2a1 1 0 0 0 1 1h7.6a1 1 0 0 0 1-1V5.5" />
      <path d="M6.5 8.5h3" />
    </Icon>
  );
}

function SnoozeIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="8" cy="8" r="5.5" />
      <path d="M8 5v3.2l2.1 1.4" />
    </Icon>
  );
}

function MailIcon({ unread }: { unread: boolean }) {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {unread ? (
        <>
          <rect x="2" y="3.5" width="12" height="9" rx="1.2" />
          <path d="m2.5 4.5 5.5 4 5.5-4" />
        </>
      ) : (
        <>
          <path d="M2 6.5 8 2.8l6 3.7v6a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-6Z" />
          <path d="m2.5 6.8 5.5 3.4 5.5-3.4" />
        </>
      )}
    </Icon>
  );
}

function PaperclipIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="m11.5 5.2-4.8 4.8a1.6 1.6 0 0 1-2.26-2.26l5.2-5.2a2.6 2.6 0 0 1 3.68 3.68l-5.4 5.4a3.6 3.6 0 0 1-5.09-5.09l4.5-4.5" />
    </Icon>
  );
}

function ChevronDownIcon({ open }: { open: boolean }) {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      style={[styles.chevronIcon, open && styles.chevronIconOpen]}
    >
      <path d="m4 6 4 4 4-4" />
    </Icon>
  );
}

function ArrowLeftIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M12.5 8h-9M7 4.2 3.2 8 7 11.8" />
    </Icon>
  );
}

function SendIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M14 2.5 7.4 9.1M14 2.5 9.6 13.8l-2.2-4.7-4.7-2.2L14 2.5Z" />
    </Icon>
  );
}

function LockNoteIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="3.5" y="7" width="9" height="6.5" rx="1.2" />
      <path d="M5.5 7V5.2a2.5 2.5 0 0 1 5 0V7" />
    </Icon>
  );
}

function CheckMarkIcon() {
  return (
    <svg viewBox="0 0 12 12" fill="none" aria-hidden="true" {...stylex.props(styles.checkIconSvg)}>
      <path
        d="M2.5 6.4 5 8.9l4.5-5.4"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function MinusMarkIcon() {
  return (
    <svg viewBox="0 0 12 12" fill="none" aria-hidden="true" {...stylex.props(styles.checkIconSvg)}>
      <path d="M2.5 6h7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

function InboxEmptyIcon() {
  return (
    <Icon
      size="lg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M4 7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7Z" />
      <path d="M4 13h4.5l2 2.5h3l2-2.5H20" />
    </Icon>
  );
}

export interface InboxTableProps extends StyleOverrideProps {
  /** Workspace title rendered in the top bar. */
  workspaceName?: string;
  /** Subtitle identifying the support queue or desk. */
  deskSubtitle?: string;
  /** Optional thread ID opened initially in the reading pane. */
  defaultSelectedId?: string;
}

/**
 * InboxTable — two-pane resizable support & security triage queue combining an
 * adaptive container-query queue table (folder SegmentGroup, search, status
 * filter, bulk Checkbox selection + floating ActionBar, unread indicators, star
 * toggles, hover quick-actions) with a collapsible reading pane and live
 * reply / internal-note composer.
 */
export function InboxTable({
  workspaceName = "Northwind Dispatch",
  deskSubtitle = "Partner Support & Security Desk",
  defaultSelectedId = INITIAL_THREADS[0]!.id,
  palette,
  style,
}: InboxTableProps) {
  const queue = useMemo(() => Toast.createToaster(), []);
  const threadScrollRef = useRef<HTMLDivElement | null>(null);

  const [threads, setThreads] = useState<InboxThread[]>(INITIAL_THREADS);
  const [folder, setFolder] = useState<QueueFolder>("all");
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("active");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());
  const [activeThreadId, setActiveThreadId] = useState<string | null>(defaultSelectedId);
  const [mobileThreadOpen, setMobileThreadOpen] = useState<boolean>(false);

  // Collapsible message state: tracks expanded message IDs per open thread.
  const [expandedMessages, setExpandedMessages] = useState<Set<string>>(() => {
    const initial = INITIAL_THREADS.find((t) => t.id === defaultSelectedId) ?? INITIAL_THREADS[0];
    const lastId = initial?.messages[initial.messages.length - 1]?.id;
    return lastId ? new Set([lastId]) : new Set();
  });

  // Per-thread composer drafts so switching threads never discards unfinished replies.
  const [draftsByThread, setDraftsByThread] = useState<Record<string, string>>({});
  const [composerMode, setComposerMode] = useState<ComposerMode>("reply");

  const folderCounts = useMemo(() => {
    const nonArchived = threads.filter((t) => t.status !== "archived");
    return {
      all: nonArchived.length,
      unread: nonArchived.filter((t) => t.isUnread).length,
      starred: nonArchived.filter((t) => t.isStarred).length,
      snoozed: nonArchived.filter((t) => t.isSnoozed).length,
      open: nonArchived.filter((t) => t.status === "open").length,
      urgent: nonArchived.filter((t) => t.priority === "urgent" && t.status !== "resolved").length,
      archived: threads.filter((t) => t.status === "archived").length,
    };
  }, [threads]);

  const visibleThreads = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    return threads.filter((thread) => {
      if (statusFilter === "active") {
        if (thread.status === "archived") return false;
      } else if (thread.status !== statusFilter) {
        return false;
      }

      if (folder === "unread" && !thread.isUnread) return false;
      if (folder === "starred" && !thread.isStarred) return false;
      if (folder === "snoozed" && !thread.isSnoozed) return false;

      if (!q) return true;
      return (
        thread.ticketNumber.toLowerCase().includes(q) ||
        thread.sender.toLowerCase().includes(q) ||
        thread.senderEmail.toLowerCase().includes(q) ||
        thread.senderOrg.toLowerCase().includes(q) ||
        thread.subject.toLowerCase().includes(q) ||
        thread.preview.toLowerCase().includes(q) ||
        thread.labels.some((label) => label.toLowerCase().includes(q))
      );
    });
  }, [folder, searchQuery, statusFilter, threads]);

  const activeThread = useMemo(
    () => threads.find((t) => t.id === activeThreadId) ?? null,
    [activeThreadId, threads],
  );

  // Keep expanded messages synced when switching threads so earlier messages collapse
  // and the latest message opens immediately.
  const openThread = useCallback((thread: InboxThread) => {
    setActiveThreadId(thread.id);
    setMobileThreadOpen(true);
    const latestId = thread.messages[thread.messages.length - 1]?.id;
    setExpandedMessages(latestId ? new Set([latestId]) : new Set());
    if (thread.isUnread) {
      setThreads((prev) =>
        prev.map((item) => (item.id === thread.id ? { ...item, isUnread: false } : item)),
      );
    }
  }, []);

  const selectedVisibleCount = useMemo(
    () => visibleThreads.filter((t) => selectedIds.has(t.id)).length,
    [selectedIds, visibleThreads],
  );

  const allVisibleSelected =
    visibleThreads.length > 0 && selectedVisibleCount === visibleThreads.length;
  const someVisibleSelected =
    selectedVisibleCount > 0 && selectedVisibleCount < visibleThreads.length;

  const selectedThreads = useMemo(
    () => threads.filter((t) => selectedIds.has(t.id)),
    [selectedIds, threads],
  );

  const hasActiveFilters =
    folder !== "all" || statusFilter !== "active" || searchQuery.trim().length > 0;

  const resetFilters = useCallback(() => {
    setFolder("all");
    setStatusFilter("active");
    setSearchQuery("");
  }, []);

  const toggleSelectAllVisible = useCallback(
    (checked: boolean | "indeterminate") => {
      const nextSelect = checked === true;
      setSelectedIds((prev) => {
        const next = new Set(prev);
        for (const thread of visibleThreads) {
          if (nextSelect) {
            next.add(thread.id);
          } else {
            next.delete(thread.id);
          }
        }
        return next;
      });
    },
    [visibleThreads],
  );

  const toggleSelectRow = useCallback((id: string, checked: boolean) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (checked) {
        next.add(id);
      } else {
        next.delete(id);
      }
      return next;
    });
  }, []);

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

  const toggleStar = useCallback(
    (ids: string[], nextStarred?: boolean) => {
      const idSet = new Set(ids);
      let resolvedStar = nextStarred ?? true;
      setThreads((prev) =>
        prev.map((t) => {
          if (!idSet.has(t.id)) return t;
          resolvedStar = nextStarred ?? !t.isStarred;
          return { ...t, isStarred: resolvedStar };
        }),
      );
      if (ids.length > 1) {
        queue.info(
          resolvedStar ? `Starred ${ids.length} threads` : `Removed star from ${ids.length} threads`,
        );
      }
    },
    [queue],
  );

  const setReadState = useCallback(
    (ids: string[], nextUnread: boolean) => {
      const idSet = new Set(ids);
      setThreads((prev) =>
        prev.map((t) => (idSet.has(t.id) ? { ...t, isUnread: nextUnread } : t)),
      );
      queue.info(
        ids.length === 1
          ? nextUnread
            ? "Marked conversation unread"
            : "Marked conversation read"
          : nextUnread
            ? `Marked ${ids.length} conversations unread`
            : `Marked ${ids.length} conversations read`,
      );
    },
    [queue],
  );

  const toggleSnooze = useCallback(
    (ids: string[], nextSnoozed?: boolean) => {
      const idSet = new Set(ids);
      let finalState = nextSnoozed ?? true;
      setThreads((prev) =>
        prev.map((t) => {
          if (!idSet.has(t.id)) return t;
          finalState = nextSnoozed ?? !t.isSnoozed;
          return { ...t, isSnoozed: finalState };
        }),
      );
      queue.info(
        ids.length === 1
          ? finalState
            ? "Snoozed until tomorrow 09:00 UTC"
            : "Moved back from Snoozed"
          : finalState
            ? `Snoozed ${ids.length} conversations`
            : `Unsnoozed ${ids.length} conversations`,
      );
    },
    [queue],
  );

  const archiveThreads = useCallback(
    (ids: string[], restore = false) => {
      const idSet = new Set(ids);
      setThreads((prev) =>
        prev.map((t) =>
          idSet.has(t.id)
            ? {
                ...t,
                status: restore ? "open" : "archived",
                isUnread: restore ? t.isUnread : false,
                isSnoozed: false,
              }
            : t,
        ),
      );
      setSelectedIds((prev) => {
        const next = new Set(prev);
        for (const id of ids) next.delete(id);
        return next;
      });
      queue.success(
        ids.length === 1
          ? restore
            ? "Conversation restored to queue"
            : "Conversation archived"
          : restore
            ? `Restored ${ids.length} conversations`
            : `Archived ${ids.length} conversations`,
      );
    },
    [queue],
  );

  const updateThreadField = useCallback(
    <K extends "status" | "assignee" | "priority">(
      id: string,
      field: K,
      value: InboxThread[K],
      toastTitle: string,
    ) => {
      setThreads((prev) =>
        prev.map((t) => (t.id === id ? { ...t, [field]: value } : t)),
      );
      queue.info(toastTitle);
    },
    [queue],
  );

  const toggleMessageExpanded = useCallback((messageId: string, open: boolean) => {
    setExpandedMessages((prev) => {
      const next = new Set(prev);
      if (open) {
        next.add(messageId);
      } else {
        next.delete(messageId);
      }
      return next;
    });
  }, []);

  const allMessagesExpanded = useMemo(() => {
    if (!activeThread || activeThread.messages.length <= 1) return true;
    return activeThread.messages.every((m) => expandedMessages.has(m.id));
  }, [activeThread, expandedMessages]);

  const handleToggleExpandAll = useCallback(() => {
    if (!activeThread) return;
    if (allMessagesExpanded) {
      const lastId = activeThread.messages[activeThread.messages.length - 1]?.id;
      setExpandedMessages(lastId ? new Set([lastId]) : new Set());
    } else {
      setExpandedMessages(new Set(activeThread.messages.map((m) => m.id)));
    }
  }, [activeThread, allMessagesExpanded]);

  const currentDraft = activeThread ? (draftsByThread[activeThread.id] ?? "") : "";

  const handleDraftChange = useCallback(
    (value: string) => {
      if (!activeThread) return;
      setDraftsByThread((prev) => ({ ...prev, [activeThread.id]: value }));
    },
    [activeThread],
  );

  const submitComposer = useCallback(
    (alsoResolve = false) => {
      if (!activeThread) return;
      const trimmed = currentDraft.trim();
      if (!trimmed) return;

      const isNote = composerMode === "note";
      const paragraphs = trimmed
        .split(/\n{2,}/)
        .map((p) => p.trim())
        .filter(Boolean);
      const newMessageId = `m-${activeThread.id}-${Date.now()}`;
      const newMessage: ThreadMessage = {
        id: newMessageId,
        author: "You (Desk Lead)",
        authorEmail: "desk-lead@northwind-dispatch.io",
        authorInitials: "YD",
        authorTone: "green",
        isTeam: true,
        isInternalNote: isNote,
        sentAt: "Just now",
        body: paragraphs.length > 0 ? paragraphs : [trimmed],
      };

      const nextStatus: ThreadStatus = alsoResolve
        ? "resolved"
        : !isNote && activeThread.status === "open"
          ? "waiting"
          : activeThread.status;

      setThreads((prev) =>
        prev.map((t) =>
          t.id !== activeThread.id
            ? t
            : {
                ...t,
                messages: [...t.messages, newMessage],
                preview: isNote ? t.preview : trimmed.replace(/\s+/g, " "),
                updatedAt: "Just now",
                isUnread: false,
                status: nextStatus,
                assignee: t.assignee ?? "You (Desk Lead)",
              },
        ),
      );

      setExpandedMessages((prev) => {
        const next = new Set(prev);
        next.add(newMessageId);
        return next;
      });
      setDraftsByThread((prev) => ({ ...prev, [activeThread.id]: "" }));

      queue.success(
        isNote
          ? `Internal note added to ${activeThread.ticketNumber}`
          : alsoResolve
            ? `Reply sent & ${activeThread.ticketNumber} resolved`
            : `Reply sent to ${activeThread.sender}`,
        {
          description: isNote
            ? "Visible only to Northwind Dispatch team members."
            : `Delivered to ${activeThread.senderEmail}.`,
        },
      );
    },
    [activeThread, composerMode, currentDraft, queue],
  );

  // Scroll the reading pane to the newest message after appending a reply/note.
  const activeMessageCount = activeThread?.messages.length ?? 0;
  useEffect(() => {
    const node = threadScrollRef.current;
    if (!node) return;
    node.scrollTo({ top: node.scrollHeight, behavior: "smooth" });
  }, [activeMessageCount]);

  const anySelectedUnread = selectedThreads.some((t) => t.isUnread);
  const anySelectedUnstarred = selectedThreads.some((t) => !t.isStarred);

  return (
    <VStack gap="0" palette={palette} style={[styles.root, style]}>
      {/* Top workspace header */}
      <HStack
        render={<header />}
        justify="between"
        wrap="wrap"
        gap="3"
        style={styles.header}
      >
        <HStack gap="2.5">
          <Center display="inline" style={styles.brandMark} aria-hidden="true">
            <DispatchLogoIcon />
          </Center>
          <HStack align="baseline" wrap="wrap" gap="2">
            <Heading render={<h1 />} size="md" style={styles.headerTitle}>
              {workspaceName}
            </Heading>
            <Text render={<span />} size="xs" variant="muted" style={styles.nowrap}>
              {deskSubtitle}
            </Text>
          </HStack>
        </HStack>

        <HStack wrap="wrap" gap="2">
          <span {...stylex.props(styles.telemetryStat)}>
            <Status.Root size="sm" palette={accentPalette}>
              <Status.Indicator />
            </Status.Root>
            <strong {...stylex.props(styles.telemetryStrong)}>{folderCounts.unread}</strong> unread
          </span>
          <span aria-hidden="true" {...stylex.props(styles.telemetryStat)}>
            ·
          </span>
          <span {...stylex.props(styles.telemetryStat)}>
            <strong {...stylex.props(styles.telemetryStrong)}>{folderCounts.open}</strong> open
          </span>
          {folderCounts.urgent > 0 ? (
            <Badge variant="subtle" size="sm" palette={redPalette}>
              {folderCounts.urgent} urgent
            </Badge>
          ) : null}
          {folderCounts.archived > 0 ? (
            <Button
              variant={statusFilter === "archived" ? "surface" : "ghost"}
              size="xs"
              onClick={() =>
                setStatusFilter((prev) => (prev === "archived" ? "active" : "archived"))
              }
            >
              <ArchiveIcon />
              Archived ({folderCounts.archived})
            </Button>
          ) : null}
        </HStack>
      </HStack>

      {/* Two-pane resizable workspace */}
      <div {...stylex.props(styles.workspace)}>
        <Splitter.Root orientation="horizontal" defaultSize={[48, 52]} minSize={26}>
          {/* Left pane: Queue Table */}
          <Splitter.Panel
            index={0}
            style={[
              styles.queuePane,
              mobileThreadOpen && styles.queuePaneHiddenMobile,
            ]}
          >
            <VStack gap="2" style={styles.filterBar}>
              <HStack justify="between" wrap="wrap" gap="2">
                <div {...stylex.props(styles.folderStripScroll)}>
                  <SegmentGroup.Root
                    size="xs"
                    value={folder}
                    onValueChange={(next) => {
                      if (
                        next === "all" ||
                        next === "unread" ||
                        next === "starred" ||
                        next === "snoozed"
                      ) {
                        setFolder(next);
                      }
                    }}
                    aria-label="Queue folders"
                  >
                    <SegmentGroup.Item value="all">
                      All
                      <Text
                        render={<span />}
                        size="xs"
                        tone="subtle"
                        tabular="true"
                        style={styles.folderCount}
                      >
                        {folderCounts.all}
                      </Text>
                    </SegmentGroup.Item>
                    <SegmentGroup.Item value="unread">
                      Unread
                      <Text
                        render={<span />}
                        size="xs"
                        tone="subtle"
                        tabular="true"
                        style={styles.folderCount}
                      >
                        {folderCounts.unread}
                      </Text>
                    </SegmentGroup.Item>
                    <SegmentGroup.Item value="starred">
                      Starred
                      <Text
                        render={<span />}
                        size="xs"
                        tone="subtle"
                        tabular="true"
                        style={styles.folderCount}
                      >
                        {folderCounts.starred}
                      </Text>
                    </SegmentGroup.Item>
                    <SegmentGroup.Item value="snoozed">
                      Snoozed
                      <Text
                        render={<span />}
                        size="xs"
                        tone="subtle"
                        tabular="true"
                        style={styles.folderCount}
                      >
                        {folderCounts.snoozed}
                      </Text>
                    </SegmentGroup.Item>
                  </SegmentGroup.Root>
                </div>

                <Text
                  render={<span />}
                  size="xs"
                  tone="subtle"
                  tabular="true"
                  style={styles.queueCountText}
                >
                  {visibleThreads.length}{" "}
                  {visibleThreads.length === 1 ? "thread" : "threads"}
                </Text>
              </HStack>

              <HStack wrap="wrap" gap="2">
                <HStack gap="0" style={styles.searchWrap}>
                  <span {...stylex.props(styles.searchIcon)}>
                    <SearchIcon />
                  </span>
                  <Input
                    size="sm"
                    placeholder="Search ticket, sender, subject, label…"
                    aria-label="Search conversations"
                    value={searchQuery}
                    onChange={(event) => setSearchQuery(event.target.value)}
                    style={styles.searchInput}
                  />
                  {searchQuery.length > 0 ? (
                    <IconButton
                      type="button"
                      variant="ghost"
                      size="2xs"
                      aria-label="Clear search"
                      onClick={() => setSearchQuery("")}
                      style={styles.searchClearBtn}
                    >
                      <CloseIcon />
                    </IconButton>
                  ) : null}
                </HStack>

                <Select.Root
                  size="sm"
                  variant="outline"
                  value={statusFilter}
                  onValueChange={(next) => {
                    if (
                      next === "active" ||
                      next === "open" ||
                      next === "waiting" ||
                      next === "resolved" ||
                      next === "archived"
                    ) {
                      setStatusFilter(next);
                    }
                  }}
                  style={styles.statusSelectWrap}
                >
                  <Select.Control>
                    <Select.Trigger aria-label="Filter by status">
                      <Select.Value>
                        {STATUS_FILTER_OPTIONS.find((opt) => opt.value === statusFilter)?.label}
                      </Select.Value>
                    </Select.Trigger>
                    <Select.IndicatorGroup>
                      <Select.Icon />
                    </Select.IndicatorGroup>
                  </Select.Control>
                  <Select.Content>
                    {STATUS_FILTER_OPTIONS.map((opt) => (
                      <Select.Item key={opt.value} value={opt.value}>
                        <Select.ItemText>{opt.label}</Select.ItemText>
                        <Select.ItemIndicator />
                      </Select.Item>
                    ))}
                  </Select.Content>
                </Select.Root>

                {hasActiveFilters ? (
                  <Button variant="ghost" size="xs" onClick={resetFilters}>
                    Reset
                  </Button>
                ) : null}
              </HStack>
            </VStack>

            <div
              role="region"
              aria-label="Support inbox queue"
              {...stylex.props(styles.tableScroll)}
            >
              {visibleThreads.length === 0 ? (
                <EmptyState.Root size="md">
                  <EmptyState.Content>
                    <EmptyState.Indicator>
                      <InboxEmptyIcon />
                    </EmptyState.Indicator>
                    <EmptyState.Title>No matching conversations</EmptyState.Title>
                    <EmptyState.Description>
                      Try clearing your search query or switching to another queue folder.
                    </EmptyState.Description>
                    {hasActiveFilters ? (
                      <EmptyState.Actions>
                        <Button variant="surface" size="sm" onClick={resetFilters}>
                          Reset filters
                        </Button>
                      </EmptyState.Actions>
                    ) : null}
                  </EmptyState.Content>
                </EmptyState.Root>
              ) : (
                <Table.Root variant="line" size="sm" style={styles.queueTable}>
                  <Table.Header style={styles.tableHeader}>
                    <Table.Row>
                      <Table.ColumnHeader style={[styles.headerCell, styles.colCheck]}>
                        <Checkbox.Root size="sm" palette={accentPalette}>
                          <Checkbox.Control
                            aria-label="Select all visible conversations"
                            checked={
                              allVisibleSelected
                                ? true
                                : someVisibleSelected
                                  ? "indeterminate"
                                  : false
                            }
                            onCheckedChange={toggleSelectAllVisible}
                          >
                            <Checkbox.Indicator>
                              {someVisibleSelected ? <MinusMarkIcon /> : <CheckMarkIcon />}
                            </Checkbox.Indicator>
                          </Checkbox.Control>
                        </Checkbox.Root>
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={[styles.headerCell, styles.colSender]}>
                        Sender
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={[styles.headerCell, styles.colSubject]}>
                        Conversation
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={[styles.headerCell, styles.colLabels]}>
                        Labels
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={[styles.headerCell, styles.colTime]}>
                        Activity
                      </Table.ColumnHeader>
                    </Table.Row>
                  </Table.Header>

                  <Table.Body>
                    {visibleThreads.map((thread) => {
                      const isChecked = selectedIds.has(thread.id);
                      const isActive = thread.id === activeThreadId;
                      const threadHasAttachments = hasAttachments(thread);
                      return (
                        <Table.Row
                          key={thread.id}
                          tabIndex={0}
                          aria-current={isActive ? "true" : undefined}
                          data-selected={isChecked ? "" : undefined}
                          onClick={(event) => {
                            if (isRowSelfClick(event)) openThread(thread);
                          }}
                          onKeyDown={(event) => {
                            if (
                              (event.key === "Enter" || event.key === " ") &&
                              isRowSelfClick(event)
                            ) {
                              event.preventDefault();
                              openThread(thread);
                            }
                          }}
                          style={[
                            styles.queueRow,
                            thread.isUnread && styles.queueRowUnread,
                            isChecked && styles.queueRowSelected,
                            isActive && styles.queueRowActive,
                          ]}
                        >
                          {/* Checkbox + unread indicator + star toggle */}
                          <Table.Cell style={[styles.bodyCell, styles.colCheck]}>
                            <HStack gap="1.5">
                              <Checkbox.Root size="sm" palette={accentPalette}>
                                <Checkbox.Control
                                  aria-label={`Select ${thread.ticketNumber}: ${thread.subject}`}
                                  checked={isChecked}
                                  onCheckedChange={(next) =>
                                    toggleSelectRow(thread.id, next === true)
                                  }
                                />
                              </Checkbox.Root>

                              <Center render={<span />} display="inline" style={styles.unreadDotSlot}>
                                {thread.isUnread ? (
                                  <span
                                    aria-label="Unread"
                                    title="Unread"
                                    {...stylex.props(styles.unreadDot)}
                                  />
                                ) : null}
                              </Center>

                              <IconButton
                                type="button"
                                variant="ghost"
                                size="2xs"
                                aria-pressed={thread.isStarred}
                                aria-label={
                                  thread.isStarred
                                    ? `Unstar ${thread.ticketNumber}`
                                    : `Star ${thread.ticketNumber}`
                                }
                                title={thread.isStarred ? "Unstar" : "Star"}
                                onClick={() => toggleStar([thread.id])}
                                style={[
                                  styles.starButton,
                                  thread.isStarred && styles.starButtonActive,
                                ]}
                              >
                                <StarIcon filled={thread.isStarred} />
                              </IconButton>
                            </HStack>
                          </Table.Cell>

                          {/* Sender column (hidden when queue pane narrows below 500px) */}
                          <Table.Cell style={[styles.bodyCell, styles.colSender]}>
                            <HStack gap="2">
                              <Avatar.Root
                                size="xs"
                                variant="subtle"
                                palette={AVATAR_PALETTE[thread.senderTone]}
                              >
                                <Avatar.Fallback>{thread.senderInitials}</Avatar.Fallback>
                              </Avatar.Root>
                              <VStack gap="0">
                                <Text
                                  render={<span />}
                                  size="xs"
                                  weight={thread.isUnread ? "semibold" : "normal"}
                                  truncate="true"
                                >
                                  {thread.sender}
                                </Text>
                                <Text render={<span />} size="xs" tone="subtle" truncate="true">
                                  {thread.senderOrg}
                                </Text>
                              </VStack>
                            </HStack>
                          </Table.Cell>

                          {/* Conversation subject + preview + adaptive compact/medium metadata */}
                          <Table.Cell style={[styles.bodyCell, styles.colSubject]}>
                            <VStack gap="0.5">
                              <HStack justify="between" gap="1.5" style={styles.compactHeaderRow}>
                                <HStack gap="1.5">
                                  <Text
                                    render={<span />}
                                    size="xs"
                                    weight={thread.isUnread ? "semibold" : "normal"}
                                    truncate="true"
                                  >
                                    {thread.sender}
                                  </Text>
                                  <Text render={<span />} size="xs" tone="subtle" truncate="true">
                                    · {thread.senderOrg}
                                  </Text>
                                </HStack>
                                <Text
                                  render={<span />}
                                  size="xs"
                                  tone="subtle"
                                  tabular="true"
                                  style={styles.noShrinkNowrap}
                                >
                                  {thread.updatedAt}
                                </Text>
                              </HStack>

                              <HStack gap="1.5">
                                <Text
                                  render={<span />}
                                  variant="mono"
                                  size="xs"
                                  tone="subtle"
                                  style={styles.noShrink}
                                >
                                  {thread.ticketNumber}
                                </Text>
                                <Text
                                  render={<span />}
                                  size="sm"
                                  weight={thread.isUnread ? "semibold" : "normal"}
                                  truncate="true"
                                >
                                  {thread.subject}
                                </Text>
                                {thread.messages.length > 1 ? (
                                  <span {...stylex.props(styles.msgCountChip)}>
                                    {thread.messages.length}
                                  </span>
                                ) : null}
                              </HStack>

                              <Text render={<span />} size="xs" variant="muted" truncate="true">
                                {thread.preview}
                              </Text>

                              {/* Compact inline badges shown once the standalone Labels column hides */}
                              <HStack wrap="wrap" gap="1" style={styles.inlineBadgesRow}>
                                <Status.Root size="sm" palette={STATUS_PALETTE[thread.status]}>
                                  <Status.Indicator />
                                  {STATUS_LABEL[thread.status]}
                                </Status.Root>
                                {thread.priority !== "normal" ? (
                                  <Badge
                                    variant="subtle"
                                    size="xs"
                                    palette={PRIORITY_PALETTE[thread.priority]}
                                  >
                                    {PRIORITY_LABEL[thread.priority]}
                                  </Badge>
                                ) : null}
                                {thread.isSnoozed ? (
                                  <Badge variant="outline" size="xs" palette={amberPalette}>
                                    Snoozed
                                  </Badge>
                                ) : null}
                                {thread.labels.slice(0, 2).map((label) => (
                                  <Badge
                                    key={label}
                                    variant="subtle"
                                    size="xs"
                                    palette={getLabelPalette(label)}
                                  >
                                    {label}
                                  </Badge>
                                ))}
                              </HStack>
                            </VStack>
                          </Table.Cell>

                          {/* Labels & Priority column (hidden below 680px) */}
                          <Table.Cell style={[styles.bodyCell, styles.colLabels]}>
                            <HStack wrap="wrap" gap="1">
                              {thread.priority !== "normal" ? (
                                <Badge
                                  variant="subtle"
                                  size="xs"
                                  palette={PRIORITY_PALETTE[thread.priority]}
                                >
                                  {PRIORITY_LABEL[thread.priority]}
                                </Badge>
                              ) : null}
                              {thread.isSnoozed ? (
                                <Badge variant="outline" size="xs" palette={amberPalette}>
                                  Snoozed
                                </Badge>
                              ) : null}
                              {thread.labels.slice(0, 2).map((label) => (
                                <Badge
                                  key={label}
                                  variant="subtle"
                                  size="xs"
                                  palette={getLabelPalette(label)}
                                >
                                  {label}
                                </Badge>
                              ))}
                            </HStack>
                          </Table.Cell>

                          {/* Relative timestamp & hover quick-actions */}
                          <Table.Cell style={[styles.bodyCell, styles.colTime]}>
                            <HStack justify="end" gap="0" style={styles.trailingCellInner}>
                              <span
                                {...stylex.props(
                                  styles.timeDisplay,
                                  thread.isUnread && styles.timeDisplayUnread,
                                )}
                              >
                                {threadHasAttachments ? <PaperclipIcon /> : null}
                                <span>{thread.updatedAt}</span>
                              </span>

                              <HStack gap="0.5" style={styles.hoverActions}>
                                <IconButton
                                  type="button"
                                  variant="surface"
                                  size="2xs"
                                  aria-label={
                                    thread.isUnread
                                      ? `Mark ${thread.ticketNumber} read`
                                      : `Mark ${thread.ticketNumber} unread`
                                  }
                                  title={thread.isUnread ? "Mark read" : "Mark unread"}
                                  onClick={() => setReadState([thread.id], !thread.isUnread)}
                                  style={styles.rowIconBtn}
                                >
                                  <MailIcon unread={thread.isUnread} />
                                </IconButton>
                                <IconButton
                                  type="button"
                                  variant="surface"
                                  size="2xs"
                                  aria-label={
                                    thread.isSnoozed
                                      ? `Unsnooze ${thread.ticketNumber}`
                                      : `Snooze ${thread.ticketNumber}`
                                  }
                                  title={thread.isSnoozed ? "Unsnooze" : "Snooze"}
                                  onClick={() => toggleSnooze([thread.id])}
                                  style={styles.rowIconBtn}
                                >
                                  <SnoozeIcon />
                                </IconButton>
                                <IconButton
                                  type="button"
                                  variant="surface"
                                  size="2xs"
                                  aria-label={
                                    thread.status === "archived"
                                      ? `Restore ${thread.ticketNumber}`
                                      : `Archive ${thread.ticketNumber}`
                                  }
                                  title={thread.status === "archived" ? "Restore" : "Archive"}
                                  onClick={() =>
                                    archiveThreads([thread.id], thread.status === "archived")
                                  }
                                  style={styles.rowIconBtn}
                                >
                                  <ArchiveIcon />
                                </IconButton>
                              </HStack>
                            </HStack>
                          </Table.Cell>
                        </Table.Row>
                      );
                    })}
                  </Table.Body>
                </Table.Root>
              )}
            </div>
          </Splitter.Panel>

          <Splitter.ResizeTrigger
            index={0}
            aria-label="Resize queue and reading pane"
            style={styles.splitterHandle}
          />

          {/* Right pane: Reading & Thread Pane */}
          <Splitter.Panel
            index={1}
            role="region"
            aria-label="Selected conversation thread"
            style={[
              styles.readerPane,
              mobileThreadOpen && styles.readerPaneOpenMobile,
            ]}
          >
            {!activeThread ? (
              <EmptyState.Root size="md">
                <EmptyState.Content>
                  <EmptyState.Indicator>
                    <InboxEmptyIcon />
                  </EmptyState.Indicator>
                  <EmptyState.Title>Select a conversation</EmptyState.Title>
                  <EmptyState.Description>
                    Choose any thread from the queue to inspect its full message chain and reply.
                  </EmptyState.Description>
                </EmptyState.Content>
              </EmptyState.Root>
            ) : (
              <>
                {/* Thread Header */}
                <VStack gap="2.5" style={styles.readerHeader}>
                  <HStack justify="between" wrap="wrap" gap="2">
                    <HStack wrap="wrap" gap="2">
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => setMobileThreadOpen(false)}
                        style={styles.backButton}
                      >
                        <ArrowLeftIcon />
                        Queue
                      </Button>
                      <Text
                        render={<span />}
                        variant="mono"
                        size="xs"
                        tone="muted"
                        weight="medium"
                      >
                        {activeThread.ticketNumber}
                      </Text>
                      <Text render={<span />} aria-hidden="true" size="xs" variant="muted">
                        ·
                      </Text>
                      <Text render={<span />} size="xs" variant="muted">
                        {activeThread.senderOrg}
                      </Text>
                      <Status.Root size="sm" palette={STATUS_PALETTE[activeThread.status]}>
                        <Status.Indicator />
                        {STATUS_LABEL[activeThread.status]}
                      </Status.Root>
                    </HStack>

                    <HStack wrap="wrap" gap="1">
                      <Button
                        variant="ghost"
                        size="xs"
                        aria-pressed={activeThread.isStarred}
                        aria-label={activeThread.isStarred ? "Unstar thread" : "Star thread"}
                        palette={activeThread.isStarred ? amberPalette : undefined}
                        onClick={() => toggleStar([activeThread.id])}
                      >
                        <StarIcon filled={activeThread.isStarred} />
                        {activeThread.isStarred ? "Starred" : "Star"}
                      </Button>
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => setReadState([activeThread.id], !activeThread.isUnread)}
                      >
                        <MailIcon unread={!activeThread.isUnread} />
                        {activeThread.isUnread ? "Mark read" : "Unread"}
                      </Button>
                      <Button
                        variant="ghost"
                        size="xs"
                        palette={activeThread.isSnoozed ? amberPalette : undefined}
                        onClick={() => toggleSnooze([activeThread.id])}
                      >
                        <SnoozeIcon />
                        {activeThread.isSnoozed ? "Unsnooze" : "Snooze"}
                      </Button>
                      <Button
                        variant="surface"
                        size="xs"
                        onClick={() =>
                          archiveThreads([activeThread.id], activeThread.status === "archived")
                        }
                      >
                        <ArchiveIcon />
                        {activeThread.status === "archived" ? "Restore" : "Archive"}
                      </Button>
                    </HStack>
                  </HStack>

                  <Separator decorative />

                  <Heading render={<h2 />} size="md" style={styles.readerSubject}>
                    {activeThread.subject}
                  </Heading>

                  <HStack wrap="wrap" gap="1.5">
                    <Badge
                      variant="subtle"
                      size="sm"
                      palette={PRIORITY_PALETTE[activeThread.priority]}
                    >
                      {PRIORITY_LABEL[activeThread.priority]} priority
                    </Badge>
                    {activeThread.isSnoozed ? (
                      <Badge variant="outline" size="sm" palette={amberPalette}>
                        Snoozed
                      </Badge>
                    ) : null}
                    {activeThread.labels.map((label) => (
                      <Badge
                        key={label}
                        variant="subtle"
                        size="sm"
                        palette={getLabelPalette(label)}
                      >
                        {label}
                      </Badge>
                    ))}
                  </HStack>
                </VStack>

                {/* Assignee / Status / Priority Triage Strip */}
                <HStack justify="between" wrap="wrap" gap="2" style={styles.triageBar}>
                  <HStack wrap="wrap" gap="2">
                    <HStack gap="1.5">
                      <Text render={<span />} size="xs" tone="subtle" weight="medium">
                        Status
                      </Text>
                      <Select.Root
                        size="xs"
                        variant="outline"
                        value={activeThread.status}
                        onValueChange={(next) => {
                          if (
                            next === "open" ||
                            next === "waiting" ||
                            next === "resolved" ||
                            next === "archived"
                          ) {
                            updateThreadField(
                              activeThread.id,
                              "status",
                              next,
                              `${activeThread.ticketNumber} marked ${STATUS_LABEL[next].toLowerCase()}`,
                            );
                          }
                        }}
                        style={styles.triageSelectStatus}
                      >
                        <Select.Control>
                          <Select.Trigger aria-label="Conversation status">
                            <Select.Value>{STATUS_LABEL[activeThread.status]}</Select.Value>
                          </Select.Trigger>
                          <Select.IndicatorGroup>
                            <Select.Icon />
                          </Select.IndicatorGroup>
                        </Select.Control>
                        <Select.Content>
                          {THREAD_STATUS_OPTIONS.map((opt) => (
                            <Select.Item key={opt.value} value={opt.value}>
                              <Select.ItemText>{opt.label}</Select.ItemText>
                              <Select.ItemIndicator />
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select.Root>
                    </HStack>

                    <HStack gap="1.5">
                      <Text render={<span />} size="xs" tone="subtle" weight="medium">
                        Assignee
                      </Text>
                      <Select.Root
                        size="xs"
                        variant="outline"
                        value={activeThread.assignee ?? "Unassigned"}
                        onValueChange={(next) => {
                          if (typeof next !== "string") return;
                          const assigneeVal = next === "Unassigned" ? null : next;
                          updateThreadField(
                            activeThread.id,
                            "assignee",
                            assigneeVal,
                            assigneeVal
                              ? `Assigned ${activeThread.ticketNumber} to ${assigneeVal}`
                              : `Unassigned ${activeThread.ticketNumber}`,
                          );
                        }}
                        style={styles.triageSelectAssignee}
                      >
                        <Select.Control>
                          <Select.Trigger aria-label="Conversation assignee">
                            <Select.Value>{activeThread.assignee ?? "Unassigned"}</Select.Value>
                          </Select.Trigger>
                          <Select.IndicatorGroup>
                            <Select.Icon />
                          </Select.IndicatorGroup>
                        </Select.Control>
                        <Select.Content>
                          {ASSIGNEES.map((person) => (
                            <Select.Item key={person} value={person}>
                              <Select.ItemText>{person}</Select.ItemText>
                              <Select.ItemIndicator />
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select.Root>
                    </HStack>

                    <HStack gap="1.5">
                      <Text render={<span />} size="xs" tone="subtle" weight="medium">
                        Priority
                      </Text>
                      <Select.Root
                        size="xs"
                        variant="outline"
                        value={activeThread.priority}
                        onValueChange={(next) => {
                          if (next === "urgent" || next === "high" || next === "normal") {
                            updateThreadField(
                              activeThread.id,
                              "priority",
                              next,
                              `${activeThread.ticketNumber} priority set to ${PRIORITY_LABEL[next]}`,
                            );
                          }
                        }}
                        style={styles.triageSelectPriority}
                      >
                        <Select.Control>
                          <Select.Trigger aria-label="Conversation priority">
                            <Select.Value>{PRIORITY_LABEL[activeThread.priority]}</Select.Value>
                          </Select.Trigger>
                          <Select.IndicatorGroup>
                            <Select.Icon />
                          </Select.IndicatorGroup>
                        </Select.Control>
                        <Select.Content>
                          {PRIORITY_OPTIONS.map((opt) => (
                            <Select.Item key={opt.value} value={opt.value}>
                              <Select.ItemText>{opt.label}</Select.ItemText>
                              <Select.ItemIndicator />
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select.Root>
                    </HStack>
                  </HStack>

                  {activeThread.messages.length > 1 ? (
                    <Button variant="ghost" size="xs" onClick={handleToggleExpandAll}>
                      {allMessagesExpanded
                        ? "Collapse earlier"
                        : `Expand all (${activeThread.messages.length})`}
                    </Button>
                  ) : null}
                </HStack>

                {/* Collapsible Message Chain */}
                <VStack ref={threadScrollRef} gap="2.5" style={styles.threadScroll}>
                  {activeThread.messages.map((message) => {
                    const isOpen = expandedMessages.has(message.id);
                    const snippet = message.body[0] ?? "";
                    return (
                      <Collapsible.Root
                        key={message.id}
                        open={isOpen}
                        onOpenChange={(next) => toggleMessageExpanded(message.id, next)}
                        {...stylex.props(
                          styles.messageCard,
                          message.isInternalNote && styles.messageCardNote,
                        )}
                      >
                        <Collapsible.Trigger {...stylex.props(styles.messageTrigger)}>
                          <HStack gap="2.5" style={styles.messageTriggerLead}>
                            <Avatar.Root
                              size="sm"
                              variant="subtle"
                              palette={AVATAR_PALETTE[message.authorTone]}
                            >
                              <Avatar.Fallback>{message.authorInitials}</Avatar.Fallback>
                            </Avatar.Root>
                            <VStack gap="0.5">
                              <HStack wrap="wrap" gap="1.5">
                                <Text render={<span />} size="sm" weight="semibold">
                                  {message.author}
                                </Text>
                                {message.isInternalNote ? (
                                  <Badge variant="subtle" size="xs" palette={amberPalette}>
                                    <LockNoteIcon />
                                    Internal note
                                  </Badge>
                                ) : message.isTeam ? (
                                  <Badge variant="subtle" size="xs" palette={accentPalette}>
                                    Support
                                  </Badge>
                                ) : (
                                  <Text render={<span />} size="xs" tone="subtle" truncate="true">
                                    {message.authorEmail}
                                  </Text>
                                )}
                              </HStack>
                              {!isOpen ? (
                                <Text render={<span />} size="xs" variant="muted" truncate="true">
                                  {snippet}
                                </Text>
                              ) : null}
                            </VStack>
                          </HStack>

                          <HStack gap="1.5" style={styles.messageTriggerTrail}>
                            {(message.attachments?.length ?? 0) > 0 ? <PaperclipIcon /> : null}
                            <span>{message.sentAt}</span>
                            <ChevronDownIcon open={isOpen} />
                          </HStack>
                        </Collapsible.Trigger>

                        <Collapsible.Panel>
                          <div {...stylex.props(styles.messageBodyOuter)}>
                            <VStack gap="2.5" style={styles.messageBodyCopy}>
                              {message.body.map((paragraph, idx) => (
                                <Text key={idx} size="sm">
                                  {paragraph}
                                </Text>
                              ))}
                            </VStack>

                            {message.attachments && message.attachments.length > 0 ? (
                              <HStack wrap="wrap" gap="1.5" style={styles.attachmentStrip}>
                                {message.attachments.map((file) => (
                                  <button
                                    key={file.id}
                                    type="button"
                                    onClick={() =>
                                      queue.info(`Downloaded ${file.name}`, {
                                        description: `${file.sizeLabel} · Attached to ${activeThread.ticketNumber}`,
                                      })
                                    }
                                    {...stylex.props(styles.attachmentChip)}
                                  >
                                    <PaperclipIcon />
                                    <span>{file.name}</span>
                                    <span {...stylex.props(styles.attachmentSize)}>
                                      {file.sizeLabel}
                                    </span>
                                  </button>
                                ))}
                              </HStack>
                            ) : null}
                          </div>
                        </Collapsible.Panel>
                      </Collapsible.Root>
                    );
                  })}
                </VStack>

                {/* Live Reply / Internal Note Composer */}
                <VStack
                  render={
                    <form
                      onSubmit={(event) => {
                        event.preventDefault();
                        submitComposer(false);
                      }}
                    />
                  }
                  gap="2"
                  style={[
                    styles.composerShell,
                    composerMode === "note" && styles.composerShellNote,
                  ]}
                >
                  <HStack justify="between" wrap="wrap" gap="2">
                    <SegmentGroup.Root
                      size="xs"
                      value={composerMode}
                      onValueChange={(next) => {
                        if (next === "reply" || next === "note") setComposerMode(next);
                      }}
                      aria-label="Composer mode"
                    >
                      <SegmentGroup.Item value="reply">Send reply</SegmentGroup.Item>
                      <SegmentGroup.Item value="note">Internal note</SegmentGroup.Item>
                    </SegmentGroup.Root>

                    <Text render={<span />} size="xs" variant="muted" truncate="true">
                      {composerMode === "reply"
                        ? `To: ${activeThread.sender} <${activeThread.senderEmail}>`
                        : "Visible only to Northwind Dispatch team"}
                    </Text>
                  </HStack>

                  <Textarea
                    size="sm"
                    rows={3}
                    aria-label={
                      composerMode === "reply"
                        ? `Reply to ${activeThread.sender}`
                        : `Internal note on ${activeThread.ticketNumber}`
                    }
                    placeholder={
                      composerMode === "reply"
                        ? `Write a reply to ${activeThread.sender}…`
                        : "Add an internal handoff note or investigation detail…"
                    }
                    value={currentDraft}
                    onChange={(event) => handleDraftChange(event.target.value)}
                    onKeyDown={(event) => {
                      if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
                        event.preventDefault();
                        submitComposer(false);
                      }
                    }}
                    style={styles.composerTextarea}
                  />

                  <HStack justify="between" wrap="wrap" gap="2">
                    <Text render={<span />} size="xs" tone="subtle" style={styles.composerHint}>
                      ⌘/Ctrl + Enter to submit
                    </Text>

                    <HStack gap="2" style={styles.composerSubmitGroup}>
                      {composerMode === "reply" && activeThread.status !== "resolved" ? (
                        <Button
                          type="button"
                          variant="surface"
                          size="xs"
                          disabled={currentDraft.trim().length === 0}
                          onClick={() => submitComposer(true)}
                        >
                          Send &amp; resolve
                        </Button>
                      ) : null}
                      <Button
                        type="submit"
                        variant="solid"
                        size="xs"
                        palette={composerMode === "note" ? amberPalette : accentPalette}
                        disabled={currentDraft.trim().length === 0}
                      >
                        {composerMode === "note" ? <LockNoteIcon /> : <SendIcon />}
                        {composerMode === "note" ? "Add internal note" : "Send reply"}
                      </Button>
                    </HStack>
                  </HStack>
                </VStack>
              </>
            )}
          </Splitter.Panel>
        </Splitter.Root>
      </div>

      {/* Floating Bulk ActionBar */}
      {selectedThreads.length > 0 ? (
        <ActionBar.Positioner>
          <ActionBar.Content style={styles.actionBarContent}>
            <ActionBar.SelectionTrigger>
              <span>{selectedThreads.length} selected</span>
            </ActionBar.SelectionTrigger>
            <ActionBar.Separator />
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                setReadState(
                  selectedThreads.map((t) => t.id),
                  !anySelectedUnread,
                )
              }
            >
              <MailIcon unread={anySelectedUnread} />
              {anySelectedUnread ? "Mark read" : "Mark unread"}
            </Button>
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                toggleStar(
                  selectedThreads.map((t) => t.id),
                  anySelectedUnstarred,
                )
              }
            >
              <StarIcon filled={anySelectedUnstarred} />
              {anySelectedUnstarred ? "Star" : "Unstar"}
            </Button>
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                toggleSnooze(
                  selectedThreads.map((t) => t.id),
                  true,
                )
              }
            >
              <SnoozeIcon />
              Snooze
            </Button>
            <Button
              variant="ghost"
              size="xs"
              palette={redPalette}
              onClick={() => archiveThreads(selectedThreads.map((t) => t.id))}
            >
              <ArchiveIcon />
              Archive
            </Button>
            <ActionBar.Separator />
            <Button variant="ghost" size="xs" onClick={clearSelection}>
              Clear
            </Button>
          </ActionBar.Content>
        </ActionBar.Positioner>
      ) : null}

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

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