{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "analytics-dashboard",
  "title": "Revenue Recovery Analytics Block",
  "description": "Complete FRAME/12 e-commerce revenue recovery analytics block extracted from the flagship storyboard and backed by an authoritative mulberry32(1207) fixture model where KPI overview, time-series analysis, period comparison, checkout segment breakdown, ranked interventions, and filterable daily ledgers reconcile 100%.",
  "dependencies": [
    "@radix-ui/react-select"
  ],
  "registryDependencies": [
    "https://frame12.dev/r/frame12-styles.json",
    "https://frame12.dev/r/frame12.json"
  ],
  "files": [
    {
      "path": "blocks/analytics-dashboard.tsx",
      "content": "'use client';\n\nimport * as React from 'react';\nimport { useChanged, type MotionMode } from '@/hooks/use-on-twos';\nimport {\n  Sheet,\n  Scene,\n  Panel,\n  PanelPair,\n  SegmentedControl,\n  Button,\n  Input,\n  Select,\n  SelectTrigger,\n  SelectValue,\n  SelectContent,\n  SelectItem,\n  Badge,\n  Tag,\n  type TagStatus,\n  Alert,\n  Notice,\n  ToastProvider,\n  useToast,\n  useOptionalToast,\n  Skeleton,\n  SkeletonText,\n  EmptyState,\n  Breadcrumb,\n  Pagination,\n  Metric,\n  ToneAreaChart,\n  ToneBarList,\n  ToneSpark,\n  Dialog,\n  DialogContent,\n  DialogHeader,\n  DialogTitle,\n  DialogDescription,\n  DialogFooter,\n  DialogClose,\n  Table,\n  TableHeader,\n  TableBody,\n  TableFooter,\n  TableRow,\n  TableHead,\n  TableCell,\n  TableCaption,\n} from '@/components/frame12';\n\n// ============================================================================\n// AUTHORITATIVE DETERMINISTIC FIXTURE MODEL (Fernwood Supply Co. · mulberry32(1207))\n// Shared by the public homepage (`/`) and the installable Analytics Block.\n// ============================================================================\n\nfunction mulberry32(a: number): () => number {\n  return function () {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nexport const STORE = 'Fernwood Supply Co.';\nexport const END_LABEL = 'Oct 31, 2026';\nexport type RangeDays = 7 | 30 | 90;\nexport const RANGES: RangeDays[] = [7, 30, 90];\nexport const DEFAULT_RANGE: RangeDays = 30;\n\nexport type CheckoutSegmentId = 'returning-vip' | 'first-time-mobile' | 'high-aov-desktop';\n\nexport interface CheckoutSegmentMeta {\n  id: CheckoutSegmentId;\n  name: string;\n  shortName: string;\n  description: string;\n}\n\nexport const CHECKOUT_SEGMENTS: CheckoutSegmentMeta[] = [\n  {\n    id: 'returning-vip',\n    name: 'Returning VIP & Loyalty',\n    shortName: 'Returning VIP',\n    description: 'Repeat buyers with 2+ prior orders and saved payment credentials.',\n  },\n  {\n    id: 'first-time-mobile',\n    name: 'First-Time Mobile Checkout',\n    shortName: 'First-Time Mobile',\n    description: 'New mobile sessions re-engaged via SMS, push, or exit-intent prompts.',\n  },\n  {\n    id: 'high-aov-desktop',\n    name: 'High-AOV Desktop Carts',\n    shortName: 'High-AOV Desktop',\n    description: 'Desktop baskets over $150 completing checkout after restock or cart reminders.',\n  },\n];\n\nexport interface InterventionMeta {\n  id: string;\n  name: string;\n  channel: string;\n  triggerWindow: string;\n  base: number;\n  trend: number;\n  margin: number;\n  segmentWeights: Record<CheckoutSegmentId, number>;\n}\n\nexport const INTERVENTIONS: InterventionMeta[] = [\n  {\n    id: 'cart',\n    name: 'Abandoned-cart email',\n    channel: 'Email',\n    triggerWindow: '1h post-abandon',\n    base: 1150,\n    trend: 0.15,\n    margin: 0.38,\n    segmentWeights: {\n      'returning-vip': 0.44,\n      'first-time-mobile': 0.31,\n      'high-aov-desktop': 0.25,\n    },\n  },\n  {\n    id: 'exit',\n    name: 'Exit-intent offer',\n    channel: 'On-site Modal',\n    triggerWindow: 'Session exit',\n    base: 700,\n    trend: 0.25,\n    margin: 0.22,\n    segmentWeights: {\n      'returning-vip': 0.24,\n      'first-time-mobile': 0.52,\n      'high-aov-desktop': 0.24,\n    },\n  },\n  {\n    id: 'stock',\n    name: 'Back-in-stock alert',\n    channel: 'SMS & Push',\n    triggerWindow: 'Inventory restock',\n    base: 520,\n    trend: 0.05,\n    margin: 0.41,\n    segmentWeights: {\n      'returning-vip': 0.48,\n      'first-time-mobile': 0.28,\n      'high-aov-desktop': 0.24,\n    },\n  },\n  {\n    id: 'price',\n    name: 'Price-drop notice',\n    channel: 'Email & SMS',\n    triggerWindow: 'Catalog markdown',\n    base: 430,\n    trend: -0.1,\n    margin: 0.18,\n    segmentWeights: {\n      'returning-vip': 0.34,\n      'first-time-mobile': 0.42,\n      'high-aov-desktop': 0.24,\n    },\n  },\n  {\n    id: 'upsell',\n    name: 'Post-purchase upsell',\n    channel: 'Checkout Receipt',\n    triggerWindow: 'Immediate post-pay',\n    base: 300,\n    trend: 0.3,\n    margin: 0.46,\n    segmentWeights: {\n      'returning-vip': 0.51,\n      'first-time-mobile': 0.22,\n      'high-aov-desktop': 0.27,\n    },\n  },\n];\n\nexport interface DayDatum {\n  ms: number;\n  dayKey: string;\n  label: string;\n  long: string;\n  total: number;\n  byId: Record<string, number>;\n  profitById: Record<string, number>;\n  bySegment: Record<CheckoutSegmentId, number>;\n  profitBySegment: Record<CheckoutSegmentId, number>;\n  byIdAndSegment: Record<string, Record<CheckoutSegmentId, number>>;\n  profitByIdAndSegment: Record<string, Record<CheckoutSegmentId, number>>;\n  profit: number;\n  lift: number;\n  topInterventionId: string;\n  topSegmentId: CheckoutSegmentId;\n  evidenceNote: string;\n}\n\nexport interface InterventionRow {\n  id: string;\n  name: string;\n  channel: string;\n  triggerWindow: string;\n  margin: number;\n  value: number;\n  prevValue: number;\n  deltaPct: number;\n  profit: number;\n  share: number;\n}\n\nexport interface SegmentRow {\n  id: CheckoutSegmentId;\n  name: string;\n  shortName: string;\n  description: string;\n  revenue: number;\n  prevRevenue: number;\n  deltaPct: number;\n  profit: number;\n  share: number;\n}\n\nexport interface RangeSummary {\n  range: RangeDays;\n  days: DayDatum[];\n  prevDays: DayDatum[];\n  revenue: number;\n  prevRevenue: number;\n  revenueDelta: number;\n  profit: number;\n  prevProfit: number;\n  profitDelta: number;\n  netMarginPct: number;\n  prevNetMarginPct: number;\n  lift: number;\n  prevLift: number;\n  liftDelta: number;\n  rows: InterventionRow[];\n  segments: SegmentRow[];\n  leader: string;\n  peak: DayDatum;\n  prevPeak: DayDatum;\n}\n\nconst DAYS = 180;\nconst END = Date.UTC(2026, 9, 31);\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nfunction partitionBySegment(\n  amount: number,\n  weights: Record<CheckoutSegmentId, number>,\n): Record<CheckoutSegmentId, number> {\n  const vip = Math.round(amount * weights['returning-vip']);\n  const mobile = Math.round(amount * weights['first-time-mobile']);\n  const desktop = amount - vip - mobile;\n  return {\n    'returning-vip': vip,\n    'first-time-mobile': mobile,\n    'high-aov-desktop': desktop,\n  };\n}\n\nfunction buildDays(): DayDatum[] {\n  const rnd = mulberry32(1207);\n  const weekly = [1.16, 0.93, 0.95, 0.97, 1.02, 1.12, 1.2]; // Sun..Sat\n  const out: DayDatum[] = [];\n\n  for (let t = 0; t < DAYS; t++) {\n    const ms = END - (DAYS - 1 - t) * 864e5;\n    const d = new Date(ms);\n    const wk = weekly[d.getUTCDay()];\n    const byId: Record<string, number> = {};\n    const profitById: Record<string, number> = {};\n    const bySegment: Record<CheckoutSegmentId, number> = {\n      'returning-vip': 0,\n      'first-time-mobile': 0,\n      'high-aov-desktop': 0,\n    };\n    const profitBySegment: Record<CheckoutSegmentId, number> = {\n      'returning-vip': 0,\n      'first-time-mobile': 0,\n      'high-aov-desktop': 0,\n    };\n    const byIdAndSegment: Record<string, Record<CheckoutSegmentId, number>> = {};\n    const profitByIdAndSegment: Record<string, Record<CheckoutSegmentId, number>> = {};\n\n    let total = 0;\n    let rawProfit = 0;\n\n    for (const it of INTERVENTIONS) {\n      const trend = 1 + it.trend * (t / (DAYS - 1));\n      const noise = 1 + (rnd() - 0.5) * 0.36;\n      const boost = it.id === 'exit' && t >= DAYS - 9 ? 2.05 : 1;\n      const v = Math.round(it.base * trend * wk * noise * boost);\n      byId[it.id] = v;\n      total += v;\n      rawProfit += v * it.margin;\n    }\n\n    const totalProfit = Math.round(rawProfit);\n    // Reconcile per-intervention integer profit so sum(profitById) === totalProfit\n    let allocatedProfit = 0;\n    for (let i = 0; i < INTERVENTIONS.length; i++) {\n      const it = INTERVENTIONS[i];\n      const p =\n        i === INTERVENTIONS.length - 1\n          ? totalProfit - allocatedProfit\n          : Math.round(byId[it.id] * it.margin);\n      profitById[it.id] = p;\n      allocatedProfit += p;\n\n      const segRev = partitionBySegment(byId[it.id], it.segmentWeights);\n      const segProf = partitionBySegment(p, it.segmentWeights);\n      byIdAndSegment[it.id] = segRev;\n      profitByIdAndSegment[it.id] = segProf;\n\n      bySegment['returning-vip'] += segRev['returning-vip'];\n      bySegment['first-time-mobile'] += segRev['first-time-mobile'];\n      bySegment['high-aov-desktop'] += segRev['high-aov-desktop'];\n\n      profitBySegment['returning-vip'] += segProf['returning-vip'];\n      profitBySegment['first-time-mobile'] += segProf['first-time-mobile'];\n      profitBySegment['high-aov-desktop'] += segProf['high-aov-desktop'];\n    }\n\n    let lift = 0.48 + 0.1 * (t / (DAYS - 1)) + (rnd() - 0.5) * 0.12;\n    if (t >= DAYS - 7) lift -= 0.09;\n\n    let topInterventionId = INTERVENTIONS[0].id;\n    for (const it of INTERVENTIONS) {\n      if (byId[it.id] > byId[topInterventionId]) {\n        topInterventionId = it.id;\n      }\n    }\n\n    let topSegmentId: CheckoutSegmentId = 'returning-vip';\n    for (const seg of CHECKOUT_SEGMENTS) {\n      if (bySegment[seg.id] > bySegment[topSegmentId]) {\n        topSegmentId = seg.id;\n      }\n    }\n\n    const monthName = MONTHS[d.getUTCMonth()];\n    const dayNum = d.getUTCDate();\n    const yearNum = d.getUTCFullYear();\n    const dayKey = `${yearNum}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(dayNum).padStart(2, '0')}`;\n    const evidenceNote =\n      t >= DAYS - 9\n        ? 'Exit-intent shipping-threshold prompt active (2.05x session recovery multiplier; holdout lift softened -0.09 pp in final 7d).'\n        : d.getUTCDay() === 0 || d.getUTCDay() === 6\n          ? 'Weekend checkout cadence peak; abandoned-cart and back-in-stock dispatches led recovery volume.'\n          : 'Standard weekday dispatch cadence across 10% randomized holdout control.';\n\n    out.push({\n      ms,\n      dayKey,\n      label: `${monthName} ${dayNum}`,\n      long: `${monthName} ${dayNum}, ${yearNum}`,\n      total,\n      byId,\n      profitById,\n      bySegment,\n      profitBySegment,\n      byIdAndSegment,\n      profitByIdAndSegment,\n      profit: totalProfit,\n      lift,\n      topInterventionId,\n      topSegmentId,\n      evidenceNote,\n    });\n  }\n  return out;\n}\n\nexport const DAYS_DATA: DayDatum[] = buildDays();\n\nfunction sum<T>(a: T[], f: (x: T) => number): number {\n  let s = 0;\n  for (const x of a) s += f(x);\n  return s;\n}\n\nexport function summarize(range: RangeDays): RangeSummary {\n  const cur = DAYS_DATA.slice(DAYS - range);\n  const prev = DAYS_DATA.slice(DAYS - 2 * range, DAYS - range);\n  const revenue = sum(cur, (d) => d.total);\n  const prevRevenue = sum(prev, (d) => d.total);\n  const profit = sum(cur, (d) => d.profit);\n  const prevProfit = sum(prev, (d) => d.profit);\n  const lift = sum(cur, (d) => d.lift) / cur.length;\n  const prevLift = sum(prev, (d) => d.lift) / prev.length;\n\n  const rows: InterventionRow[] = INTERVENTIONS.map((it) => {\n    const val = sum(cur, (d) => d.byId[it.id]);\n    const prevVal = sum(prev, (d) => d.byId[it.id]);\n    const prof = sum(cur, (d) => d.profitById[it.id]);\n    return {\n      id: it.id,\n      name: it.name,\n      channel: it.channel,\n      triggerWindow: it.triggerWindow,\n      margin: it.margin,\n      value: val,\n      prevValue: prevVal,\n      deltaPct: prevVal > 0 ? (val - prevVal) / prevVal : 0,\n      profit: prof,\n      share: revenue > 0 ? val / revenue : 0,\n    };\n  }).sort((a, b) => b.value - a.value);\n\n  const segments: SegmentRow[] = CHECKOUT_SEGMENTS.map((seg) => {\n    const rev = sum(cur, (d) => d.bySegment[seg.id]);\n    const prevRev = sum(prev, (d) => d.bySegment[seg.id]);\n    const prof = sum(cur, (d) => d.profitBySegment[seg.id]);\n    return {\n      id: seg.id,\n      name: seg.name,\n      shortName: seg.shortName,\n      description: seg.description,\n      revenue: rev,\n      prevRevenue: prevRev,\n      deltaPct: prevRev > 0 ? (rev - prevRev) / prevRev : 0,\n      profit: prof,\n      share: revenue > 0 ? rev / revenue : 0,\n    };\n  });\n\n  let peak = cur[0];\n  for (const d of cur) if (d.total > peak.total) peak = d;\n\n  let prevPeak = prev[0];\n  for (const d of prev) if (d.total > prevPeak.total) prevPeak = d;\n\n  return {\n    range,\n    days: cur,\n    prevDays: prev,\n    revenue,\n    prevRevenue,\n    revenueDelta: (revenue - prevRevenue) / prevRevenue,\n    profit,\n    prevProfit,\n    profitDelta: (profit - prevProfit) / prevProfit,\n    netMarginPct: revenue > 0 ? (profit / revenue) * 100 : 0,\n    prevNetMarginPct: prevRevenue > 0 ? (prevProfit / prevRevenue) * 100 : 0,\n    lift,\n    prevLift,\n    liftDelta: Number((Number(lift.toFixed(2)) - Number(prevLift.toFixed(2))).toFixed(2)),\n    rows,\n    segments,\n    leader: rows[0].id,\n    peak,\n    prevPeak,\n  };\n}\n\nexport const SUMMARIES: Record<RangeDays, RangeSummary> = {\n  7: summarize(7),\n  30: summarize(30),\n  90: summarize(90),\n};\n\nexport const fmtMoney = (v: number): string => '$' + Math.round(v).toLocaleString('en-US');\nexport const fmtMoneyShort = (v: number): string => {\n  if (Math.abs(v) >= 1000) {\n    const k = v / 1000;\n    return '$' + (Number.isInteger(k) ? k.toFixed(0) : k.toFixed(1)) + 'k';\n  }\n  return '$' + Math.round(v);\n};\nexport const fmtPct = (v: number): string => (Math.abs(v) * 100).toFixed(1) + '%';\nexport const fmtSignedPct = (v: number): string =>\n  (v >= 0 ? '+' : '−') + (Math.abs(v) * 100).toFixed(1) + '%';\nexport const fmtPP = (v: number): string => (v >= 0 ? '+' : '−') + Math.abs(v).toFixed(2) + ' pp';\nexport const fmtPPAbs = (v: number): string => Math.abs(v).toFixed(2) + ' pp';\nexport const rangeLabel = (r: number): string => `${r} days`;\n\nexport const PROFIT_NOTE = 'Margin on recovered orders, after offer costs';\nexport const LIFT_NOTE = 'Checkout conversion vs. holdout group';\n\nexport const RANGE_OPTIONS: Array<{ value: RangeDays; label: string; unit: string }> = RANGES.map(\n  (r) => ({\n    value: r,\n    label: String(r),\n    unit: 'days',\n  }),\n);\n\n// ============================================================================\n// REUSABLE CORE STORYBOARD SCENES (C-01..C-04)\n// Shared between the homepage (`/`) and the standalone Analytics Block.\n// ============================================================================\n\nexport type AnalyticsDatasetState = 'populated' | 'loading' | 'empty' | 'error';\nexport type AnalyticsComparisonMode = 'intervention' | 'prior-period';\n\nexport interface RevenueRecoveryCoreScenesProps {\n  range: RangeDays;\n  focus: string | null;\n  onSelectFocus: (nextId: string | null) => void;\n  motion?: MotionMode;\n  idPrefix?: string;\n  chartHeight?: number;\n  datasetState?: AnalyticsDatasetState;\n  comparisonMode?: AnalyticsComparisonMode;\n  onRestorePopulated?: () => void;\n}\n\nexport function RevenueRecoveryCoreScenes({\n  range,\n  focus,\n  onSelectFocus,\n  motion = 'stepped',\n  idPrefix,\n  chartHeight = 320,\n  datasetState = 'populated',\n  comparisonMode = 'intervention',\n  onRestorePopulated,\n}: RevenueRecoveryCoreScenesProps) {\n  const autoId = React.useId().replace(/[^a-zA-Z0-9_-]/g, '');\n  const resolvedIdPrefix = idPrefix ?? `f12-recovery-scenes-${autoId}`;\n  const changed = useChanged(range);\n  const s = SUMMARIES[range];\n  const focusItem = focus ? INTERVENTIONS.find((i) => i.id === focus) ?? null : null;\n\n  const isLoading = datasetState === 'loading';\n  const isEmpty = datasetState === 'empty';\n\n  const chartData = React.useMemo(() => {\n    if (isEmpty) return [];\n    return s.days.map((d, idx) => {\n      let compareValue: number | undefined;\n      if (comparisonMode === 'prior-period' && s.prevDays[idx]) {\n        compareValue = s.prevDays[idx].total;\n      } else if (focusItem) {\n        compareValue = d.byId[focusItem.id];\n      }\n      return {\n        label: d.label,\n        longLabel: d.long,\n        value: d.total,\n        compareValue,\n      };\n    });\n  }, [s.days, s.prevDays, focusItem, comparisonMode, isEmpty]);\n\n  const compareLabel =\n    comparisonMode === 'prior-period'\n      ? `Prior ${range}d window`\n      : focusItem\n        ? focusItem.name\n        : undefined;\n\n  const barItems = React.useMemo(() => {\n    if (isEmpty) return [];\n    return s.rows.map((r, idx) => ({\n      id: r.id,\n      name: r.name,\n      value: r.value,\n      formattedValue: fmtMoney(r.value),\n      share: r.share,\n      badge: idx === 0 ? 'Top performer' : undefined,\n    }));\n  }, [s.rows, isEmpty]);\n\n  const displayRevenue = isEmpty ? 0 : s.revenue;\n  const displayRevenueDelta = isEmpty ? 0 : s.revenueDelta;\n  const displayProfit = isEmpty ? 0 : s.profit;\n  const displayProfitDelta = isEmpty ? 0 : s.profitDelta;\n  const displayLift = isEmpty ? 0 : s.lift;\n  const displayLiftDelta = isEmpty ? 0 : s.liftDelta;\n\n  return (\n    <>\n      <Scene gutter=\"scene\" layout=\"split\" aria-busy={isLoading || undefined}>\n        <Panel className=\"c01\" label=\"Recovered revenue over time\">\n          {isLoading ? (\n            <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-c01-skeleton`}>\n              <Skeleton variant=\"line\" width=\"42%\" label=\"Loading recovered revenue metric\" />\n              <Skeleton variant=\"metric\" width=\"64%\" />\n              <Skeleton variant=\"block\" height={chartHeight} />\n            </div>\n          ) : (\n            <>\n              <div className=\"f12-c01-hd\">\n                <Metric\n                  label=\"Recovered revenue\"\n                  value={displayRevenue}\n                  format={fmtMoney}\n                  delta={displayRevenueDelta}\n                  deltaKind=\"pct\"\n                  range={range}\n                  motion={motion}\n                  big\n                />\n                {compareLabel ? (\n                  <ul className=\"f12-legend\" aria-label=\"Chart legend\" role=\"list\">\n                    <li>\n                      <i className=\"f12-sw f12-sw-total\" aria-hidden=\"true\" />\n                      All interventions\n                    </li>\n                    <li>\n                      <i className=\"f12-sw f12-sw-focus\" aria-hidden=\"true\" />\n                      {compareLabel}\n                    </li>\n                  </ul>\n                ) : (\n                  <p className=\"f12-legend f12-legend-hint\">\n                    Select an intervention in C-04 to compare it with the total.\n                  </p>\n                )}\n              </div>\n              {isEmpty ? (\n                <EmptyState\n                  id={`${resolvedIdPrefix}-chart-empty`}\n                  code=\"ZERO RECOVERY EVENTS\"\n                  title=\"No recovered checkout revenue in this sandbox state\"\n                  description=\"The active simulation state is set to ZERO (empty). Switch back to LIVE fixture data to inspect the 180-day Fernwood Supply Co. recovery series.\"\n                  action={\n                    onRestorePopulated ? (\n                      <Button\n                        id={`${resolvedIdPrefix}-restore-from-empty-chart`}\n                        variant=\"primary\"\n                        size=\"sm\"\n                        onClick={onRestorePopulated}\n                      >\n                        Load sample data\n                      </Button>\n                    ) : undefined\n                  }\n                />\n              ) : (\n                <ToneAreaChart\n                  data={chartData}\n                  seriesLabel=\"Recovered revenue\"\n                  labelColumnHeader=\"Date\"\n                  compareLabel={compareLabel}\n                  formatValue={fmtMoney}\n                  formatShort={fmtMoneyShort}\n                  motion={motion}\n                  height={chartHeight}\n                />\n              )}\n            </>\n          )}\n        </Panel>\n\n        <PanelPair\n          top={{\n            label: 'Incremental profit',\n            children: isLoading ? (\n              <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-c02-skeleton`}>\n                <Skeleton variant=\"line\" width=\"48%\" label=\"Loading incremental profit metric\" />\n                <Skeleton variant=\"metric\" width=\"70%\" />\n                <Skeleton variant=\"block\" height={74} />\n              </div>\n            ) : (\n              <Metric\n                label=\"Incremental profit\"\n                value={displayProfit}\n                format={fmtMoney}\n                delta={displayProfitDelta}\n                deltaKind=\"pct\"\n                range={range}\n                note={PROFIT_NOTE}\n                motion={motion}\n                spark={\n                  <ToneSpark\n                    values={isEmpty ? [0, 0, 0, 0, 0, 0, 0] : s.days.map((d) => d.profit)}\n                    label=\"Daily profit\"\n                    rangeKey={range}\n                    motion={motion}\n                  />\n                }\n              />\n            ),\n          }}\n          bottom={{\n            label: 'Conversion lift',\n            children: isLoading ? (\n              <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-c03-skeleton`}>\n                <Skeleton variant=\"line\" width=\"45%\" label=\"Loading conversion lift metric\" />\n                <Skeleton variant=\"metric\" width=\"68%\" />\n                <Skeleton variant=\"block\" height={74} />\n              </div>\n            ) : (\n              <Metric\n                label=\"Conversion lift\"\n                value={displayLift}\n                format={fmtPP}\n                delta={displayLiftDelta}\n                deltaKind=\"pp\"\n                range={range}\n                note={LIFT_NOTE}\n                motion={motion}\n                spark={\n                  <ToneSpark\n                    values={isEmpty ? [0, 0, 0, 0, 0, 0, 0] : s.days.map((d) => d.lift)}\n                    label=\"Daily lift\"\n                    rangeKey={range}\n                    motion={motion}\n                  />\n                }\n              />\n            ),\n          }}\n        />\n      </Scene>\n\n      <Scene gutter=\"scene\" layout=\"stack\" aria-busy={isLoading || undefined}>\n        <Panel className=\"c04\" label=\"Revenue by intervention\">\n          {isLoading ? (\n            <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-c04-skeleton`}>\n              <Skeleton variant=\"line\" width=\"38%\" label=\"Loading ranked interventions\" />\n              <Skeleton variant=\"block\" height={180} />\n              <SkeletonText lines={2} />\n            </div>\n          ) : isEmpty ? (\n            <EmptyState\n              id={`${resolvedIdPrefix}-interventions-empty`}\n              code=\"NO ATTRIBUTION ROWS\"\n              title=\"Zero intervention triggers recorded\"\n              description=\"No abandoned-cart, exit-intent, back-in-stock, price-drop, or post-purchase upsell events exist in the empty simulation state.\"\n            />\n          ) : (\n            <ToneBarList\n              title=\"Revenue by intervention\"\n              subtitle={`Last ${s.range} days · share of recovered revenue`}\n              items={barItems}\n              selectedId={focus}\n              onSelect={onSelectFocus}\n              motion={motion}\n              changed={changed}\n              idPrefix={resolvedIdPrefix}\n            />\n          )}\n        </Panel>\n      </Scene>\n    </>\n  );\n}\n\n// ============================================================================\n// STANDALONE INSTALLABLE ANALYTICS APPLICATION BLOCK (`AnalyticsDashboard`)\n// Combines Expressive Storyboard (C-01..C-04) with Quiet Supporting Ledgers.\n// ============================================================================\n\nexport type LedgerSortMode = 'date-desc' | 'revenue-desc' | 'profit-desc';\n\nconst DATASET_STATE_OPTIONS: Array<{ value: AnalyticsDatasetState; label: string; unit: string }> = [\n  { value: 'populated', label: 'LIVE', unit: 'fixture' },\n  { value: 'loading', label: 'LOAD', unit: 'skel' },\n  { value: 'empty', label: 'ZERO', unit: 'empty' },\n  { value: 'error', label: 'ERR', unit: '503' },\n];\n\nconst COMPARISON_MODE_OPTIONS: Array<{\n  value: AnalyticsComparisonMode;\n  label: string;\n  unit: string;\n}> = [\n  { value: 'intervention', label: 'FOCUS', unit: 'c-04' },\n  { value: 'prior-period', label: 'PREV', unit: 'period' },\n];\n\nconst LEDGER_PAGE_SIZE = 10;\n\nexport interface AnalyticsDashboardProps {\n  /** Default observation window in days (`30` by default). */\n  defaultRange?: RangeDays;\n  /** Default focused intervention ID (`null` by default). */\n  defaultFocusId?: string | null;\n  /** Default chart comparison mode (`'intervention'` by default). */\n  defaultComparisonMode?: AnalyticsComparisonMode;\n  /** Default dataset simulation state (`'populated'` by default). */\n  defaultDatasetState?: AnalyticsDatasetState;\n  /** Alias for `defaultRange`. */\n  initialRange?: RangeDays;\n  /** Alias for `defaultFocusId`. */\n  initialFocusId?: string | null;\n  /** Alias for `defaultComparisonMode`. */\n  initialComparisonMode?: AnalyticsComparisonMode;\n  /** Alias for `defaultDatasetState`. */\n  initialDatasetState?: AnalyticsDatasetState;\n  /** Motion grammar override (`'stepped'` 12fps by default). */\n  motion?: MotionMode;\n  /** Theme override (`'light'` or `'dark'`). */\n  theme?: 'light' | 'dark';\n  /** Additional CSS class names for the root `<Sheet>`. */\n  className?: string;\n  /** Show interactive sandbox state switcher (`true` by default). */\n  showSandboxControls?: boolean;\n  /** Deterministic DOM ID prefix (`'f12-analytics-<id>'` by default). */\n  idPrefix?: string;\n  /** Optional slot rendered below the sheet header. */\n  headerSlot?: React.ReactNode;\n  /** Optional slot rendered at the bottom of the sheet. */\n  footerSlot?: React.ReactNode;\n}\n\nfunction AnalyticsDashboardInner({\n  defaultRange,\n  defaultFocusId,\n  defaultComparisonMode,\n  defaultDatasetState,\n  initialRange,\n  initialFocusId,\n  initialComparisonMode,\n  initialDatasetState,\n  motion = 'stepped',\n  theme,\n  className,\n  showSandboxControls = true,\n  idPrefix,\n  headerSlot,\n  footerSlot,\n}: AnalyticsDashboardProps) {\n  const autoId = React.useId().replace(/[^a-zA-Z0-9_-]/g, '');\n  const resolvedIdPrefix = idPrefix ?? `f12-analytics-${autoId}`;\n  const { toast } = useToast();\n\n  const [range, setRange] = React.useState<RangeDays>(\n    defaultRange ?? initialRange ?? DEFAULT_RANGE,\n  );\n  const [focus, setFocus] = React.useState<string | null>(\n    defaultFocusId !== undefined ? defaultFocusId : (initialFocusId ?? null),\n  );\n  const [comparisonMode, setComparisonMode] =\n    React.useState<AnalyticsComparisonMode>(\n      defaultComparisonMode ?? initialComparisonMode ?? 'intervention',\n    );\n  const [datasetState, setDatasetState] =\n    React.useState<AnalyticsDatasetState>(\n      defaultDatasetState ?? initialDatasetState ?? 'populated',\n    );\n\n  const [segmentFilter, setSegmentFilter] = React.useState<CheckoutSegmentId | 'all'>('all');\n  const [ledgerSearch, setLedgerSearch] = React.useState<string>('');\n  const [ledgerSort, setLedgerSort] = React.useState<LedgerSortMode>('date-desc');\n  const [ledgerPage, setLedgerPage] = React.useState<number>(1);\n  const [inspectedDayKey, setInspectedDayKey] = React.useState<string | null>(null);\n\n  const pendingFocusTargetIdRef = React.useRef<string | null>(null);\n\n  React.useEffect(() => {\n    const targetId = pendingFocusTargetIdRef.current;\n    if (!targetId) return;\n    pendingFocusTargetIdRef.current = null;\n    const raf = window.requestAnimationFrame(() => {\n      const el = document.getElementById(targetId);\n      if (el && typeof el.focus === 'function') {\n        el.focus();\n      }\n    });\n    return () => window.cancelAnimationFrame(raf);\n  }, [range, focus, comparisonMode, datasetState, segmentFilter, ledgerSearch, ledgerSort, ledgerPage, inspectedDayKey]);\n\n  const s = SUMMARIES[range];\n  const focusItem = focus ? INTERVENTIONS.find((i) => i.id === focus) ?? null : null;\n  const isLoading = datasetState === 'loading';\n  const isEmpty = datasetState === 'empty';\n  const isError = datasetState === 'error';\n\n  // Reset pagination to page 1 when range or filters change\n  const handleRangeChange = (nextRange: RangeDays) => {\n    setRange(nextRange);\n    setLedgerPage(1);\n  };\n\n  const handleFocusSelect = (nextId: string | null) => {\n    setFocus(nextId);\n    setLedgerPage(1);\n  };\n\n  const handleSegmentSelect = (nextSeg: CheckoutSegmentId | 'all') => {\n    setSegmentFilter(nextSeg);\n    setLedgerPage(1);\n  };\n\n  const handleRestorePopulated = () => {\n    pendingFocusTargetIdRef.current = `${resolvedIdPrefix}-rng-${range}`;\n    setDatasetState('populated');\n    toast({\n      status: 'success',\n      title: 'Restored Fernwood Supply Co. telemetry',\n      description: `Loaded ${range}-day deterministic recovery fixture through ${END_LABEL}.`,\n    });\n  };\n\n  const isDrilledIn = focusItem !== null || segmentFilter !== 'all';\n\n  const handleClearDrillDown = () => {\n    // The breadcrumb button that triggered this turns back into plain text, so hand focus to the\n    // dashboard heading (the level the reader just stepped up to) before it unmounts.\n    const targetId = `${resolvedIdPrefix}-title`;\n    document.getElementById(targetId)?.focus({ preventScroll: true });\n    pendingFocusTargetIdRef.current = targetId;\n    setFocus(null);\n    setSegmentFilter('all');\n    setLedgerPage(1);\n  };\n\n  const handleResetView = () => {\n    const targetId = `${resolvedIdPrefix}-rng-${DEFAULT_RANGE}`;\n    pendingFocusTargetIdRef.current = null;\n    setRange(DEFAULT_RANGE);\n    setFocus(null);\n    setComparisonMode('intervention');\n    setDatasetState('populated');\n    setSegmentFilter('all');\n    setLedgerSearch('');\n    setLedgerSort('date-desc');\n    setLedgerPage(1);\n    setInspectedDayKey(null);\n    window.requestAnimationFrame(() => {\n      document.getElementById(targetId)?.focus();\n    });\n    toast({\n      status: 'info',\n      title: 'Reset analytics view',\n      description: 'Restored 30-day window, all interventions, all checkout segments, and default date sorting.',\n    });\n  };\n\n  // Reconciled Segment Breakdown scoped to either all interventions or the focused intervention\n  const scopedSegments = React.useMemo<SegmentRow[]>(() => {\n    if (isEmpty) {\n      return CHECKOUT_SEGMENTS.map((seg) => ({\n        id: seg.id,\n        name: seg.name,\n        shortName: seg.shortName,\n        description: seg.description,\n        revenue: 0,\n        prevRevenue: 0,\n        deltaPct: 0,\n        profit: 0,\n        share: 0,\n      }));\n    }\n    if (!focusItem) {\n      return s.segments;\n    }\n    const scopeRev = sum(s.days, (d) => d.byId[focusItem.id]);\n    return CHECKOUT_SEGMENTS.map((seg) => {\n      const rev = sum(s.days, (d) => d.byIdAndSegment[focusItem.id][seg.id]);\n      const prevRev = sum(s.prevDays, (d) => d.byIdAndSegment[focusItem.id][seg.id]);\n      const prof = sum(s.days, (d) => d.profitByIdAndSegment[focusItem.id][seg.id]);\n      return {\n        id: seg.id,\n        name: seg.name,\n        shortName: seg.shortName,\n        description: seg.description,\n        revenue: rev,\n        prevRevenue: prevRev,\n        deltaPct: prevRev > 0 ? (rev - prevRev) / prevRev : 0,\n        profit: prof,\n        share: scopeRev > 0 ? rev / scopeRev : 0,\n      };\n    });\n  }, [s, focusItem, isEmpty]);\n\n  const scopedTotalRevenue = React.useMemo(\n    () => sum(scopedSegments, (seg) => seg.revenue),\n    [scopedSegments],\n  );\n  const scopedTotalProfit = React.useMemo(\n    () => sum(scopedSegments, (seg) => seg.profit),\n    [scopedSegments],\n  );\n\n  // Reconciled Period Comparison scoped to either all interventions or the focused intervention\n  const scopedPeriod = React.useMemo(() => {\n    if (!focusItem) {\n      return {\n        revenue: s.revenue,\n        prevRevenue: s.prevRevenue,\n        revenueDelta: s.revenueDelta,\n        profit: s.profit,\n        prevProfit: s.prevProfit,\n        profitDelta: s.profitDelta,\n        netMarginPct: s.netMarginPct,\n        prevNetMarginPct: s.prevNetMarginPct,\n        peakLabel: s.peak.label,\n        peakValue: s.peak.total,\n        prevPeakLabel: s.prevPeak.label,\n        prevPeakValue: s.prevPeak.total,\n      };\n    }\n    const rev = sum(s.days, (d) => d.byId[focusItem.id]);\n    const prevRev = sum(s.prevDays, (d) => d.byId[focusItem.id]);\n    const prof = sum(s.days, (d) => d.profitById[focusItem.id]);\n    const prevProf = sum(s.prevDays, (d) => d.profitById[focusItem.id]);\n    let peakDay = s.days[0];\n    for (const d of s.days) {\n      if (d.byId[focusItem.id] > peakDay.byId[focusItem.id]) peakDay = d;\n    }\n    let prevPeakDay = s.prevDays[0];\n    for (const d of s.prevDays) {\n      if (d.byId[focusItem.id] > prevPeakDay.byId[focusItem.id]) prevPeakDay = d;\n    }\n    return {\n      revenue: rev,\n      prevRevenue: prevRev,\n      revenueDelta: prevRev > 0 ? (rev - prevRev) / prevRev : 0,\n      profit: prof,\n      prevProfit: prevProf,\n      profitDelta: prevProf > 0 ? (prof - prevProf) / prevProf : 0,\n      netMarginPct: rev > 0 ? (prof / rev) * 100 : 0,\n      prevNetMarginPct: prevRev > 0 ? (prevProf / prevRev) * 100 : 0,\n      peakLabel: peakDay.label,\n      peakValue: peakDay.byId[focusItem.id],\n      prevPeakLabel: prevPeakDay.label,\n      prevPeakValue: prevPeakDay.byId[focusItem.id],\n    };\n  }, [s, focusItem]);\n\n  // Reconciled Daily Recovery Ledger rows (filtered by intervention, segment, and search query)\n  const ledgerRows = React.useMemo(() => {\n    if (isEmpty) return [];\n    const q = ledgerSearch.trim().toLowerCase();\n\n    const mapped = s.days.map((d) => {\n      let rowRevenue: number;\n      let rowProfit: number;\n\n      if (focusItem && segmentFilter !== 'all') {\n        rowRevenue = d.byIdAndSegment[focusItem.id][segmentFilter];\n        rowProfit = d.profitByIdAndSegment[focusItem.id][segmentFilter];\n      } else if (focusItem) {\n        rowRevenue = d.byId[focusItem.id];\n        rowProfit = d.profitById[focusItem.id];\n      } else if (segmentFilter !== 'all') {\n        rowRevenue = d.bySegment[segmentFilter];\n        rowProfit = d.profitBySegment[segmentFilter];\n      } else {\n        rowRevenue = d.total;\n        rowProfit = d.profit;\n      }\n\n      let activeInterventionMeta = focusItem;\n      if (!activeInterventionMeta) {\n        let bestIntervention = INTERVENTIONS[0];\n        let bestInterventionRev = -1;\n        for (const it of INTERVENTIONS) {\n          const candidateRev =\n            segmentFilter !== 'all'\n              ? d.byIdAndSegment[it.id][segmentFilter]\n              : d.byId[it.id];\n          if (candidateRev > bestInterventionRev) {\n            bestInterventionRev = candidateRev;\n            bestIntervention = it;\n          }\n        }\n        activeInterventionMeta = bestIntervention;\n      }\n\n      let activeSegmentMeta =\n        segmentFilter !== 'all'\n          ? CHECKOUT_SEGMENTS.find((seg) => seg.id === segmentFilter) ?? null\n          : null;\n      if (!activeSegmentMeta) {\n        let bestSegment = CHECKOUT_SEGMENTS[0];\n        let bestSegmentRev = -1;\n        for (const seg of CHECKOUT_SEGMENTS) {\n          const candidateRev = focusItem\n            ? d.byIdAndSegment[focusItem.id][seg.id]\n            : d.bySegment[seg.id];\n          if (candidateRev > bestSegmentRev) {\n            bestSegmentRev = candidateRev;\n            bestSegment = seg;\n          }\n        }\n        activeSegmentMeta = bestSegment;\n      }\n\n      const marginPct = rowRevenue > 0 ? (rowProfit / rowRevenue) * 100 : 0;\n\n      const candidateInterventions = focusItem ? [focusItem] : INTERVENTIONS;\n      const contributingInterventions = candidateInterventions.filter((it) => {\n        const rev =\n          segmentFilter !== 'all'\n            ? d.byIdAndSegment[it.id][segmentFilter]\n            : d.byId[it.id];\n        return rev > 0;\n      });\n      const candidateSegments =\n        segmentFilter !== 'all'\n          ? CHECKOUT_SEGMENTS.filter((seg) => seg.id === segmentFilter)\n          : CHECKOUT_SEGMENTS;\n      const contributingSegments = candidateSegments.filter((seg) => {\n        const rev = focusItem\n          ? d.byIdAndSegment[focusItem.id][seg.id]\n          : d.bySegment[seg.id];\n        return rev > 0;\n      });\n\n      return {\n        day: d,\n        dayKey: d.dayKey,\n        label: d.label,\n        longLabel: d.long,\n        revenue: rowRevenue,\n        profit: rowProfit,\n        marginPct,\n        lift: d.lift,\n        interventionName: activeInterventionMeta.name,\n        channel: activeInterventionMeta.channel,\n        segmentName: activeSegmentMeta.shortName,\n        evidenceNote: d.evidenceNote,\n        contributingInterventions,\n        contributingSegments,\n      };\n    });\n\n    const filtered = q\n      ? mapped.filter(\n          (r) =>\n            r.label.toLowerCase().includes(q) ||\n            r.longLabel.toLowerCase().includes(q) ||\n            r.dayKey.toLowerCase().includes(q) ||\n            r.interventionName.toLowerCase().includes(q) ||\n            r.channel.toLowerCase().includes(q) ||\n            r.segmentName.toLowerCase().includes(q) ||\n            r.evidenceNote.toLowerCase().includes(q) ||\n            r.contributingInterventions.some(\n              (it) =>\n                it.name.toLowerCase().includes(q) ||\n                it.channel.toLowerCase().includes(q),\n            ) ||\n            r.contributingSegments.some(\n              (seg) =>\n                seg.name.toLowerCase().includes(q) ||\n                seg.shortName.toLowerCase().includes(q),\n            ),\n        )\n      : mapped;\n\n    const sorted = [...filtered];\n    if (ledgerSort === 'date-desc') {\n      sorted.sort((a, b) => b.day.ms - a.day.ms);\n    } else if (ledgerSort === 'revenue-desc') {\n      sorted.sort((a, b) => b.revenue - a.revenue || b.day.ms - a.day.ms);\n    } else if (ledgerSort === 'profit-desc') {\n      sorted.sort((a, b) => b.profit - a.profit || b.day.ms - a.day.ms);\n    }\n    return sorted;\n  }, [s.days, focusItem, segmentFilter, ledgerSearch, ledgerSort, isEmpty]);\n\n  const totalLedgerRevenue = React.useMemo(\n    () => sum(ledgerRows, (r) => r.revenue),\n    [ledgerRows],\n  );\n  const totalLedgerProfit = React.useMemo(\n    () => sum(ledgerRows, (r) => r.profit),\n    [ledgerRows],\n  );\n  const totalLedgerMarginPct =\n    totalLedgerRevenue > 0 ? (totalLedgerProfit / totalLedgerRevenue) * 100 : 0;\n  const avgLedgerLift =\n    ledgerRows.length > 0 ? sum(ledgerRows, (r) => r.lift) / ledgerRows.length : 0;\n\n  const totalPages = Math.max(1, Math.ceil(ledgerRows.length / LEDGER_PAGE_SIZE));\n  const safePage = Math.min(ledgerPage, totalPages);\n  const pagedLedgerRows = React.useMemo(\n    () =>\n      ledgerRows.slice(\n        (safePage - 1) * LEDGER_PAGE_SIZE,\n        safePage * LEDGER_PAGE_SIZE,\n      ),\n    [ledgerRows, safePage],\n  );\n\n  const inspectedDay = React.useMemo(\n    () => (inspectedDayKey ? s.days.find((d) => d.dayKey === inspectedDayKey) ?? null : null),\n    [inspectedDayKey, s.days],\n  );\n\n  const hasActiveFilters =\n    focus !== null ||\n    segmentFilter !== 'all' ||\n    ledgerSearch.trim().length > 0 ||\n    ledgerSort !== 'date-desc';\n\n  const postureTag: { status: TagStatus; label: string } = isError\n    ? { status: 'danger', label: 'WAREHOUSE FAULT' }\n    : isEmpty\n      ? { status: 'neutral', label: 'EMPTY SANDBOX' }\n      : isLoading\n        ? { status: 'info', label: 'LOADING TELEMETRY' }\n        : { status: 'success', label: 'RECONCILED LEDGER' };\n\n  const activeScopeBreadcrumbLabel = focusItem\n    ? `${range}d · ${focusItem.name}`\n    : segmentFilter !== 'all'\n      ? `${range}d · ${CHECKOUT_SEGMENTS.find((seg) => seg.id === segmentFilter)?.shortName}`\n      : `${range}d Window (${s.days[0].label} – ${s.days[s.days.length - 1].label})`;\n\n  return (\n    <Sheet\n      id={`${resolvedIdPrefix}-sheet`}\n      autoCut\n      pegs\n      motion={motion}\n      theme={theme}\n      className={['f12-console', 'f12-analytics', className].filter(Boolean).join(' ')}\n    >\n      {/* ===================================================================== SHEET HEADER */}\n      <header className=\"f12-hd\">\n        <div className=\"f12-hd-text\">\n          <Breadcrumb\n            aria-label=\"Analytics hierarchy\"\n            density=\"compact\"\n            items={[\n              // Store root: context text — no store-level view exists inside this block.\n              { label: STORE },\n              {\n                // Dashboard level: while drilled into an intervention or checkout segment, steps\n                // back out to the whole-dashboard scope (the date window is kept).\n                label: 'Revenue Recovery',\n                onSelect: isDrilledIn ? handleClearDrillDown : undefined,\n              },\n              {\n                label: activeScopeBreadcrumbLabel,\n                current: true,\n              },\n            ]}\n          />\n          <p className=\"f12-eyebrow\">\n            <span>{STORE} · Revenue Recovery Analytics</span>\n            <Tag status={postureTag.status} id={`${resolvedIdPrefix}-posture-tag`}>\n              {postureTag.label}\n            </Tag>\n            <Badge burst={false}>{`Through ${END_LABEL}`}</Badge>\n          </p>\n          <h1 className=\"f12-title\" id={`${resolvedIdPrefix}-title`} tabIndex={-1}>\n            Revenue Recovery\n          </h1>\n          <p className=\"f12-sub\" id={`${resolvedIdPrefix}-subtitle`}>\n            Expressive storyboard establishing shot{' '}\n            <span className=\"f12-nowrap\">\n              (<code className=\"f12-code-inline\">C-01</code>–<code className=\"f12-code-inline\">C-04</code>)\n            </span>{' '}\n            paired with Quiet period-comparison,\n            checkout-segment, and daily attribution ledgers reconciled from a single{' '}\n            <code className=\"f12-code-inline\">mulberry32(1207)</code> fixture.\n          </p>\n        </div>\n\n        <div className=\"f12-stack-pair\">\n          <div\n            className=\"f12-row-pair\"\n            role=\"group\"\n            aria-label=\"Observation window and comparison controls\"\n          >\n            <SegmentedControl\n              idPrefix={`${resolvedIdPrefix}-rng`}\n              ariaLabel=\"Date range\"\n              options={RANGE_OPTIONS}\n              value={range}\n              onChange={handleRangeChange}\n            />\n            <SegmentedControl\n              idPrefix={`${resolvedIdPrefix}-compare`}\n              ariaLabel=\"Time-series comparison overlay\"\n              options={COMPARISON_MODE_OPTIONS}\n              value={comparisonMode}\n              onChange={setComparisonMode}\n            />\n          </div>\n\n          {showSandboxControls ? (\n            <div\n              className=\"f12-row-pair\"\n              role=\"group\"\n              aria-label=\"Sandbox dataset state and view reset\"\n            >\n              <SegmentedControl\n                idPrefix={`${resolvedIdPrefix}-dataset`}\n                ariaLabel=\"Dataset simulation state\"\n                options={DATASET_STATE_OPTIONS}\n                value={datasetState}\n                onChange={setDatasetState}\n              />\n              <Button\n                id={`${resolvedIdPrefix}-reset-btn`}\n                variant=\"secondary\"\n                size=\"sm\"\n                onClick={handleResetView}\n              >\n                Reset sandbox\n              </Button>\n            </div>\n          ) : null}\n        </div>\n      </header>\n\n      {headerSlot}\n\n      {/* ===================================================================== FAULT BANNER */}\n      {isError ? (\n        <Alert\n          id={`${resolvedIdPrefix}-error-banner`}\n          status=\"danger\"\n          title=\"Warehouse attribution feed interrupted — HTTP 503\"\n          actions={\n            <Button\n              id={`${resolvedIdPrefix}-retry-btn`}\n              variant=\"primary\"\n              size=\"sm\"\n              onClick={handleRestorePopulated}\n            >\n              Retry attribution sync\n            </Button>\n          }\n        >\n          Upstream holdout reconciliation worker timed out while refreshing checkout attribution.\n          Cached local figures remain visible below; click Retry attribution sync to restore live\n          sandbox state.\n        </Alert>\n      ) : null}\n\n      {/* ===================================================================== EXPRESSIVE STORYBOARD (C-01..C-04) */}\n      <RevenueRecoveryCoreScenes\n        range={range}\n        focus={focus}\n        onSelectFocus={(nextId) => {\n          handleFocusSelect(nextId);\n          if (nextId !== null && comparisonMode === 'prior-period') {\n            setComparisonMode('intervention');\n          }\n        }}\n        motion={motion}\n        idPrefix={resolvedIdPrefix}\n        chartHeight={320}\n        datasetState={datasetState}\n        comparisonMode={comparisonMode}\n        onRestorePopulated={handleRestorePopulated}\n      />\n\n      {/* ===================================================================== QUIET OPERATIONAL ANALYTICS: PERIOD COMPARISON & SEGMENT BREAKDOWN */}\n      <Scene gutter=\"scene\" layout=\"equal\" aria-busy={isLoading || undefined}>\n        <Panel\n          variant=\"quiet\"\n          id={`${resolvedIdPrefix}-period-comparison-panel`}\n          label=\"Period-over-period comparison and holdout methodology\"\n        >\n          {isLoading ? (\n            <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-period-skeleton`}>\n              <Skeleton variant=\"line\" width=\"52%\" />\n              <Skeleton variant=\"block\" height={190} />\n              <SkeletonText lines={2} />\n            </div>\n          ) : (\n            <div className=\"f12-stack-pair\">\n              <div className=\"f12-row-between\">\n                <div className=\"f12-row-pair\">\n                  <h2 className=\"f12-console-quiet-title\">\n                    PERIOD COMPARISON · CURRENT {range}D VS. PRIOR {range}D\n                  </h2>\n                  <Tag status={focusItem ? 'info' : 'neutral'}>\n                    {focusItem ? `SCOPED: ${focusItem.name.toUpperCase()}` : 'ALL INTERVENTIONS'}\n                  </Tag>\n                  <Tag status={comparisonMode === 'prior-period' ? 'info' : 'neutral'}>\n                    {comparisonMode === 'prior-period' ? 'CHART OVERLAY ACTIVE' : 'QUIET LEDGER'}\n                  </Tag>\n                </div>\n                <Button\n                  id={`${resolvedIdPrefix}-toggle-prev-overlay`}\n                  variant={comparisonMode === 'prior-period' ? 'primary' : 'secondary'}\n                  size=\"sm\"\n                  onClick={() => {\n                    setComparisonMode(\n                      comparisonMode === 'prior-period' ? 'intervention' : 'prior-period',\n                    );\n                  }}\n                >\n                  {comparisonMode === 'prior-period'\n                    ? 'Hide prior-period overlay'\n                    : `Overlay prior ${range}d on C-01`}\n                </Button>\n              </div>\n              <p className=\"f12-console-quiet-sub\">\n                Direct window-over-window reconciliation comparing the active {range}-day window\n                ({s.days[0].label} – {s.days[s.days.length - 1].label}) against the immediately\n                preceding {range}-day baseline ({s.prevDays[0].label} –{' '}\n                {s.prevDays[s.prevDays.length - 1].label})\n                {focusItem ? ` for ${focusItem.name}` : ''}.\n              </p>\n\n              <Table density=\"compact\" id={`${resolvedIdPrefix}-period-table`}>\n                <TableCaption>\n                  Reconciled {range}-day period comparison through {END_LABEL}\n                  {focusItem ? ` (${focusItem.name})` : ''}.\n                </TableCaption>\n                <TableHeader>\n                  <TableRow>\n                    <TableHead>Metric</TableHead>\n                    <TableHead>{`Current (${range}d)`}</TableHead>\n                    <TableHead>{`Prior (${range}d)`}</TableHead>\n                    <TableHead>Delta</TableHead>\n                  </TableRow>\n                </TableHeader>\n                <TableBody>\n                  <TableRow>\n                    <TableCell>Recovered revenue</TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-period-cur-revenue`}>\n                      {fmtMoney(isEmpty ? 0 : scopedPeriod.revenue)}\n                    </TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-period-prev-revenue`}>\n                      {fmtMoney(isEmpty ? 0 : scopedPeriod.prevRevenue)}\n                    </TableCell>\n                    <TableCell>\n                      <Tag\n                        status={\n                          isEmpty ? 'neutral' : scopedPeriod.revenueDelta >= 0 ? 'success' : 'warning'\n                        }\n                      >\n                        {isEmpty ? '+0.0%' : fmtSignedPct(scopedPeriod.revenueDelta)}\n                      </Tag>\n                    </TableCell>\n                  </TableRow>\n                  <TableRow>\n                    <TableCell>Incremental profit</TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-period-cur-profit`}>\n                      {fmtMoney(isEmpty ? 0 : scopedPeriod.profit)}\n                    </TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-period-prev-profit`}>\n                      {fmtMoney(isEmpty ? 0 : scopedPeriod.prevProfit)}\n                    </TableCell>\n                    <TableCell>\n                      <Tag\n                        status={\n                          isEmpty ? 'neutral' : scopedPeriod.profitDelta >= 0 ? 'success' : 'warning'\n                        }\n                      >\n                        {isEmpty ? '+0.0%' : fmtSignedPct(scopedPeriod.profitDelta)}\n                      </Tag>\n                    </TableCell>\n                  </TableRow>\n                  <TableRow>\n                    <TableCell>Net profit margin</TableCell>\n                    <TableCell>{`${(isEmpty ? 0 : scopedPeriod.netMarginPct).toFixed(1)}%`}</TableCell>\n                    <TableCell>{`${(isEmpty ? 0 : scopedPeriod.prevNetMarginPct).toFixed(1)}%`}</TableCell>\n                    <TableCell>\n                      {(() => {\n                        if (isEmpty) return '0.0 pp';\n                        const curMargin = Number(scopedPeriod.netMarginPct.toFixed(1));\n                        const prevMargin = Number(scopedPeriod.prevNetMarginPct.toFixed(1));\n                        const marginDelta = Number((curMargin - prevMargin).toFixed(1));\n                        return `${marginDelta > 0 ? '+' : ''}${marginDelta.toFixed(1)} pp`;\n                      })()}\n                    </TableCell>\n                  </TableRow>\n                  <TableRow>\n                    <TableCell>Conversion lift vs. holdout</TableCell>\n                    <TableCell>{isEmpty ? '+0.00 pp' : fmtPP(s.lift)}</TableCell>\n                    <TableCell>{isEmpty ? '+0.00 pp' : fmtPP(s.prevLift)}</TableCell>\n                    <TableCell>\n                      {(() => {\n                        const displayedLiftDelta = isEmpty\n                          ? 0\n                          : Number((Number(s.lift.toFixed(2)) - Number(s.prevLift.toFixed(2))).toFixed(2));\n                        return (\n                          <Tag\n                            status={\n                              isEmpty || Math.abs(displayedLiftDelta) < 0.005\n                                ? 'neutral'\n                                : displayedLiftDelta > 0\n                                  ? 'success'\n                                  : 'warning'\n                            }\n                          >\n                            {isEmpty || Math.abs(displayedLiftDelta) < 0.005\n                              ? '0.00 pp'\n                              : fmtPP(displayedLiftDelta)}\n                          </Tag>\n                        );\n                      })()}\n                    </TableCell>\n                  </TableRow>\n                  <TableRow>\n                    <TableCell>Peak daily recovery</TableCell>\n                    <TableCell>\n                      {isEmpty\n                        ? '$0'\n                        : `${scopedPeriod.peakLabel} · ${fmtMoney(scopedPeriod.peakValue)}`}\n                    </TableCell>\n                    <TableCell>\n                      {isEmpty\n                        ? '$0'\n                        : `${scopedPeriod.prevPeakLabel} · ${fmtMoney(scopedPeriod.prevPeakValue)}`}\n                    </TableCell>\n                    <TableCell>\n                      {isEmpty\n                        ? '+0.0%'\n                        : fmtSignedPct(\n                            (scopedPeriod.peakValue - scopedPeriod.prevPeakValue) /\n                              scopedPeriod.prevPeakValue,\n                          )}\n                    </TableCell>\n                  </TableRow>\n                </TableBody>\n              </Table>\n\n              <Notice status=\"info\" title=\"Deterministic holdout & margin accounting\">\n                Every trigger withholds a 10% randomized holdout cohort. Incremental profit deducts\n                channel delivery and discount costs per intervention (Abandoned-cart 38% margin,\n                Exit-intent 22%, Back-in-stock 41%, Price-drop 18%, Post-purchase upsell 46%).\n              </Notice>\n            </div>\n          )}\n        </Panel>\n\n        <Panel\n          variant=\"quiet\"\n          id={`${resolvedIdPrefix}-segment-breakdown-panel`}\n          label=\"Checkout segment breakdown\"\n        >\n          {isLoading ? (\n            <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-segment-skeleton`}>\n              <Skeleton variant=\"line\" width=\"48%\" />\n              <Skeleton variant=\"block\" height={190} />\n              <SkeletonText lines={2} />\n            </div>\n          ) : (\n            <div className=\"f12-stack-pair\">\n              <div className=\"f12-row-between\">\n                <div className=\"f12-stack-pair\">\n                  <div className=\"f12-row-pair\">\n                    <h2 className=\"f12-console-quiet-title\">\n                      CHECKOUT SEGMENT BREAKDOWN\n                    </h2>\n                    <Tag status={focusItem ? 'info' : 'neutral'}>\n                      {focusItem ? `SCOPED: ${focusItem.name.toUpperCase()}` : 'ALL INTERVENTIONS'}\n                    </Tag>\n                  </div>\n                  <p className=\"f12-console-quiet-sub\">\n                    Cohort and device attribution reconciled to 100% of{' '}\n                    {focusItem ? `${focusItem.name} revenue` : `total ${range}-day recovered revenue`}{' '}\n                    ({fmtMoney(scopedTotalRevenue)}). Select a segment to filter the daily ledger.\n                  </p>\n                </div>\n              </div>\n\n              <div\n                className=\"f12-row-pair\"\n                role=\"group\"\n                aria-label=\"Filter daily ledger by checkout segment\"\n              >\n                <Button\n                  id={`${resolvedIdPrefix}-seg-filter-all`}\n                  variant={segmentFilter === 'all' ? 'primary' : 'secondary'}\n                  size=\"sm\"\n                  aria-pressed={segmentFilter === 'all'}\n                  onClick={() => handleSegmentSelect('all')}\n                >\n                  All segments (100%)\n                </Button>\n                {scopedSegments.map((seg) => (\n                  <Button\n                    key={seg.id}\n                    id={`${resolvedIdPrefix}-seg-filter-${seg.id}`}\n                    variant={segmentFilter === seg.id ? 'primary' : 'secondary'}\n                    size=\"sm\"\n                    aria-pressed={segmentFilter === seg.id}\n                    onClick={() =>\n                      handleSegmentSelect(segmentFilter === seg.id ? 'all' : seg.id)\n                    }\n                  >\n                    {`${seg.shortName} (${Math.round(seg.share * 100)}%)`}\n                  </Button>\n                ))}\n              </div>\n\n              <Table density=\"compact\" id={`${resolvedIdPrefix}-segment-table`}>\n                <TableCaption>\n                  Checkout segment breakdown for {focusItem ? focusItem.name : `all interventions`} (\n                  {range} days).\n                </TableCaption>\n                <TableHeader>\n                  <TableRow>\n                    <TableHead>Segment</TableHead>\n                    <TableHead>Recovered</TableHead>\n                    <TableHead>Profit</TableHead>\n                    <TableHead>Share</TableHead>\n                    <TableHead>vs. Prior</TableHead>\n                  </TableRow>\n                </TableHeader>\n                <TableBody>\n                  {scopedSegments.map((seg) => (\n                    <TableRow key={seg.id}>\n                      <TableCell>\n                        <strong>{seg.name}</strong>\n                        <div className=\"f12-mono-note f12-analytics-seg-desc\">{seg.description}</div>\n                      </TableCell>\n                      <TableCell>{fmtMoney(seg.revenue)}</TableCell>\n                      <TableCell>{fmtMoney(seg.profit)}</TableCell>\n                      <TableCell>{`${(seg.share * 100).toFixed(1)}%`}</TableCell>\n                      <TableCell>\n                        <Tag status={isEmpty ? 'neutral' : seg.deltaPct >= 0 ? 'success' : 'warning'}>\n                          {isEmpty ? '+0.0%' : fmtSignedPct(seg.deltaPct)}\n                        </Tag>\n                      </TableCell>\n                    </TableRow>\n                  ))}\n                </TableBody>\n                <TableFooter>\n                  <TableRow>\n                    <TableCell>\n                      {focusItem ? `Total (${focusItem.name})` : `Total (${range} days)`}\n                    </TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-segment-total-revenue`}>\n                      {fmtMoney(scopedTotalRevenue)}\n                    </TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-segment-total-profit`}>\n                      {fmtMoney(scopedTotalProfit)}\n                    </TableCell>\n                    <TableCell>{isEmpty ? '0.0%' : '100.0%'}</TableCell>\n                    <TableCell>\n                      {isEmpty\n                        ? '+0.0%'\n                        : fmtSignedPct(\n                            focusItem\n                              ? s.rows.find((r) => r.id === focusItem.id)?.deltaPct ?? 0\n                              : s.revenueDelta,\n                          )}\n                    </TableCell>\n                  </TableRow>\n                </TableFooter>\n              </Table>\n            </div>\n          )}\n        </Panel>\n      </Scene>\n\n      {/* ===================================================================== QUIET OPERATIONAL ANALYTICS: FILTERABLE DAILY RECOVERY LEDGER */}\n      <Scene gutter=\"scene\" layout=\"stack\" aria-busy={isLoading || undefined}>\n        <Panel\n          variant=\"quiet\"\n          id={`${resolvedIdPrefix}-daily-ledger-panel`}\n          label=\"Filterable daily recovery ledger and supporting evidence\"\n        >\n          {isLoading ? (\n            <div className=\"f12-stack-pair\" id={`${resolvedIdPrefix}-ledger-skeleton`}>\n              <Skeleton variant=\"line\" width=\"44%\" />\n              <Skeleton variant=\"block\" height={260} />\n            </div>\n          ) : (\n            <div className=\"f12-stack-scene\">\n              <div className=\"f12-stack-pair\">\n                <div className=\"f12-row-between\">\n                  <div className=\"f12-row-pair\">\n                    <h2 className=\"f12-console-quiet-title\">\n                      DAILY RECOVERY &amp; ATTRIBUTION EVIDENCE LEDGER\n                    </h2>\n                    <Tag status=\"neutral\" id={`${resolvedIdPrefix}-ledger-count-tag`}>\n                      {`${ledgerRows.length} OF ${isEmpty ? 0 : s.days.length} DAYS`}\n                    </Tag>\n                    {focusItem ? (\n                      <Tag status=\"info\">{`INTERVENTION: ${focusItem.name.toUpperCase()}`}</Tag>\n                    ) : null}\n                    {segmentFilter !== 'all' ? (\n                      <Tag status=\"info\">\n                        {`SEGMENT: ${CHECKOUT_SEGMENTS.find((seg) => seg.id === segmentFilter)?.shortName.toUpperCase()}`}\n                      </Tag>\n                    ) : null}\n                  </div>\n\n                  {hasActiveFilters ? (\n                    <Button\n                      id={`${resolvedIdPrefix}-clear-ledger-filters`}\n                      variant=\"secondary\"\n                      size=\"sm\"\n                      onClick={() => {\n                        pendingFocusTargetIdRef.current = `${resolvedIdPrefix}-ledger-search`;\n                        setFocus(null);\n                        setSegmentFilter('all');\n                        setLedgerSearch('');\n                        setLedgerSort('date-desc');\n                        setLedgerPage(1);\n                      }}\n                    >\n                      Clear active filters\n                    </Button>\n                  ) : null}\n                </div>\n                <p className=\"f12-console-quiet-sub\">\n                  Filter daily recovery records by date, intervention, or checkout segment. Unfiltered\n                  column totals reconcile exactly with C-01 ({fmtMoney(isEmpty ? 0 : s.revenue)}) and\n                  C-02 ({fmtMoney(isEmpty ? 0 : s.profit)}).\n                </p>\n              </div>\n\n              <div className=\"f12-console-filters\" role=\"group\" aria-label=\"Daily ledger filters\">\n                <Input\n                  id={`${resolvedIdPrefix}-ledger-search`}\n                  density=\"compact\"\n                  label=\"Search date, intervention, or note\"\n                  placeholder=\"e.g. Oct 31, Exit-intent, weekend...\"\n                  value={ledgerSearch}\n                  onChange={(e) => {\n                    setLedgerSearch(e.target.value);\n                    setLedgerPage(1);\n                  }}\n                />\n\n                <Select\n                  id={`${resolvedIdPrefix}-ledger-intervention`}\n                  density=\"compact\"\n                  label=\"Intervention filter\"\n                  value={focus ?? 'all'}\n                  onValueChange={(val) => handleFocusSelect(val === 'all' ? null : val)}\n                >\n                  <SelectTrigger>\n                    <SelectValue />\n                  </SelectTrigger>\n                  <SelectContent>\n                    <SelectItem value=\"all\">All interventions (5)</SelectItem>\n                    {INTERVENTIONS.map((it) => (\n                      <SelectItem key={it.id} value={it.id}>\n                        {`${it.name} (${it.channel})`}\n                      </SelectItem>\n                    ))}\n                  </SelectContent>\n                </Select>\n\n                <Select\n                  id={`${resolvedIdPrefix}-ledger-segment`}\n                  density=\"compact\"\n                  label=\"Checkout segment\"\n                  value={segmentFilter}\n                  onValueChange={(val) =>\n                    handleSegmentSelect(val as CheckoutSegmentId | 'all')\n                  }\n                >\n                  <SelectTrigger>\n                    <SelectValue />\n                  </SelectTrigger>\n                  <SelectContent>\n                    <SelectItem value=\"all\">All checkout segments (3)</SelectItem>\n                    {CHECKOUT_SEGMENTS.map((seg) => (\n                      <SelectItem key={seg.id} value={seg.id}>\n                        {seg.name}\n                      </SelectItem>\n                    ))}\n                  </SelectContent>\n                </Select>\n\n                <Select\n                  id={`${resolvedIdPrefix}-ledger-sort`}\n                  density=\"compact\"\n                  label=\"Sort order\"\n                  value={ledgerSort}\n                  onValueChange={(val) => {\n                    setLedgerSort(val as LedgerSortMode);\n                    setLedgerPage(1);\n                  }}\n                >\n                  <SelectTrigger>\n                    <SelectValue />\n                  </SelectTrigger>\n                  <SelectContent>\n                    <SelectItem value=\"date-desc\">Date (newest first)</SelectItem>\n                    <SelectItem value=\"revenue-desc\">Recovered revenue (high → low)</SelectItem>\n                    <SelectItem value=\"profit-desc\">Incremental profit (high → low)</SelectItem>\n                  </SelectContent>\n                </Select>\n              </div>\n\n              {ledgerRows.length === 0 ? (\n                <EmptyState\n                  id={`${resolvedIdPrefix}-ledger-empty`}\n                  code={isEmpty ? 'EMPTY DATASET' : 'NO MATCHING DAYS'}\n                  title={\n                    isEmpty\n                      ? 'No daily recovery records in ZERO state'\n                      : 'No daily ledger rows match the current filter query'\n                  }\n                  description={\n                    isEmpty\n                      ? 'Switch the dataset simulation state back to LIVE to populate the daily attribution ledger.'\n                      : `No days in the ${range}-day window matched \"${ledgerSearch}\". Reset the search and scope filters to restore all ${s.days.length} daily rows.`\n                  }\n                  action={\n                    isEmpty ? (\n                      <Button\n                        id={`${resolvedIdPrefix}-ledger-restore-dataset`}\n                        variant=\"primary\"\n                        size=\"sm\"\n                        onClick={handleRestorePopulated}\n                      >\n                        Load sample data\n                      </Button>\n                    ) : (\n                      <Button\n                        id={`${resolvedIdPrefix}-ledger-reset-empty`}\n                        variant=\"primary\"\n                        size=\"sm\"\n                        onClick={() => {\n                          pendingFocusTargetIdRef.current = `${resolvedIdPrefix}-ledger-search`;\n                          setFocus(null);\n                          setSegmentFilter('all');\n                          setLedgerSearch('');\n                          setLedgerSort('date-desc');\n                          setLedgerPage(1);\n                        }}\n                      >\n                        Reset ledger filters\n                      </Button>\n                    )\n                  }\n                />\n              ) : (\n                <>\n                  <Table density=\"compact\" id={`${resolvedIdPrefix}-ledger-table`}>\n                    <TableCaption>\n                      Daily recovery attribution ledger ({ledgerRows.length} matching day(s) in{' '}\n                      {range}-day window; totals reconcile with C-01..C-04).\n                    </TableCaption>\n                    <TableHeader>\n                      <TableRow>\n                        <TableHead>Date</TableHead>\n                        <TableHead>{focusItem ? 'Scoped Intervention' : 'Top Intervention'}</TableHead>\n                        <TableHead>{segmentFilter !== 'all' ? 'Scoped Segment' : 'Lead Segment'}</TableHead>\n                        <TableHead>Recovered Revenue</TableHead>\n                        <TableHead>Incremental Profit</TableHead>\n                        <TableHead>Net Margin</TableHead>\n                        <TableHead>Lift vs. Holdout</TableHead>\n                        <TableHead>Evidence</TableHead>\n                      </TableRow>\n                    </TableHeader>\n                    <TableBody>\n                      {pagedLedgerRows.map((row) => (\n                        <TableRow key={row.dayKey}>\n                          <TableCell>\n                            <code className=\"f12-code-inline\">{row.label}</code>\n                          </TableCell>\n                          <TableCell>\n                            <strong>{row.interventionName}</strong>\n                            <span className=\"f12-mono-note\">{` · ${row.channel}`}</span>\n                          </TableCell>\n                          <TableCell>{row.segmentName}</TableCell>\n                          <TableCell>{fmtMoney(row.revenue)}</TableCell>\n                          <TableCell>{fmtMoney(row.profit)}</TableCell>\n                          <TableCell>{`${row.marginPct.toFixed(1)}%`}</TableCell>\n                          <TableCell>{fmtPP(row.lift)}</TableCell>\n                          <TableCell>\n                            <Button\n                              id={`${resolvedIdPrefix}-inspect-day-${row.dayKey}`}\n                              variant=\"secondary\"\n                              size=\"sm\"\n                              onClick={(e) => {\n                                e.currentTarget.focus();\n                                setInspectedDayKey(row.dayKey);\n                              }}\n                            >\n                              Inspect day\n                            </Button>\n                          </TableCell>\n                        </TableRow>\n                      ))}\n                    </TableBody>\n                    <TableFooter>\n                      <TableRow>\n                        <TableCell colSpan={3}>\n                          {`Reconciled total (${ledgerRows.length} day${ledgerRows.length === 1 ? '' : 's'})`}\n                        </TableCell>\n                        <TableCell id={`${resolvedIdPrefix}-ledger-total-revenue`}>\n                          {fmtMoney(totalLedgerRevenue)}\n                        </TableCell>\n                        <TableCell id={`${resolvedIdPrefix}-ledger-total-profit`}>\n                          {fmtMoney(totalLedgerProfit)}\n                        </TableCell>\n                        <TableCell>{`${totalLedgerMarginPct.toFixed(1)}%`}</TableCell>\n                        <TableCell>{fmtPP(avgLedgerLift)}</TableCell>\n                        <TableCell>100% reconciled</TableCell>\n                      </TableRow>\n                    </TableFooter>\n                  </Table>\n\n                  <Pagination\n                    id={`${resolvedIdPrefix}-ledger-pagination`}\n                    density=\"compact\"\n                    page={safePage}\n                    totalPages={totalPages}\n                    totalItems={ledgerRows.length}\n                    pageSize={LEDGER_PAGE_SIZE}\n                    onPageChange={setLedgerPage}\n                  />\n                </>\n              )}\n            </div>\n          )}\n        </Panel>\n      </Scene>\n\n      {/* ===================================================================== C-05: DAILY ATTRIBUTION & EVIDENCE DIALOG */}\n      <Dialog\n        open={inspectedDay !== null}\n        onOpenChange={(open) => {\n          if (!open) setInspectedDayKey(null);\n        }}\n      >\n        <DialogContent\n          cut=\"C-05\"\n          id={`${resolvedIdPrefix}-day-dialog`}\n        >\n          <DialogHeader>\n            <DialogTitle>\n              {inspectedDay\n                ? `Daily Recovery Attribution · ${inspectedDay.long}`\n                : 'Daily Recovery Attribution'}\n            </DialogTitle>\n            <DialogDescription>\n              {inspectedDay\n                ? `Reconciled intervention and checkout-segment breakdown for ${inspectedDay.long} (${fmtMoney(inspectedDay.total)} recovered revenue · ${fmtMoney(inspectedDay.profit)} incremental profit · ${fmtPP(inspectedDay.lift)} conversion lift).`\n                : 'Daily breakdown.'}\n            </DialogDescription>\n          </DialogHeader>\n\n          {inspectedDay ? (\n            <div className=\"f12-stack-pair\">\n              <Notice status=\"info\" title=\"Operational attribution note\">\n                {inspectedDay.evidenceNote}\n              </Notice>\n\n              <Table density=\"compact\" id={`${resolvedIdPrefix}-day-dialog-table`}>\n                <TableCaption>\n                  Intervention breakdown for {inspectedDay.long}.\n                </TableCaption>\n                <TableHeader>\n                  <TableRow>\n                    <TableHead>Intervention</TableHead>\n                    <TableHead>Channel</TableHead>\n                    <TableHead>Recovered</TableHead>\n                    <TableHead>Profit</TableHead>\n                    <TableHead>Share</TableHead>\n                  </TableRow>\n                </TableHeader>\n                <TableBody>\n                  {INTERVENTIONS.map((it) => {\n                    const val = inspectedDay.byId[it.id];\n                    const prof = inspectedDay.profitById[it.id];\n                    const sharePct =\n                      inspectedDay.total > 0 ? (val / inspectedDay.total) * 100 : 0;\n                    return (\n                      <TableRow key={it.id}>\n                        <TableCell>\n                          <strong>{it.name}</strong>\n                        </TableCell>\n                        <TableCell>{it.channel}</TableCell>\n                        <TableCell>{fmtMoney(val)}</TableCell>\n                        <TableCell>{fmtMoney(prof)}</TableCell>\n                        <TableCell>{`${sharePct.toFixed(1)}%`}</TableCell>\n                      </TableRow>\n                    );\n                  })}\n                </TableBody>\n                <TableFooter>\n                  <TableRow>\n                    <TableCell colSpan={2}>{`Day total (${inspectedDay.label})`}</TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-day-dialog-total-rev`}>\n                      {fmtMoney(inspectedDay.total)}\n                    </TableCell>\n                    <TableCell id={`${resolvedIdPrefix}-day-dialog-total-profit`}>\n                      {fmtMoney(inspectedDay.profit)}\n                    </TableCell>\n                    <TableCell>100.0%</TableCell>\n                  </TableRow>\n                </TableFooter>\n              </Table>\n\n              <Table density=\"compact\" id={`${resolvedIdPrefix}-day-dialog-segment-table`}>\n                <TableCaption>\n                  Checkout segment breakdown for {inspectedDay.long}.\n                </TableCaption>\n                <TableHeader>\n                  <TableRow>\n                    <TableHead>Checkout Segment</TableHead>\n                    <TableHead>Recovered</TableHead>\n                    <TableHead>Profit</TableHead>\n                    <TableHead>Share</TableHead>\n                  </TableRow>\n                </TableHeader>\n                <TableBody>\n                  {CHECKOUT_SEGMENTS.map((seg) => {\n                    const segRev = inspectedDay.bySegment[seg.id];\n                    const segProf = inspectedDay.profitBySegment[seg.id];\n                    const segShare =\n                      inspectedDay.total > 0 ? (segRev / inspectedDay.total) * 100 : 0;\n                    return (\n                      <TableRow key={seg.id}>\n                        <TableCell>\n                          <strong>{seg.shortName}</strong>\n                        </TableCell>\n                        <TableCell>{fmtMoney(segRev)}</TableCell>\n                        <TableCell>{fmtMoney(segProf)}</TableCell>\n                        <TableCell>{`${segShare.toFixed(1)}%`}</TableCell>\n                      </TableRow>\n                    );\n                  })}\n                </TableBody>\n              </Table>\n            </div>\n          ) : null}\n\n          <DialogFooter>\n            {inspectedDay ? (\n              <Button\n                id={`${resolvedIdPrefix}-day-dialog-filter-top`}\n                variant=\"secondary\"\n                size=\"sm\"\n                onClick={() => {\n                  const topId = inspectedDay.topInterventionId;\n                  const topMeta = INTERVENTIONS.find((it) => it.id === topId);\n                  pendingFocusTargetIdRef.current = `${resolvedIdPrefix}-ledger-search`;\n                  setFocus(topId);\n                  setComparisonMode('intervention');\n                  setLedgerPage(1);\n                  setInspectedDayKey(null);\n                  toast({\n                    status: 'info',\n                    title: `Scoped to ${topMeta?.name ?? topId}`,\n                    description: `Filtered C-01 chart overlay, segment breakdown, and daily ledger to ${topMeta?.name ?? topId}.`,\n                  });\n                }}\n              >\n                Filter by top intervention\n              </Button>\n            ) : null}\n            <DialogClose\n              id={`${resolvedIdPrefix}-day-dialog-close`}\n              variant=\"primary\"\n              size=\"sm\"\n            >\n              Close breakdown\n            </DialogClose>\n          </DialogFooter>\n        </DialogContent>\n      </Dialog>\n\n      {footerSlot}\n    </Sheet>\n  );\n}\n\nexport function AnalyticsDashboard(props: AnalyticsDashboardProps) {\n  const existingToast = useOptionalToast();\n  if (existingToast) {\n    return <AnalyticsDashboardInner {...props} />;\n  }\n  return (\n    <ToastProvider>\n      <AnalyticsDashboardInner {...props} />\n    </ToastProvider>\n  );\n}\nexport { AnalyticsDashboard as RevenueRecoveryAnalytics };\n",
      "type": "registry:block",
      "target": "components/frame12/blocks/analytics-dashboard.tsx"
    }
  ],
  "type": "registry:block"
}