{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sift",
  "type": "registry:block",
  "title": "Sift",
  "description": "Structured filter bar for any list or table: a + Filter popover that slides property → operator → value (type-ahead fields, per-type operators, checkbox listbox, number range, and a range-selecting month calendar with presets), spring-in chips you edit in place part by part, an and/or toggle, saved views that crossfade chip sets with inline Save view, Clear all, and a result count rolling on Tally drums. Controlled or uncontrolled, keyboard-first (F, arrows, Backspace), with a pure applyFilters() helper to drive your rows.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/tally.json",
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/app/sift/sift.tsx",
      "type": "registry:block",
      "target": "components/crucible/sift.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, LayoutGroup, motion, useInView, type Transition } from \"motion/react\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { Tally } from \"@/components/crucible/tally\";\n\n/* ================================================================ types */\n\n/** How a field's values are compared and edited. */\nexport type SiftFieldType = \"text\" | \"select\" | \"number\" | \"date\" | \"boolean\";\n\n/** One choice of a `select` field. */\nexport interface SiftOption {\n  /** Stored / compared value. */\n  value: string;\n  /** Visible label. @default value */\n  label?: string;\n  /** Optional status dot color (any CSS color). */\n  color?: string;\n}\n\n/** A filterable property of your rows. */\nexport interface SiftField {\n  /** Row key read by `applyFilters` (`row[key]`). */\n  key: string;\n  /** Visible name in the property list and on chips. */\n  label: string;\n  /** Decides the operators and the value editor. */\n  type: SiftFieldType;\n  /** Choices for `select` fields (strings or `{ value, label, color }`). */\n  options?: (string | SiftOption)[];\n  /** 14px glyph (uses `currentColor`). A type glyph is used when omitted. */\n  icon?: React.ReactNode;\n}\n\n/**\n * Comparison operator. Per field type:\n * text `contains | is | is-not | starts-with`; select `any-of | none-of`;\n * number `eq | neq | gt | lt | between`; date `is | before | after | between`;\n * boolean `is-true | is-false`.\n */\nexport type SiftOperator =\n  | \"contains\"\n  | \"is\"\n  | \"is-not\"\n  | \"starts-with\"\n  | \"any-of\"\n  | \"none-of\"\n  | \"eq\"\n  | \"neq\"\n  | \"gt\"\n  | \"lt\"\n  | \"between\"\n  | \"before\"\n  | \"after\"\n  | \"is-true\"\n  | \"is-false\";\n\n/** Relative date ranges, resolved against \"today\" when filtering. */\nexport type SiftDatePreset = \"today\" | \"last-7\" | \"last-30\" | \"this-month\";\n\n/**\n * A filter's operand: `string` (text, or a `YYYY-MM-DD` date), `string[]`\n * (select), `number`, `[min, max]` (number between), `[from, to]` date keys\n * (date between) or `null` (boolean / preset).\n */\nexport type SiftFilterValue = string | number | boolean | string[] | [number, number] | [string, string] | null;\n\n/** One applied filter (one chip). */\nexport interface SiftFilter {\n  /** Stable id (chip key). */\n  id: string;\n  /** `SiftField.key` this filter targets. */\n  field: string;\n  operator: SiftOperator;\n  value: SiftFilterValue;\n  /** Date fields only: a relative range that overrides `value`. */\n  preset?: SiftDatePreset;\n}\n\n/** How chips combine: every filter must match (`and`) or any (`or`). */\nexport type SiftConjunction = \"and\" | \"or\";\n\n/** A named, saved chip set. */\nexport interface SiftView {\n  id: string;\n  label: string;\n  filters: SiftFilter[];\n  /** @default \"and\" */\n  conjunction?: SiftConjunction;\n}\n\n/** Imperative verbs exposed through the `ref` prop. */\nexport interface SiftHandle {\n  /** Open the filter popover — at the operator step when `fieldKey` is given. */\n  open: (fieldKey?: string) => void;\n  /** Close the popover (and views menu) if open. */\n  close: () => void;\n  /** Remove every filter. */\n  clear: () => void;\n  /** Replay the intro. */\n  replay: () => void;\n}\n\nexport interface SiftProps\n  extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"onChange\" | \"defaultValue\" | \"children\"> {\n  /**\n   * Filterable properties.\n   * @default issue-tracker sample fields (Status, Priority, Assignee, Title, Estimate, Updated, Failing checks)\n   */\n  fields?: SiftField[];\n  /** Controlled filters. Omit for uncontrolled use. */\n  value?: SiftFilter[];\n  /**\n   * Initial filters (uncontrolled).\n   * @default the \"Active work\" sample view when `fields` is omitted, otherwise none\n   */\n  defaultValue?: SiftFilter[];\n  /** Fires with the full next filter list on every add, edit, removal, clear or view switch. */\n  onChange?: (filters: SiftFilter[]) => void;\n  /** Controlled conjunction. */\n  conjunction?: SiftConjunction;\n  /** Initial conjunction (uncontrolled). @default \"and\" */\n  defaultConjunction?: SiftConjunction;\n  /** Fires when the and / or toggle between chips flips. */\n  onConjunctionChange?: (conjunction: SiftConjunction) => void;\n  /**\n   * Saved views in the views menu. Pass `[]` to hide the menu.\n   * @default sample views (All issues, Active work, My open, Failing this week, Urgent & high) when `fields` is omitted\n   */\n  views?: SiftView[];\n  /** Id of the view selected initially. @default \"active\" for the sample views, else the first view */\n  defaultView?: string;\n  /** Fires when a view is picked from the menu. */\n  onViewChange?: (view: SiftView) => void;\n  /**\n   * Called when a view is saved from \"Save view\". Return a Promise to show a\n   * pending state; rejecting keeps the name field open with the error. The\n   * view is added to the menu on success. Omit to hide \"Save view\".\n   */\n  onSaveView?: (view: SiftView) => void | Promise<unknown>;\n  /** Result count shown at the right; rolls on Tally drums when it changes. */\n  count?: number;\n  /** Optional total, shown as \"24 of 40\". */\n  total?: number;\n  /** Result noun. @default { one: \"result\", other: \"results\" } */\n  noun?: { one: string; other: string };\n  /** \"Today\" for date presets and the calendar (YYYY-MM-DD or Date). @default the viewer's local today */\n  today?: string | Date;\n  /** Accent for focus rings, the active chip, values and the Apply button. @default \"#e4e4e7\" */\n  accentColor?: string;\n  /** Imperative handle (`open(fieldKey?)`, `close()`, `clear()`, `replay()`). React 19 ref-as-prop. */\n  ref?: React.Ref<SiftHandle>;\n  /** Extra classes for the root. */\n  className?: string;\n}\n\n/* ================================================================ constants */\n\nconst DEFAULT_ACCENT = \"#e4e4e7\";\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\nconst SPRING: Transition = { type: \"spring\", stiffness: 520, damping: 34, mass: 0.7 };\nconst SLIDE: Transition = { type: \"spring\", stiffness: 480, damping: 40 };\nconst FADE: Transition = { duration: 0.18, ease: \"easeOut\" };\n/** Reduced motion: geometry snaps, only opacity fades. */\nconst REDUCED_T: Transition = { duration: 0, opacity: { duration: 0.18, ease: \"easeOut\" } };\nconst POP_W = 304;\n\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nconst MONTHS_LONG = [\n  \"January\",\n  \"February\",\n  \"March\",\n  \"April\",\n  \"May\",\n  \"June\",\n  \"July\",\n  \"August\",\n  \"September\",\n  \"October\",\n  \"November\",\n  \"December\",\n];\nconst WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"];\n\nconst PRESETS: { id: SiftDatePreset; label: string }[] = [\n  { id: \"today\", label: \"Today\" },\n  { id: \"last-7\", label: \"Last 7 days\" },\n  { id: \"last-30\", label: \"Last 30 days\" },\n  { id: \"this-month\", label: \"This month\" },\n];\nconst PRESET_LABEL: Record<SiftDatePreset, string> = {\n  today: \"Today\",\n  \"last-7\": \"Last 7 days\",\n  \"last-30\": \"Last 30 days\",\n  \"this-month\": \"This month\",\n};\n\ninterface OpDef {\n  id: SiftOperator;\n  label: string;\n  hint?: string;\n}\n\nconst OPS: Record<SiftFieldType, OpDef[]> = {\n  text: [\n    { id: \"contains\", label: \"contains\" },\n    { id: \"is\", label: \"is\" },\n    { id: \"is-not\", label: \"is not\" },\n    { id: \"starts-with\", label: \"starts with\" },\n  ],\n  select: [\n    { id: \"any-of\", label: \"is any of\" },\n    { id: \"none-of\", label: \"is none of\" },\n  ],\n  number: [\n    { id: \"eq\", label: \"=\", hint: \"equals\" },\n    { id: \"neq\", label: \"≠\", hint: \"not equal\" },\n    { id: \"gt\", label: \">\", hint: \"greater than\" },\n    { id: \"lt\", label: \"<\", hint: \"less than\" },\n    { id: \"between\", label: \"between\", hint: \"inclusive\" },\n  ],\n  date: [\n    { id: \"is\", label: \"is\" },\n    { id: \"before\", label: \"before\" },\n    { id: \"after\", label: \"after\" },\n    { id: \"between\", label: \"between\" },\n  ],\n  boolean: [\n    { id: \"is-true\", label: \"is true\" },\n    { id: \"is-false\", label: \"is false\" },\n  ],\n};\n\nfunction opLabel(type: SiftFieldType, op: SiftOperator): string {\n  return OPS[type].find((o) => o.id === op)?.label ?? op;\n}\n\n/* ================================================================ icons */\n\nconst svg = (d: React.ReactNode) => (\n  <svg\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    stroke=\"currentColor\"\n    strokeWidth=\"1.5\"\n    strokeLinecap=\"round\"\n    strokeLinejoin=\"round\"\n    className=\"size-3.5 shrink-0\"\n    aria-hidden\n  >\n    {d}\n  </svg>\n);\n\nconst Icon = {\n  plus: svg(<path d=\"M8 3.5v9M3.5 8h9\" />),\n  x: svg(<path d=\"m4.5 4.5 7 7m0-7-7 7\" />),\n  back: svg(<path d=\"M9.5 3.5 5 8l4.5 4.5\" />),\n  chevron: svg(<path d=\"m4.5 6.5 3.5 3.5 3.5-3.5\" />),\n  chevL: svg(<path d=\"M9.5 4 5.5 8l4 4\" />),\n  chevR: svg(<path d=\"m6.5 4 4 4-4 4\" />),\n  check: svg(<path d=\"m3.5 8.5 3 3 6-7\" />),\n  search: svg(\n    <>\n      <circle cx=\"7\" cy=\"7\" r=\"4.25\" />\n      <path d=\"m10.25 10.25 3 3\" />\n    </>\n  ),\n  views: svg(\n    <>\n      <path d=\"M2.5 5 8 2.5 13.5 5 8 7.5z\" />\n      <path d=\"m2.5 8 5.5 2.5L13.5 8\" />\n      <path d=\"m2.5 11 5.5 2.5 5.5-2.5\" />\n    </>\n  ),\n  funnel: svg(<path d=\"M2.5 3.5h11l-4.25 5v4l-2.5 1.25V8.5z\" />),\n  text: svg(<path d=\"M3 12.5 6 3.5l3 9M4 9.5h4M10.5 8.5c.4-.6 1-.9 1.75-.9 1 0 1.75.6 1.75 1.6v3.3M14 10.5c-2.2 0-3.5.4-3.5 1.2 0 .6.5 1 1.2 1 1.2 0 2.3-.8 2.3-2.2\" />),\n  select: svg(\n    <>\n      <circle cx=\"8\" cy=\"8\" r=\"5.25\" />\n      <circle cx=\"8\" cy=\"8\" r=\"1.75\" fill=\"currentColor\" stroke=\"none\" />\n    </>\n  ),\n  number: svg(<path d=\"M6 2.5 4.75 13.5M11.25 2.5 10 13.5M3 6h10.5M2.5 10H13\" />),\n  date: svg(\n    <>\n      <rect x=\"2.5\" y=\"3.5\" width=\"11\" height=\"10\" rx=\"2\" />\n      <path d=\"M2.5 7h11M5.5 2v3M10.5 2v3\" />\n    </>\n  ),\n  boolean: svg(\n    <>\n      <rect x=\"1.75\" y=\"4.5\" width=\"12.5\" height=\"7\" rx=\"3.5\" />\n      <circle cx=\"10.75\" cy=\"8\" r=\"1.9\" fill=\"currentColor\" stroke=\"none\" />\n    </>\n  ),\n  status: svg(\n    <>\n      <circle cx=\"8\" cy=\"8\" r=\"5.25\" strokeDasharray=\"2.2 1.6\" />\n      <path d=\"M8 4.75a3.25 3.25 0 0 1 0 6.5z\" fill=\"currentColor\" stroke=\"none\" />\n    </>\n  ),\n  priority: svg(<path d=\"M3.5 12.5v-3M8 12.5v-6M12.5 12.5v-9\" strokeWidth=\"1.75\" />),\n  person: svg(\n    <>\n      <circle cx=\"8\" cy=\"5.75\" r=\"2.5\" />\n      <path d=\"M3 13.5c.6-2.4 2.6-3.75 5-3.75s4.4 1.35 5 3.75\" />\n    </>\n  ),\n  estimate: svg(\n    <>\n      <path d=\"M8 2.5 13.5 5.5v5L8 13.5 2.5 10.5v-5z\" />\n      <path d=\"M2.5 5.5 8 8.5l5.5-3M8 8.5v5\" />\n    </>\n  ),\n  clock: svg(\n    <>\n      <circle cx=\"8\" cy=\"8\" r=\"5.5\" />\n      <path d=\"M8 5v3l2 1.5\" />\n    </>\n  ),\n  alert: svg(\n    <>\n      <path d=\"M8 2.5 14 13H2z\" />\n      <path d=\"M8 6.75v2.75M8 11.25v.01\" />\n    </>\n  ),\n};\n\nconst TYPE_ICON: Record<SiftFieldType, React.ReactNode> = {\n  text: Icon.text,\n  select: Icon.select,\n  number: Icon.number,\n  date: Icon.date,\n  boolean: Icon.boolean,\n};\n\n/* ================================================================ sample data */\n\n/** Sample issue-tracker fields used when `fields` is omitted. */\nexport const defaultSiftFields: SiftField[] = [\n  {\n    key: \"status\",\n    label: \"Status\",\n    type: \"select\",\n    icon: Icon.status,\n    options: [\n      { value: \"Backlog\", color: \"#71717a\" },\n      { value: \"Todo\", color: \"#d4d4d8\" },\n      { value: \"In progress\", color: \"#fbbf24\" },\n      { value: \"In review\", color: \"#818cf8\" },\n      { value: \"Done\", color: \"#4ade80\" },\n      { value: \"Canceled\", color: \"#52525b\" },\n    ],\n  },\n  {\n    key: \"priority\",\n    label: \"Priority\",\n    type: \"select\",\n    icon: Icon.priority,\n    options: [\n      { value: \"Urgent\", color: \"#f87171\" },\n      { value: \"High\", color: \"#fb923c\" },\n      { value: \"Medium\", color: \"#facc15\" },\n      { value: \"Low\", color: \"#a1a1aa\" },\n      { value: \"None\", color: \"#52525b\" },\n    ],\n  },\n  {\n    key: \"assignee\",\n    label: \"Assignee\",\n    type: \"select\",\n    icon: Icon.person,\n    options: [\"Mara Quill\", \"Jonah Reyes\", \"Ines Varga\", \"Kofi Mensah\", \"Priya Raman\", \"Unassigned\"],\n  },\n  { key: \"title\", label: \"Title\", type: \"text\", icon: Icon.text },\n  { key: \"estimate\", label: \"Estimate\", type: \"number\", icon: Icon.estimate },\n  { key: \"updated\", label: \"Updated\", type: \"date\", icon: Icon.clock },\n  { key: \"failing\", label: \"Failing checks\", type: \"boolean\", icon: Icon.alert },\n];\n\n/** Sample saved views for `defaultSiftFields`. */\nexport const defaultSiftViews: SiftView[] = [\n  { id: \"all\", label: \"All issues\", filters: [] },\n  {\n    id: \"active\",\n    label: \"Active work\",\n    filters: [\n      { id: \"v-active-status\", field: \"status\", operator: \"any-of\", value: [\"Todo\", \"In progress\", \"In review\"] },\n      { id: \"v-active-est\", field: \"estimate\", operator: \"gt\", value: 1 },\n    ],\n  },\n  {\n    id: \"mine\",\n    label: \"My open\",\n    filters: [\n      { id: \"v-mine-who\", field: \"assignee\", operator: \"any-of\", value: [\"Mara Quill\"] },\n      { id: \"v-mine-status\", field: \"status\", operator: \"none-of\", value: [\"Done\", \"Canceled\"] },\n    ],\n  },\n  {\n    id: \"failing\",\n    label: \"Failing this week\",\n    filters: [\n      { id: \"v-fail-bool\", field: \"failing\", operator: \"is-true\", value: null },\n      { id: \"v-fail-date\", field: \"updated\", operator: \"is\", value: null, preset: \"last-7\" },\n    ],\n  },\n  {\n    id: \"urgent\",\n    label: \"Urgent & high\",\n    filters: [{ id: \"v-urgent\", field: \"priority\", operator: \"any-of\", value: [\"Urgent\", \"High\"] }],\n  },\n];\n\n/* ================================================================ date helpers */\n\nconst pad = (n: number) => String(n).padStart(2, \"0\");\nfunction dkey(d: Date): string {\n  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n}\nfunction fromKey(k: string): Date {\n  const [y, m, d] = k.split(\"-\").map(Number);\n  return new Date(y, (m ?? 1) - 1, d ?? 1);\n}\nfunction addDays(k: string, n: number): string {\n  const d = fromKey(k);\n  d.setDate(d.getDate() + n);\n  return dkey(d);\n}\nfunction addMonths(month: string, n: number): string {\n  const [y, m] = month.split(\"-\").map(Number);\n  const d = new Date(y, m - 1 + n, 1);\n  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}`;\n}\n/** Coerces a row value (Date, epoch ms, ISO string) to a local `YYYY-MM-DD` key. */\nfunction toKey(v: unknown): string | null {\n  if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : dkey(v);\n  if (typeof v === \"number\") return Number.isFinite(v) ? dkey(new Date(v)) : null;\n  if (typeof v === \"string\") {\n    if (/^\\d{4}-\\d{2}-\\d{2}$/.test(v)) return v;\n    const d = new Date(v);\n    return Number.isNaN(d.getTime()) ? null : dkey(d);\n  }\n  return null;\n}\nfunction presetRange(p: SiftDatePreset, today: string): [string, string] {\n  if (p === \"today\") return [today, today];\n  if (p === \"last-7\") return [addDays(today, -6), today];\n  if (p === \"last-30\") return [addDays(today, -29), today];\n  const first = `${today.slice(0, 7)}-01`;\n  return [first, addDays(`${addMonths(today.slice(0, 7), 1)}-01`, -1)];\n}\nfunction fmtDay(k: string): string {\n  const d = fromKey(k);\n  return `${MONTHS[d.getMonth()]} ${d.getDate()}`;\n}\n\nconst subscribeNoop = () => () => {};\n/** Local today as `YYYY-MM-DD`; null on the server / during hydration. */\nfunction useTodayKey(override?: string | Date): string | null {\n  const live = React.useSyncExternalStore(\n    subscribeNoop,\n    () => dkey(new Date()),\n    () => null\n  );\n  if (override) return toKey(override);\n  return live;\n}\n\n/* ================================================================ pure filtering */\n\nfunction optionsOf(field: SiftField | undefined): Required<SiftOption>[] {\n  return (field?.options ?? []).map((o) =>\n    typeof o === \"string\"\n      ? { value: o, label: o, color: \"\" }\n      : { value: o.value, label: o.label ?? o.value, color: o.color ?? \"\" }\n  );\n}\n\nfunction matches(row: Record<string, unknown>, f: SiftFilter, field: SiftField, today: string): boolean {\n  const raw = row[field.key];\n  switch (field.type) {\n    case \"text\": {\n      const hay = String(raw ?? \"\").toLowerCase();\n      const needle = String(f.value ?? \"\").toLowerCase();\n      if (!needle) return true;\n      if (f.operator === \"is\") return hay === needle;\n      if (f.operator === \"is-not\") return hay !== needle;\n      if (f.operator === \"starts-with\") return hay.startsWith(needle);\n      return hay.includes(needle);\n    }\n    case \"select\": {\n      const sel = Array.isArray(f.value) ? f.value.map(String) : f.value == null ? [] : [String(f.value)];\n      if (!sel.length) return true;\n      const vals = Array.isArray(raw) ? raw.map(String) : raw == null ? [] : [String(raw)];\n      const hit = vals.some((v) => sel.includes(v));\n      return f.operator === \"none-of\" ? !hit : hit;\n    }\n    case \"number\": {\n      const n = typeof raw === \"number\" ? raw : Number(raw);\n      if (raw == null || Number.isNaN(n)) return false;\n      if (f.operator === \"between\" && Array.isArray(f.value)) {\n        const [a, b] = (f.value as number[]).map(Number);\n        return n >= Math.min(a, b) && n <= Math.max(a, b);\n      }\n      const v = Number(f.value);\n      if (f.operator === \"neq\") return n !== v;\n      if (f.operator === \"gt\") return n > v;\n      if (f.operator === \"lt\") return n < v;\n      return n === v;\n    }\n    case \"date\": {\n      const k = toKey(raw);\n      if (!k) return false;\n      if (f.preset) {\n        const [a, b] = presetRange(f.preset, today);\n        return k >= a && k <= b;\n      }\n      if (f.operator === \"between\" && Array.isArray(f.value)) {\n        const [a, b] = (f.value as string[]).map(String).sort();\n        return k >= a && k <= b;\n      }\n      const v = String(f.value ?? \"\");\n      if (!v) return true;\n      if (f.operator === \"before\") return k < v;\n      if (f.operator === \"after\") return k > v;\n      return k === v;\n    }\n    case \"boolean\":\n      return Boolean(raw) === (f.operator === \"is-true\");\n  }\n}\n\n/**\n * Pure helper: returns the rows that satisfy `filters` (AND by default, or OR),\n * reading `row[field.key]`. Filters for unknown fields are ignored. Date\n * values may be `Date`s, epoch ms or ISO strings; presets resolve against\n * `options.now` (default: the current date).\n */\nexport function applyFilters<T extends object>(\n  rows: readonly T[],\n  filters: readonly SiftFilter[],\n  fields: readonly SiftField[] = defaultSiftFields,\n  options: { conjunction?: SiftConjunction; now?: Date | string } = {}\n): T[] {\n  const active = filters\n    .map((f) => ({ f, field: fields.find((x) => x.key === f.field) }))\n    .filter((x): x is { f: SiftFilter; field: SiftField } => !!x.field);\n  if (!active.length) return rows.slice();\n  const today = toKey(options.now ?? new Date()) ?? dkey(new Date());\n  const any = options.conjunction === \"or\";\n  return rows.filter((row) => {\n    const r = row as Record<string, unknown>;\n    return any ? active.some((x) => matches(r, x.f, x.field, today)) : active.every((x) => matches(r, x.f, x.field, today));\n  });\n}\n\n/* ================================================================ misc helpers */\n\nfunction inkFor(hex: string): string {\n  const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());\n  if (!m) return \"#0a0a0a\";\n  const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join(\"\") : m[1];\n  const [r, g, b] = [0, 2, 4].map((i) => {\n    const c = parseInt(h.slice(i, i + 2), 16) / 255;\n    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n  });\n  const L = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n  return L > 0.36 ? \"#0a0a0a\" : \"#ffffff\";\n}\n\nfunction sig(filters: readonly SiftFilter[], conj: SiftConjunction): string {\n  return JSON.stringify([conj, filters.map((f) => [f.field, f.operator, f.value, f.preset ?? null])]);\n}\n\nfunction summarize(field: SiftField, f: SiftFilter): string {\n  switch (field.type) {\n    case \"text\":\n      return `“${String(f.value ?? \"\")}”`;\n    case \"select\": {\n      const opts = optionsOf(field);\n      const labels = (Array.isArray(f.value) ? f.value : []).map(\n        (v) => opts.find((o) => o.value === v)?.label ?? String(v)\n      );\n      return labels.length > 2 ? `${labels.slice(0, 2).join(\", \")} +${labels.length - 2}` : labels.join(\", \");\n    }\n    case \"number\":\n      return Array.isArray(f.value) ? `${f.value[0]} – ${f.value[1]}` : String(f.value ?? \"\");\n    case \"date\":\n      if (f.preset) return PRESET_LABEL[f.preset];\n      if (Array.isArray(f.value)) {\n        const [a, b] = (f.value as string[]).map(String).sort();\n        return a === b ? fmtDay(a) : `${fmtDay(a)} – ${fmtDay(b)}`;\n      }\n      return f.value ? fmtDay(String(f.value)) : \"\";\n    case \"boolean\":\n      return \"\";\n  }\n}\n\nfunction describe(field: SiftField, f: SiftFilter): string {\n  const v = summarize(field, f);\n  return `${field.label} ${opLabel(field.type, f.operator)}${v ? ` ${v}` : \"\"}`;\n}\n\n/* ================================================================ draft */\n\ninterface Draft {\n  editingId: string | null;\n  field: string | null;\n  operator: SiftOperator | null;\n  text: string;\n  sel: string[];\n  numA: string;\n  numB: string;\n  dateA: string | null;\n  dateB: string | null;\n  preset: SiftDatePreset | null;\n}\n\nconst EMPTY_DRAFT: Draft = {\n  editingId: null,\n  field: null,\n  operator: null,\n  text: \"\",\n  sel: [],\n  numA: \"\",\n  numB: \"\",\n  dateA: null,\n  dateB: null,\n  preset: null,\n};\n\nfunction draftFrom(f: SiftFilter): Draft {\n  const d: Draft = { ...EMPTY_DRAFT, editingId: f.id, field: f.field, operator: f.operator };\n  const v = f.value;\n  if (typeof v === \"string\") {\n    d.text = v;\n    d.dateA = /^\\d{4}-\\d{2}-\\d{2}$/.test(v) ? v : null;\n  }\n  if (Array.isArray(v)) {\n    if (typeof v[0] === \"number\") {\n      d.numA = String(v[0]);\n      d.numB = String(v[1] ?? \"\");\n    } else if (f.operator === \"between\" && v.length === 2 && /^\\d{4}-/.test(String(v[0]))) {\n      d.dateA = String(v[0]);\n      d.dateB = String(v[1]);\n    } else d.sel = v.map(String);\n  }\n  if (typeof v === \"number\") d.numA = String(v);\n  d.preset = f.preset ?? null;\n  return d;\n}\n\nconst isNum = (s: string) => s.trim() !== \"\" && Number.isFinite(Number(s));\n\nfunction buildFilter(d: Draft, field: SiftField, id: string): SiftFilter | null {\n  const op = d.operator;\n  if (!op) return null;\n  const base = { id, field: field.key, operator: op };\n  switch (field.type) {\n    case \"text\":\n      return d.text.trim() ? { ...base, value: d.text.trim() } : null;\n    case \"select\":\n      return d.sel.length ? { ...base, value: d.sel } : null;\n    case \"number\":\n      if (op === \"between\")\n        return isNum(d.numA) && isNum(d.numB)\n          ? { ...base, value: [Number(d.numA), Number(d.numB)].sort((a, b) => a - b) as [number, number] }\n          : null;\n      return isNum(d.numA) ? { ...base, value: Number(d.numA) } : null;\n    case \"date\":\n      if (d.preset) return { ...base, operator: \"is\", value: null, preset: d.preset };\n      if (!d.dateA) return null;\n      if (op === \"between\") {\n        const pair = [d.dateA, d.dateB ?? d.dateA].sort() as [string, string];\n        return { ...base, value: pair };\n      }\n      return { ...base, value: d.dateA };\n    case \"boolean\":\n      return op === \"is-true\" || op === \"is-false\" ? { ...base, value: null } : null;\n  }\n}\n\n/* ================================================================ small pieces */\n\ntype Step = \"field\" | \"operator\" | \"value\";\nconst STEP_INDEX: Record<Step, number> = { field: 0, operator: 1, value: 2 };\n\nfunction Dot({ color }: { color: string }) {\n  if (!color) return null;\n  return <span aria-hidden className=\"size-2 shrink-0 rounded-full\" style={{ background: color }} />;\n}\n\nconst FOCUS =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-[var(--sift-accent)] focus-visible:ring-offset-1 focus-visible:ring-offset-neutral-900\";\n\n/** Keyboard model shared by the listboxes: Up/Down/Home/End move, Enter picks. */\nfunction listKeys(\n  e: React.KeyboardEvent,\n  count: number,\n  active: number,\n  setActive: (n: number) => void,\n  pick: (n: number) => void\n) {\n  if (!count) return;\n  if (e.key === \"ArrowDown\") {\n    e.preventDefault();\n    setActive((active + 1) % count);\n  } else if (e.key === \"ArrowUp\") {\n    e.preventDefault();\n    setActive((active - 1 + count) % count);\n  } else if (e.key === \"Home\") {\n    e.preventDefault();\n    setActive(0);\n  } else if (e.key === \"End\") {\n    e.preventDefault();\n    setActive(count - 1);\n  } else if (e.key === \"Enter\") {\n    e.preventDefault();\n    pick(active);\n  }\n}\n\nfunction useFocusOnMount<T extends HTMLElement>() {\n  const ref = React.useRef<T>(null);\n  React.useEffect(() => {\n    ref.current?.focus({ preventScroll: true });\n  }, []);\n  return ref;\n}\n\n/* ---------------------------------------------------------------- field step */\n\nfunction FieldStep({\n  uid,\n  fields,\n  selected,\n  onPick,\n}: {\n  uid: string;\n  fields: SiftField[];\n  selected: string | null;\n  onPick: (key: string) => void;\n}) {\n  const [q, setQ] = React.useState(\"\");\n  const [active, setActive] = React.useState(() => Math.max(0, fields.findIndex((f) => f.key === selected)));\n  const input = useFocusOnMount<HTMLInputElement>();\n  const shown = React.useMemo(() => {\n    const s = q.trim().toLowerCase();\n    return s ? fields.filter((f) => f.label.toLowerCase().includes(s)) : fields;\n  }, [fields, q]);\n  const act = Math.min(active, shown.length - 1);\n  const listId = `${uid}-fields`;\n\n  return (\n    <div className=\"p-1.5\">\n      <label className=\"relative flex items-center\">\n        <span className=\"pointer-events-none absolute left-2.5 text-white/35\">{Icon.search}</span>\n        <input\n          ref={input}\n          value={q}\n          onChange={(e) => {\n            setQ(e.target.value);\n            setActive(0);\n          }}\n          onKeyDown={(e) => listKeys(e, shown.length, act, setActive, (i) => shown[i] && onPick(shown[i].key))}\n          role=\"combobox\"\n          aria-expanded\n          aria-controls={listId}\n          aria-activedescendant={shown[act] ? `${listId}-${shown[act].key}` : undefined}\n          aria-label=\"Filter by property\"\n          placeholder=\"Filter by…\"\n          className=\"h-9 w-full rounded-lg border border-white/[0.08] bg-white/[0.03] pl-8 pr-2.5 text-[13px] text-white placeholder:text-white/35 outline-none transition-colors focus:border-[color-mix(in_srgb,var(--sift-accent)_45%,transparent)]\"\n        />\n      </label>\n      <ul id={listId} role=\"listbox\" aria-label=\"Properties\" className=\"mt-1.5 max-h-64 overflow-y-auto\">\n        {shown.map((f, i) => (\n          <li\n            key={f.key}\n            id={`${listId}-${f.key}`}\n            role=\"option\"\n            aria-selected={i === act}\n            onPointerMove={() => setActive(i)}\n            onClick={() => onPick(f.key)}\n            className={cn(\n              \"flex h-8 cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-[13px] text-white/75\",\n              i === act && \"bg-white/[0.06] text-white\"\n            )}\n          >\n            <span className=\"text-white/45\">{f.icon ?? TYPE_ICON[f.type]}</span>\n            <span className=\"flex-1 truncate\">{f.label}</span>\n            {f.key === selected && <span className=\"text-[var(--sift-accent)]\">{Icon.check}</span>}\n          </li>\n        ))}\n        {!shown.length && <li className=\"px-2.5 py-3 text-[12.5px] text-white/40\">No matching properties</li>}\n      </ul>\n    </div>\n  );\n}\n\n/* ---------------------------------------------------------------- operator step */\n\nfunction OperatorStep({\n  uid,\n  type,\n  selected,\n  onPick,\n}: {\n  uid: string;\n  type: SiftFieldType;\n  selected: SiftOperator | null;\n  onPick: (op: SiftOperator) => void;\n}) {\n  const ops = OPS[type];\n  const [active, setActive] = React.useState(() => Math.max(0, ops.findIndex((o) => o.id === selected)));\n  const list = useFocusOnMount<HTMLUListElement>();\n  const listId = `${uid}-ops`;\n  return (\n    <div className=\"p-1.5\">\n      <ul\n        ref={list}\n        id={listId}\n        role=\"listbox\"\n        tabIndex={0}\n        aria-label=\"Operator\"\n        aria-activedescendant={`${listId}-${ops[active]?.id}`}\n        onKeyDown={(e) => listKeys(e, ops.length, active, setActive, (i) => onPick(ops[i].id))}\n        className=\"rounded-lg outline-none focus-visible:ring-1 focus-visible:ring-white/10\"\n      >\n        {ops.map((o, i) => (\n          <li\n            key={o.id}\n            id={`${listId}-${o.id}`}\n            role=\"option\"\n            aria-selected={i === active}\n            onPointerMove={() => setActive(i)}\n            onClick={() => onPick(o.id)}\n            className={cn(\n              \"flex h-8 cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-[13px] text-white/75\",\n              i === active && \"bg-white/[0.06] text-white\"\n            )}\n          >\n            <span className={cn(\"min-w-0 flex-1 truncate\", o.label.length === 1 && \"font-mono text-[13px]\")}>\n              {o.label}\n              {o.hint && <span className=\"ml-2 font-sans text-[12px] text-white/35\">{o.hint}</span>}\n            </span>\n            {o.id === selected && <span className=\"text-[var(--sift-accent)]\">{Icon.check}</span>}\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\n/* ---------------------------------------------------------------- value editors */\n\nconst INPUT =\n  \"h-9 w-full min-w-0 rounded-lg border border-white/[0.08] bg-white/[0.03] px-2.5 text-[13px] text-white tabular-nums placeholder:text-white/30 outline-none transition-colors focus:border-[color-mix(in_srgb,var(--sift-accent)_45%,transparent)]\";\n\nfunction TextEditor({ draft, set, submit }: { draft: Draft; set: (p: Partial<Draft>) => void; submit: () => void }) {\n  const ref = useFocusOnMount<HTMLInputElement>();\n  return (\n    <div className=\"p-1.5\">\n      <input\n        ref={ref}\n        value={draft.text}\n        onChange={(e) => set({ text: e.target.value })}\n        onKeyDown={(e) => {\n          if (e.key === \"Enter\") {\n            e.preventDefault();\n            submit();\n          }\n        }}\n        aria-label=\"Value\"\n        placeholder=\"Type a value…\"\n        className={INPUT}\n      />\n    </div>\n  );\n}\n\nfunction SelectEditor({\n  uid,\n  field,\n  draft,\n  set,\n  submit,\n}: {\n  uid: string;\n  field: SiftField;\n  draft: Draft;\n  set: (p: Partial<Draft>) => void;\n  submit: () => void;\n}) {\n  const opts = React.useMemo(() => optionsOf(field), [field]);\n  const [q, setQ] = React.useState(\"\");\n  const [active, setActive] = React.useState(0);\n  const input = useFocusOnMount<HTMLInputElement>();\n  const shown = React.useMemo(() => {\n    const s = q.trim().toLowerCase();\n    return s ? opts.filter((o) => o.label.toLowerCase().includes(s)) : opts;\n  }, [opts, q]);\n  const act = Math.min(active, shown.length - 1);\n  const toggle = (v: string) =>\n    set({ sel: draft.sel.includes(v) ? draft.sel.filter((x) => x !== v) : [...draft.sel, v] });\n  const listId = `${uid}-opts`;\n  return (\n    <div className=\"p-1.5\">\n      <label className=\"relative flex items-center\">\n        <span className=\"pointer-events-none absolute left-2.5 text-white/35\">{Icon.search}</span>\n        <input\n          ref={input}\n          value={q}\n          onChange={(e) => {\n            setQ(e.target.value);\n            setActive(0);\n          }}\n          onKeyDown={(e) => {\n            if (e.key === \" \" && !q) {\n              e.preventDefault();\n              if (shown[act]) toggle(shown[act].value);\n              return;\n            }\n            if (e.key === \"Enter\") {\n              e.preventDefault();\n              // Enter toggles while searching an unselected option; otherwise applies.\n              if (q && shown[act] && !draft.sel.includes(shown[act].value)) {\n                toggle(shown[act].value);\n                setQ(\"\");\n              } else submit();\n              return;\n            }\n            listKeys(e, shown.length, act, setActive, () => {});\n          }}\n          role=\"combobox\"\n          aria-expanded\n          aria-controls={listId}\n          aria-activedescendant={shown[act] ? `${listId}-${act}` : undefined}\n          aria-label={`Search ${field.label.toLowerCase()} (Space toggles, Enter applies)`}\n          placeholder={`Search ${field.label.toLowerCase()}…`}\n          className={cn(INPUT, \"pl-8\")}\n        />\n      </label>\n      <ul\n        id={listId}\n        role=\"listbox\"\n        aria-multiselectable\n        aria-label={field.label}\n        className=\"mt-1.5 max-h-56 overflow-y-auto\"\n      >\n        {shown.map((o, i) => {\n          const on = draft.sel.includes(o.value);\n          return (\n            <li\n              key={o.value}\n              id={`${listId}-${i}`}\n              role=\"option\"\n              aria-selected={on}\n              onPointerMove={() => setActive(i)}\n              onClick={() => toggle(o.value)}\n              className={cn(\n                \"flex h-8 cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-[13px] text-white/75\",\n                i === act && \"bg-white/[0.06] text-white\"\n              )}\n            >\n              <span\n                aria-hidden\n                className={cn(\n                  \"grid size-4 shrink-0 place-items-center rounded-[5px] border transition-colors duration-150\",\n                  on ? \"border-transparent\" : \"border-white/20 bg-white/[0.02]\"\n                )}\n                style={on ? { background: \"var(--sift-accent)\", color: \"var(--sift-ink)\" } : undefined}\n              >\n                {on && (\n                  <svg viewBox=\"0 0 16 16\" className=\"size-3\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.25\" aria-hidden>\n                    <path d=\"m3.5 8.5 3 3 6-7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                  </svg>\n                )}\n              </span>\n              <Dot color={o.color} />\n              <span className=\"flex-1 truncate\">{o.label}</span>\n            </li>\n          );\n        })}\n        {!shown.length && <li className=\"px-2.5 py-3 text-[12.5px] text-white/40\">No matches</li>}\n      </ul>\n    </div>\n  );\n}\n\nfunction NumberEditor({ draft, set, submit }: { draft: Draft; set: (p: Partial<Draft>) => void; submit: () => void }) {\n  const ref = useFocusOnMount<HTMLInputElement>();\n  const between = draft.operator === \"between\";\n  const onKey = (e: React.KeyboardEvent) => {\n    if (e.key === \"Enter\") {\n      e.preventDefault();\n      submit();\n    }\n  };\n  const bad = (s: string) => s.trim() !== \"\" && !isNum(s);\n  return (\n    <div className=\"flex items-center gap-2 p-1.5\">\n      <input\n        ref={ref}\n        inputMode=\"decimal\"\n        value={draft.numA}\n        onChange={(e) => set({ numA: e.target.value })}\n        onKeyDown={onKey}\n        aria-label={between ? \"Minimum\" : \"Value\"}\n        aria-invalid={bad(draft.numA) || undefined}\n        placeholder={between ? \"Min\" : \"0\"}\n        className={cn(INPUT, bad(draft.numA) && \"border-red-400/50\")}\n      />\n      {between && (\n        <>\n          <span className=\"shrink-0 text-[12px] text-white/40\">and</span>\n          <input\n            inputMode=\"decimal\"\n            value={draft.numB}\n            onChange={(e) => set({ numB: e.target.value })}\n            onKeyDown={onKey}\n            aria-label=\"Maximum\"\n            aria-invalid={bad(draft.numB) || undefined}\n            placeholder=\"Max\"\n            className={cn(INPUT, bad(draft.numB) && \"border-red-400/50\")}\n          />\n        </>\n      )}\n    </div>\n  );\n}\n\nfunction monthGrid(month: string): string[] {\n  const first = fromKey(`${month}-01`);\n  const offset = (first.getDay() + 6) % 7;\n  const start = addDays(`${month}-01`, -offset);\n  return Array.from({ length: 42 }, (_, i) => addDays(start, i));\n}\n\nfunction Calendar({\n  range,\n  a,\n  b,\n  today,\n  onSelect,\n  submit,\n}: {\n  range: boolean;\n  a: string | null;\n  b: string | null;\n  today: string;\n  onSelect: (a: string, b: string | null) => void;\n  submit: () => void;\n}) {\n  const init = a ?? today;\n  const [month, setMonth] = React.useState(init.slice(0, 7));\n  const [focusKey, setFocusKey] = React.useState(init);\n  const [hover, setHover] = React.useState<string | null>(null);\n  const [kbd, setKbd] = React.useState(0);\n  const grid = React.useRef<HTMLDivElement>(null);\n  const days = React.useMemo(() => monthGrid(month), [month]);\n  const [y, m] = month.split(\"-\").map(Number);\n\n  React.useEffect(() => {\n    if (!kbd) return;\n    grid.current?.querySelector<HTMLButtonElement>(`[data-day=\"${focusKey}\"]`)?.focus({ preventScroll: true });\n  }, [kbd, focusKey]);\n\n  const lo = a && range ? [a, b ?? hover ?? a].sort()[0] : a;\n  const hi = a && range ? [a, b ?? hover ?? a].sort()[1] : a;\n\n  const pick = (k: string) => {\n    if (!range) return onSelect(k, null);\n    if (!a || b) return onSelect(k, null);\n    return onSelect(k < a ? k : a, k < a ? a : k);\n  };\n\n  const move = (n: number) => {\n    const next = addDays(focusKey, n);\n    setFocusKey(next);\n    if (next.slice(0, 7) !== month) setMonth(next.slice(0, 7));\n    setKbd((x) => x + 1);\n  };\n\n  return (\n    <div className=\"px-2 pb-1 pt-0.5\">\n      <div className=\"flex items-center justify-between px-0.5 pb-1\">\n        <span className=\"text-[12.5px] font-medium text-white/85\" aria-live=\"polite\">\n          {MONTHS_LONG[m - 1]} {y}\n        </span>\n        <div className=\"flex gap-0.5\">\n          {[\n            { d: -1, icon: Icon.chevL, label: \"Previous month\" },\n            { d: 1, icon: Icon.chevR, label: \"Next month\" },\n          ].map((x) => (\n            <button\n              key={x.d}\n              type=\"button\"\n              aria-label={x.label}\n              onClick={() => {\n                const nm = addMonths(month, x.d);\n                setMonth(nm);\n                setFocusKey(`${nm}-01`);\n              }}\n              className={cn(\"grid size-7 place-items-center rounded-md text-white/50 hover:bg-white/[0.06] hover:text-white\", FOCUS)}\n            >\n              {x.icon}\n            </button>\n          ))}\n        </div>\n      </div>\n      <div\n        ref={grid}\n        role=\"grid\"\n        aria-label={`${MONTHS_LONG[m - 1]} ${y}${range ? \", pick a start and end date\" : \"\"}`}\n        onPointerLeave={() => setHover(null)}\n        onKeyDown={(e) => {\n          const map: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };\n          if (map[e.key] !== undefined) {\n            e.preventDefault();\n            move(map[e.key]);\n          } else if (e.key === \"PageUp\" || e.key === \"PageDown\") {\n            e.preventDefault();\n            move(e.key === \"PageUp\" ? -28 : 28);\n          } else if (e.key === \"Enter\" && a && (!range || b) && focusKey === (range ? b : a)) {\n            e.preventDefault();\n            submit();\n          }\n        }}\n      >\n        <div role=\"row\" className=\"grid grid-cols-7\">\n          {WEEKDAYS.map((w) => (\n            <span key={w} role=\"columnheader\" className=\"grid h-7 place-items-center text-[11px] text-white/35\">\n              {w}\n            </span>\n          ))}\n        </div>\n        {[0, 1, 2, 3, 4, 5].map((r) => (\n          <div role=\"row\" key={r} className=\"grid grid-cols-7\">\n            {days.slice(r * 7, r * 7 + 7).map((k) => {\n              const out = k.slice(0, 7) !== month;\n              const isEnd = k === lo || k === hi;\n              const inside = !!lo && !!hi && k > lo && k < hi;\n              const d = fromKey(k);\n              return (\n                <div role=\"gridcell\" key={k} aria-selected={isEnd || inside} className=\"relative h-8 p-px\">\n                  {(inside || (isEnd && lo !== hi)) && (\n                    <span\n                      aria-hidden\n                      className={cn(\n                        \"absolute inset-y-px bg-[color-mix(in_srgb,var(--sift-accent)_12%,transparent)]\",\n                        k === lo ? \"left-1/2 right-0\" : k === hi ? \"left-0 right-1/2\" : \"inset-x-0\"\n                      )}\n                    />\n                  )}\n                  <button\n                    type=\"button\"\n                    data-day={k}\n                    tabIndex={k === focusKey ? 0 : -1}\n                    aria-label={`${MONTHS_LONG[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}${k === today ? \" (today)\" : \"\"}`}\n                    onClick={() => {\n                      setFocusKey(k);\n                      pick(k);\n                    }}\n                    onPointerEnter={() => setHover(k)}\n                    className={cn(\n                      \"relative grid h-full w-full place-items-center rounded-md text-[12.5px] tabular-nums transition-colors\",\n                      FOCUS,\n                      out ? \"text-white/25\" : \"text-white/75\",\n                      !isEnd && \"hover:bg-white/[0.07] hover:text-white\",\n                      isEnd && \"font-semibold\"\n                    )}\n                    style={isEnd ? { background: \"var(--sift-accent)\", color: \"var(--sift-ink)\" } : undefined}\n                  >\n                    {d.getDate()}\n                    {k === today && (\n                      <span\n                        aria-hidden\n                        className=\"absolute bottom-1 left-1/2 size-[3px] -translate-x-1/2 rounded-full\"\n                        style={{ background: isEnd ? \"var(--sift-ink)\" : \"var(--sift-accent)\" }}\n                      />\n                    )}\n                  </button>\n                </div>\n              );\n            })}\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n\nfunction DateEditor({\n  draft,\n  set,\n  today,\n  submit,\n}: {\n  draft: Draft;\n  set: (p: Partial<Draft>) => void;\n  today: string;\n  submit: () => void;\n}) {\n  const first = useFocusOnMount<HTMLDivElement>();\n  return (\n    <div>\n      <div ref={first} tabIndex={-1} className=\"flex flex-wrap gap-1 px-2 pb-1.5 pt-1.5 outline-none\" role=\"group\" aria-label=\"Presets\">\n        {PRESETS.map((p) => {\n          const on = draft.preset === p.id;\n          return (\n            <button\n              key={p.id}\n              type=\"button\"\n              aria-pressed={on}\n              onClick={() => set({ preset: on ? null : p.id, dateA: null, dateB: null })}\n              className={cn(\n                \"h-7 rounded-md border px-2 text-[12px] transition-colors\",\n                FOCUS,\n                on\n                  ? \"border-[color-mix(in_srgb,var(--sift-accent)_45%,transparent)] bg-[color-mix(in_srgb,var(--sift-accent)_14%,transparent)] text-white\"\n                  : \"border-white/[0.08] text-white/60 hover:border-white/15 hover:text-white\"\n              )}\n            >\n              {p.label}\n            </button>\n          );\n        })}\n      </div>\n      <div className=\"mx-2 h-px bg-white/[0.06]\" />\n      <Calendar\n        range={draft.operator === \"between\"}\n        a={draft.preset ? null : draft.dateA}\n        b={draft.preset ? null : draft.dateB}\n        today={today}\n        onSelect={(a, b) => set({ dateA: a, dateB: b, preset: null })}\n        submit={submit}\n      />\n    </div>\n  );\n}\n\n/* ================================================================ views menu */\n\nfunction ViewsMenu({\n  uid,\n  views,\n  activeId,\n  edited,\n  open,\n  setOpen,\n  onPick,\n}: {\n  uid: string;\n  views: SiftView[];\n  activeId: string | null;\n  edited: boolean;\n  open: boolean;\n  setOpen: (o: boolean) => void;\n  onPick: (v: SiftView) => void;\n}) {\n  const btn = React.useRef<HTMLButtonElement>(null);\n  const menu = React.useRef<HTMLDivElement>(null);\n  const reduced = useReducedMotion();\n  const active = views.find((v) => v.id === activeId);\n  const menuId = `${uid}-views`;\n\n  React.useEffect(() => {\n    if (!open) return;\n    const idx = Math.max(0, views.findIndex((v) => v.id === activeId));\n    const id = requestAnimationFrame(() =>\n      menu.current?.querySelectorAll<HTMLElement>(\"[role=menuitemradio]\")[idx]?.focus({ preventScroll: true })\n    );\n    const onDown = (e: PointerEvent) => {\n      if (!menu.current?.contains(e.target as Node) && !btn.current?.contains(e.target as Node)) setOpen(false);\n    };\n    document.addEventListener(\"pointerdown\", onDown);\n    return () => {\n      cancelAnimationFrame(id);\n      document.removeEventListener(\"pointerdown\", onDown);\n    };\n  }, [open, views, activeId, setOpen]);\n\n  const close = () => {\n    setOpen(false);\n    btn.current?.focus({ preventScroll: true });\n  };\n\n  return (\n    <div className=\"relative min-w-0\">\n      <button\n        ref={btn}\n        type=\"button\"\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        aria-controls={open ? menuId : undefined}\n        onClick={() => setOpen(!open)}\n        onKeyDown={(e) => {\n          if (e.key === \"ArrowDown\" && !open) {\n            e.preventDefault();\n            setOpen(true);\n          }\n        }}\n        className={cn(\n          \"flex h-8 min-w-0 max-w-full items-center gap-2 rounded-lg px-2 text-[13px] font-medium text-white/90 transition-colors hover:bg-white/[0.05]\",\n          open && \"bg-white/[0.05]\",\n          FOCUS\n        )}\n      >\n        <span className=\"text-white/45\">{Icon.views}</span>\n        <span className=\"truncate\">{active?.label ?? \"Custom view\"}</span>\n        {edited && (\n          <span className=\"shrink-0 rounded-[5px] border border-white/10 px-1 py-px text-[10.5px] font-normal leading-tight text-white/50\">\n            Edited\n          </span>\n        )}\n        <span className={cn(\"text-white/40 transition-transform duration-200\", open && \"rotate-180\")}>{Icon.chevron}</span>\n      </button>\n      <AnimatePresence>\n        {open && (\n          <motion.div\n            ref={menu}\n            id={menuId}\n            role=\"menu\"\n            aria-label=\"Saved views\"\n            initial={reduced ? { opacity: 0 } : { opacity: 0, y: -4, scale: 0.98 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={reduced ? { opacity: 0 } : { opacity: 0, y: -4, scale: 0.98 }}\n            transition={reduced ? FADE : { duration: 0.16, ease: EASE }}\n            style={{ transformOrigin: \"top left\" }}\n            onKeyDown={(e) => {\n              const items = [...(menu.current?.querySelectorAll<HTMLElement>(\"[role=menuitemradio]\") ?? [])];\n              const i = items.indexOf(document.activeElement as HTMLElement);\n              if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n                e.preventDefault();\n                const n = (i + (e.key === \"ArrowDown\" ? 1 : -1) + items.length) % items.length;\n                items[n]?.focus({ preventScroll: true });\n              } else if (e.key === \"Home\" || e.key === \"End\") {\n                e.preventDefault();\n                items[e.key === \"Home\" ? 0 : items.length - 1]?.focus({ preventScroll: true });\n              } else if (e.key === \"Escape\" || e.key === \"Tab\") {\n                e.preventDefault();\n                close();\n              }\n            }}\n            className=\"absolute left-0 top-[calc(100%+6px)] z-40 w-60 max-w-[calc(100cqw-1rem)] rounded-xl border border-white/10 bg-[#141416] p-1 shadow-[0_24px_48px_-12px_rgba(0,0,0,0.75),0_0_0_1px_rgba(0,0,0,0.4)]\"\n          >\n            <p className=\"px-2.5 pb-1 pt-1.5 text-[11px] font-medium uppercase tracking-[0.08em] text-white/35\">Views</p>\n            {views.map((v) => {\n              const on = v.id === activeId;\n              return (\n                <div\n                  key={v.id}\n                  role=\"menuitemradio\"\n                  aria-checked={on}\n                  tabIndex={-1}\n                  onClick={() => {\n                    onPick(v);\n                    close();\n                  }}\n                  onKeyDown={(e) => {\n                    if (e.key === \"Enter\" || e.key === \" \") {\n                      e.preventDefault();\n                      onPick(v);\n                      close();\n                    }\n                  }}\n                  className=\"flex h-8 cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-[13px] text-white/75 outline-none hover:bg-white/[0.06] hover:text-white focus-visible:bg-white/[0.06] focus-visible:text-white\"\n                >\n                  <span className=\"grid w-3.5 place-items-center text-[var(--sift-accent)]\">{on && Icon.check}</span>\n                  <span className=\"flex-1 truncate\">{v.label}</span>\n                  <span className=\"text-[11.5px] tabular-nums text-white/30\">{v.filters.length || \"—\"}</span>\n                </div>\n              );\n            })}\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\n/* ================================================================ main */\n\n/**\n * Sift — a structured filter builder for any list or table. \"+ Filter\" opens\n * one popover that slides property → operator → value; applied filters become\n * editable chips joined by an and/or toggle; saved views swap chip sets with a\n * crossfade. Pair it with the exported `applyFilters(rows, filters, fields)`.\n */\nexport function Sift({\n  fields: fieldsProp,\n  value,\n  defaultValue,\n  onChange,\n  conjunction: conjProp,\n  defaultConjunction = \"and\",\n  onConjunctionChange,\n  views: viewsProp,\n  defaultView,\n  onViewChange,\n  onSaveView,\n  count,\n  total,\n  noun = { one: \"result\", other: \"results\" },\n  today: todayProp,\n  accentColor = DEFAULT_ACCENT,\n  ref,\n  className,\n  style,\n  onKeyDown,\n  ...rest\n}: SiftProps) {\n  const reduced = useReducedMotion();\n  const uid = React.useId().replace(/:/g, \"\");\n  const sample = !fieldsProp;\n  const fields = fieldsProp ?? defaultSiftFields;\n  const baseViews = React.useMemo(() => viewsProp ?? (sample ? defaultSiftViews : []), [viewsProp, sample]);\n  const initialViewId = defaultView ?? (sample && !viewsProp ? \"active\" : baseViews[0]?.id) ?? null;\n\n  /* ----- state */\n  const [innerFilters, setInnerFilters] = React.useState<SiftFilter[]>(\n    () => defaultValue ?? (sample ? (baseViews.find((v) => v.id === initialViewId)?.filters ?? []) : [])\n  );\n  const filters = value ?? innerFilters;\n  const [innerConj, setInnerConj] = React.useState<SiftConjunction>(defaultConjunction);\n  const conj = conjProp ?? innerConj;\n  const [saved, setSaved] = React.useState<SiftView[]>([]);\n  const views = React.useMemo(() => [...baseViews, ...saved], [baseViews, saved]);\n  const [activeViewId, setActiveViewId] = React.useState<string | null>(initialViewId);\n  const activeView = views.find((v) => v.id === activeViewId);\n  const edited = activeView\n    ? sig(activeView.filters, activeView.conjunction ?? \"and\") !== sig(filters, conj)\n    : filters.length > 0;\n  const [epoch, setEpoch] = React.useState(0);\n  const [announce, setAnnounce] = React.useState(\"\");\n  const idSeq = React.useRef(0);\n  const freshId = (prefix: string, taken: string[]) => {\n    let id = \"\";\n    do id = `${prefix}-${uid}-${(idSeq.current++).toString(36)}`;\n    while (taken.includes(id));\n    return id;\n  };\n  const todayKey = useTodayKey(todayProp) ?? \"2026-01-01\";\n\n  const [pop, setPop] = React.useState<{ anchor: string; step: Step; dir: 1 | -1 } | null>(null);\n  const [popPos, setPopPos] = React.useState<{ left: number; top: number; width: number } | null>(null);\n  const [draft, setDraft] = React.useState<Draft>(EMPTY_DRAFT);\n  const [viewsOpen, setViewsOpen] = React.useState(false);\n\n  const [saving, setSaving] = React.useState<null | { name: string; status: \"idle\" | \"pending\" | \"error\"; error?: string }>(\n    null\n  );\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const addRef = React.useRef<HTMLButtonElement>(null);\n  const popRef = React.useRef<HTMLDivElement>(null);\n  const anchorEl = React.useRef<HTMLElement | null>(null);\n  const restoreEl = React.useRef<HTMLElement | null>(null);\n  const saveInput = React.useRef<HTMLInputElement>(null);\n\n  /* ----- intro (once in view; falls back on a timer so it never stays hidden) */\n  const inView = useInView(rootRef, { once: true, amount: 0.2 });\n  const [forced, setForced] = React.useState(false);\n  const [introKey, setIntroKey] = React.useState(0);\n  React.useEffect(() => {\n    const t = window.setTimeout(() => setForced(true), 1200);\n    return () => window.clearTimeout(t);\n  }, []);\n  const play = reduced || inView || forced;\n  const [introDone, setIntroDone] = React.useState(false);\n  React.useEffect(() => {\n    if (!play || introDone) return;\n    const t = window.setTimeout(() => setIntroDone(true), 900);\n    return () => window.clearTimeout(t);\n  }, [play, introDone, introKey]);\n\n  /* ----- commits */\n  const commit = React.useCallback(\n    (next: SiftFilter[], msg?: string, keepView = true) => {\n      if (value === undefined) setInnerFilters(next);\n      onChange?.(next);\n      if (msg) setAnnounce(msg);\n      if (!keepView) setActiveViewId(null);\n    },\n    [value, onChange]\n  );\n\n  const setConj = (c: SiftConjunction) => {\n    if (conjProp === undefined) setInnerConj(c);\n    onConjunctionChange?.(c);\n    setAnnounce(c === \"and\" ? \"Matching all filters\" : \"Matching any filter\");\n  };\n\n  const fieldOf = (key: string | null) => fields.find((f) => f.key === key);\n\n  /* ----- popover */\n  const place = React.useCallback(() => {\n    const root = rootRef.current;\n    const a = anchorEl.current;\n    if (!root || !a) return;\n    const r = root.getBoundingClientRect();\n    const ar = a.getBoundingClientRect();\n    const width = Math.min(POP_W, r.width - 12);\n    const left = Math.max(6, Math.min(ar.left - r.left, r.width - width - 6));\n    setPopPos({ left, top: ar.bottom - r.top + 6, width });\n  }, []);\n\n  const openAt = (anchor: string, el: HTMLElement | null, step: Step, d: Draft) => {\n    setViewsOpen(false);\n    setSaving(null);\n    anchorEl.current = el;\n    restoreEl.current = (document.activeElement as HTMLElement) ?? el;\n    setDraft(d);\n    setPop({ anchor, step, dir: 1 });\n    place();\n  };\n\n  const openAdd = (fieldKey?: string) => {\n    const f = fieldKey ? fieldOf(fieldKey) : undefined;\n    openAt(\"add\", addRef.current, f ? \"operator\" : \"field\", { ...EMPTY_DRAFT, field: f?.key ?? null });\n  };\n\n  const openEdit = (filter: SiftFilter, step: Step, el: HTMLElement | null) => {\n    if (pop?.anchor === filter.id && pop.step === step) return closePop(true);\n    openAt(filter.id, el, step, draftFrom(filter));\n  };\n\n  const closePop = (restore: boolean) => {\n    setPop(null);\n    if (restore) {\n      const el = restoreEl.current;\n      requestAnimationFrame(() => (el?.isConnected ? el : addRef.current)?.focus({ preventScroll: true }));\n    }\n  };\n\n  const go = (step: Step) => setPop((p) => (p ? { ...p, step, dir: STEP_INDEX[step] >= STEP_INDEX[p.step] ? 1 : -1 } : p));\n\n  const apply = (d: Draft = draft) => {\n    const field = fieldOf(d.field);\n    if (!field) return;\n    const id = d.editingId ?? freshId(\"f\", filters.map((x) => x.id));\n    const f = buildFilter(d, field, id);\n    if (!f) return;\n    if (d.editingId) {\n      commit(\n        filters.map((x) => (x.id === d.editingId ? f : x)),\n        `Filter updated: ${describe(field, f)}`\n      );\n    } else {\n      commit([...filters, f], `Filter added: ${describe(field, f)}`);\n      restoreEl.current = addRef.current;\n    }\n    closePop(true);\n  };\n\n  const pickField = (key: string) => {\n    const nf = fieldOf(key);\n    if (!nf) return;\n    const prev = fieldOf(draft.field);\n    const keep = prev && prev.type === nf.type && prev.key === nf.key;\n    const sameType = prev && prev.type === nf.type;\n    setDraft((d) => ({\n      ...(keep ? d : sameType && nf.type !== \"select\" ? d : { ...EMPTY_DRAFT, editingId: d.editingId }),\n      field: key,\n    }));\n    go(\"operator\");\n  };\n\n  const pickOperator = (op: SiftOperator) => {\n    const field = fieldOf(draft.field);\n    if (!field) return;\n    let d: Draft = { ...draft, operator: op };\n    if (field.type === \"date\" && op !== \"is\") d = { ...d, preset: null };\n    if (field.type === \"date\" && op !== \"between\") d = { ...d, dateB: null };\n    if (field.type === \"boolean\") return apply(d);\n    setDraft(d);\n    // Editing in place: an operator swap that keeps a valid value applies at once.\n    if (draft.editingId && buildFilter(d, field, draft.editingId) && pop?.step === \"operator\" && draft.operator) {\n      const prevBetween = draft.operator === \"between\";\n      if (prevBetween === (op === \"between\")) return apply(d);\n    }\n    go(\"value\");\n  };\n\n  React.useEffect(() => {\n    if (!pop) return;\n    const root = rootRef.current;\n    const ro = new ResizeObserver(() => place());\n    if (root) ro.observe(root);\n    const onDown = (e: PointerEvent) => {\n      const t = e.target as Node;\n      if (popRef.current?.contains(t) || anchorEl.current?.contains(t)) return;\n      setPop(null);\n    };\n    document.addEventListener(\"pointerdown\", onDown);\n    return () => {\n      ro.disconnect();\n      document.removeEventListener(\"pointerdown\", onDown);\n    };\n  }, [pop, place]);\n\n  /* ----- chip ops */\n  const removeChip = (id: string, focusAfter = false) => {\n    const i = filters.findIndex((x) => x.id === id);\n    if (i < 0) return;\n    const f = filters[i];\n    const field = fieldOf(f.field);\n    const next = filters.filter((x) => x.id !== id);\n    commit(next, field ? `Removed ${describe(field, f)}` : \"Filter removed\");\n    if (pop?.anchor === id) setPop(null);\n    if (focusAfter) {\n      const target = next[Math.max(0, i - 1)]?.id;\n      requestAnimationFrame(() => {\n        const el = target\n          ? rootRef.current?.querySelector<HTMLElement>(`[data-chip=\"${target}\"] [data-part=\"field\"]`)\n          : addRef.current;\n        el?.focus({ preventScroll: true });\n      });\n    }\n  };\n\n  const clearAll = () => {\n    if (!filters.length) return;\n    commit([], \"All filters cleared\");\n    setPop(null);\n    requestAnimationFrame(() => addRef.current?.focus({ preventScroll: true }));\n  };\n\n  const pickView = (v: SiftView) => {\n    setActiveViewId(v.id);\n    setEpoch((e) => e + 1);\n    commit(v.filters, `View: ${v.label}, ${v.filters.length} filter${v.filters.length === 1 ? \"\" : \"s\"}`);\n    const c = v.conjunction ?? \"and\";\n    if (c !== conj) {\n      if (conjProp === undefined) setInnerConj(c);\n      onConjunctionChange?.(c);\n    }\n    setPop(null);\n    onViewChange?.(v);\n  };\n\n  const startSave = () => {\n    setPop(null);\n    setViewsOpen(false);\n    setSaving({ name: \"\", status: \"idle\" });\n    requestAnimationFrame(() => saveInput.current?.focus({ preventScroll: true }));\n  };\n\n  const submitSave = async () => {\n    if (!saving || saving.status === \"pending\") return;\n    const name = saving.name.trim();\n    if (!name) {\n      setSaving({ ...saving, status: \"error\", error: \"Name the view\" });\n      return;\n    }\n    const view: SiftView = {\n      id: freshId(\"view\", views.map((v) => v.id)),\n      label: name,\n      filters: filters.map((f) => ({ ...f })),\n      conjunction: conj,\n    };\n    try {\n      const r = onSaveView?.(view);\n      if (r && typeof (r as Promise<unknown>).then === \"function\") {\n        setSaving({ name, status: \"pending\" });\n        await r;\n      }\n      setSaved((s) => [...s, view]);\n      setActiveViewId(view.id);\n      setSaving(null);\n      setAnnounce(`View saved: ${name}`);\n    } catch (err) {\n      setSaving({ name, status: \"error\", error: err instanceof Error ? err.message : \"Couldn't save view\" });\n      requestAnimationFrame(() => saveInput.current?.focus({ preventScroll: true }));\n    }\n  };\n\n  /* ----- handle */\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      open: (k?: string) => openAdd(k),\n      close: () => {\n        setPop(null);\n        setViewsOpen(false);\n      },\n      clear: () => commit([], \"All filters cleared\"),\n      replay: () => {\n        setIntroDone(false);\n        setIntroKey((k) => k + 1);\n      },\n    })\n  );\n\n  /* ----- keyboard */\n  const onRootKey = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(e);\n    if (e.defaultPrevented) return;\n    const t = e.target as HTMLElement;\n    const typing = t.tagName === \"INPUT\" || t.tagName === \"TEXTAREA\" || t.isContentEditable;\n    if (e.key === \"Escape\" && pop) {\n      e.preventDefault();\n      closePop(true);\n      return;\n    }\n    if (pop && e.key === \"Tab\" && popRef.current?.contains(t)) {\n      // Trap focus within the popover.\n      const items = [\n        ...popRef.current.querySelectorAll<HTMLElement>(\n          'button:not([disabled]), input, [tabindex=\"0\"]'\n        ),\n      ].filter((el) => el.offsetParent !== null);\n      if (items.length) {\n        const i = items.indexOf(t);\n        const n = e.shiftKey ? (i <= 0 ? items.length - 1 : i - 1) : i === items.length - 1 ? 0 : i + 1;\n        e.preventDefault();\n        items[n].focus({ preventScroll: true });\n      }\n      return;\n    }\n    if (!typing && !pop && e.key.toLowerCase() === \"f\" && !e.metaKey && !e.ctrlKey && !e.altKey) {\n      e.preventDefault();\n      addRef.current?.focus({ preventScroll: true });\n    }\n  };\n\n  const onChipKey = (e: React.KeyboardEvent, i: number, id: string) => {\n    if (e.key === \"Backspace\" || e.key === \"Delete\") {\n      e.preventDefault();\n      e.stopPropagation();\n      removeChip(id, true);\n    } else if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault();\n      const n = i + (e.key === \"ArrowRight\" ? 1 : -1);\n      if (n < 0) return;\n      const target = filters[n]?.id;\n      const el = target\n        ? rootRef.current?.querySelector<HTMLElement>(`[data-chip=\"${target}\"] [data-part=\"field\"]`)\n        : addRef.current;\n      el?.focus({ preventScroll: true });\n    }\n  };\n\n  /* ----- derived render bits */\n  const accentStyle = {\n    \"--sift-accent\": accentColor,\n    \"--sift-ink\": inkFor(accentColor),\n    ...style,\n  } as React.CSSProperties;\n  const popField = fieldOf(draft.field);\n  const popOp = draft.operator && popField ? opLabel(popField.type, draft.operator) : null;\n  const canApply = !!(popField && buildFilter(draft, popField, \"x\"));\n  const showViews = views.length > 0;\n  const prevCount = usePrev(count);\n  const layoutOn = !reduced;\n\n  const chipTransition = (i: number): Transition =>\n    reduced ? REDUCED_T : { ...SPRING, delay: introDone ? 0 : 0.14 + i * 0.05 };\n\n  /* ----- step body */\n  let body: React.ReactNode = null;\n  if (pop) {\n    if (pop.step === \"field\") body = <FieldStep uid={uid} fields={fields} selected={draft.field} onPick={pickField} />;\n    else if (pop.step === \"operator\" && popField)\n      body = <OperatorStep uid={uid} type={popField.type} selected={draft.operator} onPick={pickOperator} />;\n    else if (pop.step === \"value\" && popField) {\n      const set = (p: Partial<Draft>) => setDraft((d) => ({ ...d, ...p }));\n      const submit = () => apply();\n      body =\n        popField.type === \"text\" ? (\n          <TextEditor draft={draft} set={set} submit={submit} />\n        ) : popField.type === \"select\" ? (\n          <SelectEditor uid={uid} field={popField} draft={draft} set={set} submit={submit} />\n        ) : popField.type === \"number\" ? (\n          <NumberEditor draft={draft} set={set} submit={submit} />\n        ) : popField.type === \"date\" ? (\n          <DateEditor draft={draft} set={set} today={todayKey} submit={submit} />\n        ) : null;\n    }\n  }\n\n  return (\n    <div\n      ref={rootRef}\n      data-crucible=\"sift\"\n      className={cn(\"@container relative w-full text-[13px] text-white\", className)}\n      style={accentStyle}\n      onKeyDown={onRootKey}\n      {...rest}\n    >\n      <motion.div\n        key={introKey}\n        initial={{ opacity: 0, y: 8 }}\n        animate={play ? { opacity: 1, y: 0 } : undefined}\n        transition={reduced ? { duration: 0.15, ease: \"easeOut\" } : { duration: 0.45, ease: EASE }}\n        className=\"rounded-2xl border border-white/[0.08] bg-[#111113]/90 shadow-[inset_0_1px_0_rgba(255,255,255,0.04),0_24px_60px_-28px_rgba(0,0,0,0.8)] backdrop-blur-sm\"\n      >\n        {/* header: views · count · save */}\n        <div className=\"flex min-h-12 flex-wrap items-center gap-x-2 gap-y-1 border-b border-white/[0.06] px-2 py-1.5\">\n          {showViews ? (\n            <ViewsMenu\n              uid={uid}\n              views={views}\n              activeId={activeViewId}\n              edited={edited}\n              open={viewsOpen}\n              setOpen={(o) => {\n                if (o) setPop(null);\n                setViewsOpen(o);\n              }}\n              onPick={pickView}\n            />\n          ) : (\n            <span className=\"flex h-8 items-center gap-2 px-2 text-[13px] font-medium text-white/85\">\n              <span className=\"text-white/45\">{Icon.funnel}</span>Filters\n            </span>\n          )}\n\n          <div className=\"ml-auto flex min-w-0 items-center gap-2.5\">\n            {count !== undefined && (\n              <span className=\"flex items-baseline gap-1 whitespace-nowrap px-1 text-[12.5px] text-white/45\" aria-live=\"polite\">\n                {reduced ? (\n                  <span className=\"font-medium tabular-nums text-white\">{count}</span>\n                ) : (\n                  <Tally\n                    key={count}\n                    value={count}\n                    start={prevCount ?? count}\n                    duration={0.55}\n                    stagger={0.03}\n                    glow={false}\n                    glint={false}\n                    className=\"font-medium text-white\"\n                  />\n                )}\n                {total !== undefined && <span className=\"tabular-nums\">of {total}</span>}\n                <span>{count === 1 ? noun.one : noun.other}</span>\n              </span>\n            )}\n            {onSaveView && (\n              <AnimatePresence mode=\"popLayout\" initial={false}>\n                {saving ? (\n                  <motion.form\n                    key=\"save-form\"\n                    initial={reduced ? { opacity: 0 } : { opacity: 0, width: 96 }}\n                    animate={{ opacity: 1, width: \"auto\" }}\n                    exit={{ opacity: 0 }}\n                    transition={reduced ? FADE : { duration: 0.22, ease: EASE }}\n                    onSubmit={(e) => {\n                      e.preventDefault();\n                      void submitSave();\n                    }}\n                    className=\"flex items-center gap-1\"\n                  >\n                    <motion.input\n                      ref={saveInput}\n                      value={saving.name}\n                      disabled={saving.status === \"pending\"}\n                      onChange={(e) => setSaving({ name: e.target.value, status: \"idle\" })}\n                      onKeyDown={(e) => {\n                        if (e.key === \"Escape\") {\n                          e.preventDefault();\n                          e.stopPropagation();\n                          setSaving(null);\n                        }\n                      }}\n                      onBlur={(e) => {\n                        if (!saving.name.trim() && !e.currentTarget.form?.contains(e.relatedTarget as Node)) setSaving(null);\n                      }}\n                      animate={saving.status === \"error\" && !reduced ? { x: [0, -4, 4, -2, 0] } : { x: 0 }}\n                      transition={{ duration: 0.3 }}\n                      aria-label=\"View name\"\n                      aria-invalid={saving.status === \"error\" || undefined}\n                      title={saving.error}\n                      placeholder={saving.error ?? \"View name\"}\n                      maxLength={40}\n                      className={cn(\n                        \"h-8 w-[min(11rem,40cqw)] rounded-lg border bg-white/[0.04] px-2.5 text-[13px] text-white placeholder:text-white/35 outline-none transition-colors focus:border-[color-mix(in_srgb,var(--sift-accent)_50%,transparent)] disabled:opacity-60\",\n                        saving.status === \"error\" ? \"border-red-400/50 placeholder:text-red-300/70\" : \"border-white/10\"\n                      )}\n                    />\n                    <button\n                      type=\"submit\"\n                      aria-label=\"Save view\"\n                      disabled={saving.status === \"pending\"}\n                      className={cn(\n                        \"grid size-8 shrink-0 place-items-center rounded-lg transition-[filter] hover:brightness-110 disabled:cursor-progress\",\n                        FOCUS\n                      )}\n                      style={{ background: \"var(--sift-accent)\", color: \"var(--sift-ink)\" }}\n                    >\n                      {saving.status === \"pending\" ? (\n                        <motion.span\n                          aria-hidden\n                          className=\"block size-3.5 rounded-full border-2 border-current border-t-transparent\"\n                          animate={reduced ? undefined : { rotate: 360 }}\n                          transition={{ duration: 0.8, repeat: Infinity, ease: \"linear\" }}\n                        />\n                      ) : (\n                        Icon.check\n                      )}\n                    </button>\n                  </motion.form>\n                ) : (\n                  <motion.button\n                    key=\"save-btn\"\n                    type=\"button\"\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: !filters.length || !edited ? 0.35 : 1 }}\n                    exit={{ opacity: 0 }}\n                    transition={FADE}\n                    onClick={startSave}\n                    disabled={!filters.length || !edited}\n                    className={cn(\n                      \"h-8 whitespace-nowrap rounded-lg border border-white/10 px-2.5 text-[12.5px] font-medium text-white/75 transition-colors hover:border-white/15 hover:bg-white/[0.04] hover:text-white disabled:pointer-events-none\",\n                      FOCUS\n                    )}\n                  >\n                    Save view\n                  </motion.button>\n                )}\n              </AnimatePresence>\n            )}\n          </div>\n        </div>\n\n        {/* chips row — views crossfade by stacking epochs in one grid cell */}\n        <div className=\"grid p-2\">\n          <AnimatePresence initial={false}>\n            <motion.div\n              key={epoch}\n              className=\"relative col-start-1 row-start-1\"\n              initial={{ opacity: 0, filter: reduced ? \"blur(0px)\" : \"blur(3px)\" }}\n              animate={{ opacity: 1, filter: \"blur(0px)\" }}\n              exit={{ opacity: 0, filter: reduced ? \"blur(0px)\" : \"blur(3px)\" }}\n              transition={{ duration: reduced ? 0.15 : 0.24, ease: \"easeOut\" }}\n            >\n              <LayoutGroup id={`${uid}-${epoch}`}>\n                <div role=\"group\" aria-label=\"Applied filters\" className=\"relative flex flex-wrap items-center gap-1.5\">\n                  <AnimatePresence mode=\"popLayout\" initial={true}>\n                    {filters.map((f, i) => {\n                      const field = fieldOf(f.field);\n                      if (!field) return null;\n                      const val = summarize(field, f);\n                      const on = pop?.anchor === f.id;\n                      const opts = field.type === \"select\" ? optionsOf(field) : [];\n                      const firstColor =\n                        field.type === \"select\" && Array.isArray(f.value) && f.value.length === 1\n                          ? (opts.find((o) => o.value === (f.value as string[])[0])?.color ?? \"\")\n                          : \"\";\n                      return (\n                        <motion.div\n                          key={f.id}\n                          layout={layoutOn ? \"position\" : false}\n                          className=\"flex items-center gap-1.5\"\n                          initial={{ opacity: 0, scale: 0.86, y: 3 }}\n                          animate={play ? { opacity: 1, scale: 1, y: 0 } : undefined}\n                          exit={reduced ? { opacity: 0 } : { opacity: 0, scale: 0.86, filter: \"blur(2px)\" }}\n                          transition={chipTransition(i)}\n                        >\n                          {i > 0 && (\n                            <button\n                              type=\"button\"\n                              onClick={() => setConj(conj === \"and\" ? \"or\" : \"and\")}\n                              aria-label={`Combine filters with ${conj}. Switch to ${conj === \"and\" ? \"or\" : \"and\"}`}\n                              className={cn(\n                                \"h-6 min-w-8 rounded-md px-1.5 text-[11.5px] font-medium uppercase tracking-[0.06em] text-white/40 transition-colors hover:bg-white/[0.05] hover:text-white/80\",\n                                FOCUS\n                              )}\n                            >\n                              <AnimatePresence mode=\"popLayout\" initial={false}>\n                                <motion.span\n                                  key={conj}\n                                  className=\"inline-block\"\n                                  initial={reduced ? { opacity: 0 } : { opacity: 0, y: 6 }}\n                                  animate={{ opacity: 1, y: 0 }}\n                                  exit={reduced ? { opacity: 0 } : { opacity: 0, y: -6 }}\n                                  transition={{ duration: 0.16, ease: EASE }}\n                                >\n                                  {conj}\n                                </motion.span>\n                              </AnimatePresence>\n                            </button>\n                          )}\n                          <div\n                            data-chip={f.id}\n                            role=\"group\"\n                            aria-label={`Filter: ${describe(field, f)}. Backspace removes, arrow keys move between filters`}\n                            onKeyDown={(e) => onChipKey(e, i, f.id)}\n                            className={cn(\n                              \"flex h-8 max-w-full items-stretch overflow-hidden rounded-[9px] border bg-white/[0.035] transition-[border-color,box-shadow,background-color] duration-200\",\n                              on\n                                ? \"border-[color-mix(in_srgb,var(--sift-accent)_55%,transparent)] bg-[color-mix(in_srgb,var(--sift-accent)_7%,transparent)] shadow-[0_0_0_3px_color-mix(in_srgb,var(--sift-accent)_12%,transparent)]\"\n                                : \"border-white/[0.09] hover:border-white/[0.14]\"\n                            )}\n                          >\n                            <ChipPart\n                              part=\"field\"\n                              label={`Change property (${field.label})`}\n                              onClick={(e) => openEdit(f, \"field\", e.currentTarget.closest(\"[data-chip]\"))}\n                              className=\"gap-1.5 pl-2.5 text-white/60\"\n                            >\n                              <span className=\"text-white/40\">{field.icon ?? TYPE_ICON[field.type]}</span>\n                              <span className=\"hidden whitespace-nowrap @[18rem]:inline\">{field.label}</span>\n                            </ChipPart>\n                            <ChipPart\n                              part=\"op\"\n                              label={`Change operator (${opLabel(field.type, f.operator)})`}\n                              onClick={(e) => openEdit(f, \"operator\", e.currentTarget.closest(\"[data-chip]\"))}\n                              className={cn(\"text-white/40\", opLabel(field.type, f.operator).length === 1 && \"font-mono\")}\n                            >\n                              <span className=\"whitespace-nowrap\">{opLabel(field.type, f.operator)}</span>\n                            </ChipPart>\n                            {val && (\n                              <ChipPart\n                                part=\"value\"\n                                label={`Change value (${val})`}\n                                onClick={(e) => openEdit(f, \"value\", e.currentTarget.closest(\"[data-chip]\"))}\n                                className=\"min-w-0 gap-1.5 font-medium text-[var(--sift-accent)]\"\n                              >\n                                <Dot color={firstColor} />\n                                <span className=\"truncate tabular-nums\">{val}</span>\n                              </ChipPart>\n                            )}\n                            <button\n                              type=\"button\"\n                              aria-label={`Remove filter ${describe(field, f)}`}\n                              onClick={() => removeChip(f.id, true)}\n                              className=\"grid w-7 shrink-0 place-items-center border-l border-white/[0.06] text-white/35 transition-colors hover:bg-white/[0.06] hover:text-white focus-visible:bg-white/[0.08] focus-visible:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--sift-accent)]\"\n                            >\n                              {Icon.x}\n                            </button>\n                          </div>\n                        </motion.div>\n                      );\n                    })}\n                    {/* Add + Clear all wrap together, so \"Clear all\" never lands alone on a row. */}\n                    <motion.div\n                      key=\"tail\"\n                      layout={layoutOn ? \"position\" : false}\n                      className={cn(\n                        \"flex flex-1 items-center gap-1.5\",\n                        // nowrap → the pair's min-content is both buttons, so the row\n                        // breaks before them rather than between them.\n                        filters.length ? \"flex-nowrap\" : \"min-w-0 flex-wrap\"\n                      )}\n                    >\n                      <motion.button\n                        ref={addRef}\n                        type=\"button\"\n                        aria-haspopup=\"dialog\"\n                        aria-expanded={pop?.anchor === \"add\"}\n                        aria-keyshortcuts=\"F\"\n                        onClick={() => (pop?.anchor === \"add\" ? closePop(true) : openAdd())}\n                        initial={{ opacity: 0, y: 3 }}\n                        animate={play ? { opacity: 1, y: 0 } : undefined}\n                        transition={reduced ? REDUCED_T : { ...SPRING, delay: introDone ? 0 : 0.14 + filters.length * 0.05 }}\n                        className={cn(\n                          \"flex h-8 items-center gap-1.5 rounded-[9px] border border-dashed px-2.5 text-[12.5px] font-medium transition-colors\",\n                          pop?.anchor === \"add\"\n                            ? \"border-[color-mix(in_srgb,var(--sift-accent)_55%,transparent)] bg-white/[0.05] text-white\"\n                            : \"border-white/15 text-white/60 hover:border-white/25 hover:bg-white/[0.03] hover:text-white\",\n                          FOCUS\n                        )}\n                      >\n                        {Icon.plus}\n                        Filter\n                        <kbd className=\"ml-0.5 hidden rounded border border-white/10 px-1 font-sans text-[10px] leading-[14px] text-white/35 @[30rem]:inline\">\n                          F\n                        </kbd>\n                      </motion.button>\n                      <AnimatePresence initial={false} mode=\"popLayout\">\n                        {!filters.length && (\n                          <motion.span\n                            key=\"empty\"\n                            initial={{ opacity: 0 }}\n                            animate={{ opacity: 1 }}\n                            exit={{ opacity: 0 }}\n                            transition={FADE}\n                            className=\"px-1 text-[12.5px] text-white/35\"\n                          >\n                            No filters — showing everything\n                          </motion.span>\n                        )}\n                        {filters.length > 0 && (\n                          <motion.button\n                            key=\"clear\"\n                            type=\"button\"\n                            onClick={clearAll}\n                            initial={{ opacity: 0 }}\n                            animate={{ opacity: 1 }}\n                            exit={{ opacity: 0 }}\n                            transition={FADE}\n                            className={cn(\n                              \"ml-auto h-8 whitespace-nowrap rounded-lg px-2 text-[12.5px] text-white/45 underline-offset-4 transition-colors hover:text-white hover:underline\",\n                              FOCUS\n                            )}\n                          >\n                            Clear all\n                          </motion.button>\n                        )}\n                      </AnimatePresence>\n                    </motion.div>\n                  </AnimatePresence>\n                </div>\n              </LayoutGroup>\n            </motion.div>\n          </AnimatePresence>\n        </div>\n      </motion.div>\n\n      {/* popover */}\n      <AnimatePresence>\n        {pop && popPos && (\n          <motion.div\n            ref={popRef}\n            role=\"dialog\"\n            aria-label={\n              pop.step === \"field\"\n                ? \"Choose a property\"\n                : pop.step === \"operator\"\n                  ? `${popField?.label ?? \"\"}: choose an operator`\n                  : `${popField?.label ?? \"\"} ${popOp ?? \"\"}: choose a value`\n            }\n            initial={reduced ? { opacity: 0 } : { opacity: 0, y: -6, scale: 0.97 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={reduced ? { opacity: 0 } : { opacity: 0, y: -4, scale: 0.98 }}\n            transition={reduced ? FADE : { duration: 0.18, ease: EASE }}\n            style={{ left: popPos.left, top: popPos.top, width: popPos.width, transformOrigin: \"top left\" }}\n            className=\"absolute z-50 overflow-hidden rounded-xl border border-white/10 bg-[#141416] shadow-[0_28px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.45)]\"\n          >\n            {/* step header */}\n            <div className=\"flex h-10 items-center gap-1.5 border-b border-white/[0.06] px-1.5\">\n              {pop.step !== \"field\" ? (\n                <button\n                  type=\"button\"\n                  aria-label=\"Back\"\n                  onClick={() => go(pop.step === \"value\" ? \"operator\" : \"field\")}\n                  className={cn(\"grid size-7 place-items-center rounded-md text-white/50 hover:bg-white/[0.06] hover:text-white\", FOCUS)}\n                >\n                  {Icon.back}\n                </button>\n              ) : (\n                <span className=\"grid size-7 place-items-center text-white/40\">{Icon.funnel}</span>\n              )}\n              <div className=\"flex min-w-0 flex-1 items-center gap-1.5 text-[12.5px]\">\n                {pop.step === \"field\" ? (\n                  <span className=\"font-medium text-white/80\">{draft.editingId ? \"Change property\" : \"Add filter\"}</span>\n                ) : (\n                  <>\n                    <span className=\"text-white/40\">{popField?.icon ?? (popField && TYPE_ICON[popField.type])}</span>\n                    <span className=\"truncate font-medium text-white/85\">{popField?.label}</span>\n                    {pop.step === \"value\" && popOp && (\n                      <span className={cn(\"shrink-0 text-white/40\", popOp?.length === 1 && \"font-mono\")}>{popOp}</span>\n                    )}\n                  </>\n                )}\n              </div>\n              <StepDots step={pop.step} />\n            </div>\n\n            <PopBody stepKey={pop.step} dir={pop.dir} reduced={reduced}>\n              {body}\n            </PopBody>\n\n            {pop.step === \"value\" && popField && popField.type !== \"boolean\" && (\n              <div className=\"flex items-center gap-2 border-t border-white/[0.06] px-2 py-2\">\n                <span className=\"min-w-0 flex-1 truncate pl-1 text-[12px] text-white/40\">\n                  {popField.type === \"select\"\n                    ? `${draft.sel.length} selected`\n                    : popField.type === \"date\"\n                      ? draft.preset\n                        ? PRESET_LABEL[draft.preset]\n                        : draft.dateA\n                          ? draft.operator === \"between\"\n                            ? `${fmtDay(draft.dateA)} – ${draft.dateB ? fmtDay(draft.dateB) : \"…\"}`\n                            : fmtDay(draft.dateA)\n                          : \"Pick a date\"\n                      : \"Enter to apply\"}\n                </span>\n                <button\n                  type=\"button\"\n                  onClick={() => apply()}\n                  disabled={!canApply}\n                  className={cn(\n                    \"h-8 rounded-lg px-3.5 text-[12.5px] font-semibold transition-[filter,opacity,transform] duration-150 hover:brightness-110 active:scale-[0.97] disabled:pointer-events-none disabled:opacity-35\",\n                    \"outline-none focus-visible:ring-2 focus-visible:ring-white/70 focus-visible:ring-offset-2 focus-visible:ring-offset-[#141416]\"\n                  )}\n                  style={{ background: \"var(--sift-accent)\", color: \"var(--sift-ink)\" }}\n                >\n                  {draft.editingId ? \"Update\" : \"Apply\"}\n                </button>\n              </div>\n            )}\n          </motion.div>\n        )}\n      </AnimatePresence>\n\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </div>\n  );\n}\n\n/* ================================================================ internals */\n\nfunction usePrev<T>(value: T): T | undefined {\n  const [state, setState] = React.useState<{ current: T; previous: T | undefined }>({ current: value, previous: undefined });\n  if (!Object.is(state.current, value)) setState({ current: value, previous: state.current });\n  return state.previous;\n}\n\nfunction ChipPart({\n  part,\n  label,\n  onClick,\n  className,\n  children,\n}: {\n  part: string;\n  label: string;\n  onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;\n  className?: string;\n  children: React.ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      data-part={part}\n      aria-label={label}\n      onClick={onClick}\n      className={cn(\n        \"flex min-w-0 items-center px-2 text-[12.5px] transition-colors hover:bg-white/[0.05] focus-visible:bg-white/[0.07] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--sift-accent)]\",\n        part !== \"field\" && \"border-l border-white/[0.06]\",\n        className\n      )}\n    >\n      {children}\n    </button>\n  );\n}\n\nfunction StepDots({ step }: { step: Step }) {\n  const n = STEP_INDEX[step];\n  return (\n    <span aria-hidden className=\"flex items-center gap-1 pr-1.5\">\n      {[0, 1, 2].map((i) => (\n        <span\n          key={i}\n          className=\"h-1 rounded-full transition-all duration-300\"\n          style={{\n            width: i === n ? 12 : 4,\n            background: i <= n ? \"var(--sift-accent)\" : \"rgba(255,255,255,0.15)\",\n            opacity: i === n ? 1 : i < n ? 0.5 : 1,\n          }}\n        />\n      ))}\n    </span>\n  );\n}\n\n/** Slides step content horizontally and springs the popover height to fit. */\nfunction PopBody({\n  stepKey,\n  dir,\n  reduced,\n  children,\n}: {\n  stepKey: string;\n  dir: 1 | -1;\n  reduced: boolean;\n  children: React.ReactNode;\n}) {\n  const inner = React.useRef<HTMLDivElement>(null);\n  const [h, setH] = React.useState<number | \"auto\">(\"auto\");\n  React.useEffect(() => {\n    const el = inner.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => setH(el.offsetHeight));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  return (\n    <motion.div\n      animate={{ height: h }}\n      initial={false}\n      transition={reduced ? { duration: 0 } : SLIDE}\n      className=\"relative overflow-hidden\"\n    >\n      <div ref={inner} className=\"relative\">\n        <AnimatePresence mode=\"popLayout\" initial={false} custom={dir}>\n          <motion.div\n            key={stepKey}\n            custom={dir}\n            variants={{\n              enter: (d: number) => (reduced ? { opacity: 0 } : { opacity: 0, x: d * 28 }),\n              center: { opacity: 1, x: 0 },\n              exit: (d: number) => (reduced ? { opacity: 0 } : { opacity: 0, x: d * -28 }),\n            }}\n            initial=\"enter\"\n            animate=\"center\"\n            exit=\"exit\"\n            transition={reduced ? FADE : { ...SLIDE, opacity: { duration: 0.16 } }}\n            className=\"w-full\"\n          >\n            {children}\n          </motion.div>\n        </AnimatePresence>\n      </div>\n    </motion.div>\n  );\n}\n"
    }
  ]
}