{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "insights-02",
  "description": "An unusual reading against the range it was expected to fall in, with the days outside it shaded, the worst day labelled on the chart, the explanation and likely causes.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "card",
    "button",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/chart-panel.json",
    "https://www.dashboardblocks.com/r/radix/insights.json",
    "https://www.dashboardblocks.com/r/radix/kpi.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/insights/insights-02.tsx",
      "content": "'use client'\n\nimport {\n  BlockReady,\n  BlockStateProvider,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartPlaceholder,\n  chartActiveDot,\n  chartAxisProps,\n  chartGridProps,\n  chartLineCursor,\n  ChartTooltipFrame,\n  ChartTooltipItem,\n  chartValueAxisWidth,\n} from '@/registry/components/dashboardblocks/chart'\nimport {\n  ChartPanelFigure,\n  ChartPanelLegend,\n  ChartPanelTable,\n} from '@/registry/components/dashboardblocks/chart-panel'\nimport {\n  type InsightDriver,\n  InsightDrivers,\n  InsightLabel,\n  type InsightSegment,\n  InsightText,\n  insightKindConfig,\n} from '@/registry/components/dashboardblocks/insights'\nimport { KPIValue } from '@/registry/components/dashboardblocks/kpi'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  formatDate,\n  formatNumber,\n  formatPercent,\n  formatSigned,\n} from '@/registry/lib/dashboardblocks/format'\nimport { useState } from 'react'\nimport {\n  Area,\n  CartesianGrid,\n  ComposedChart,\n  Line,\n  ReferenceArea,\n  ReferenceDot,\n  ResponsiveContainer,\n  Tooltip,\n  XAxis,\n  YAxis,\n} from 'recharts'\n\nimport { Button, buttonVariants } from '@/components/ui/button'\nimport { Card, CardContent } from '@/components/ui/card'\n\nimport { cn } from '@/lib/utils'\n\ninterface Reading {\n  high: number\n  label: string\n  low: number\n  value: number\n}\n\ninterface Insights2Props extends BlockStateProps {\n  description: string\n  drivers?: InsightDriver[]\n  explanation: InsightSegment[]\n  formatter?: (value: number) => string\n  href?: string\n  metric: string\n  onMarkExpected?: () => void\n  /** Leave out, or pass none, to show the empty state. */\n  readings?: Reading[]\n  title: string\n}\n\nconst DAY = 86_400_000\nconst NOW = Date.UTC(2026, 8, 25)\nconst OUTAGE: Record<number, number> = { 24: 212, 25: 281 }\n\nconst exampleProps: Insights2Props = {\n  description:\n    'Daily checkout conversions over the last 28 days, against the range they usually fall in.',\n  drivers: [\n    { label: 'Card payment errors', tone: 'negative', value: '+4.2 pp' },\n    { label: 'iOS app', tone: 'negative', value: '−51%' },\n    { label: 'Sessions', value: '+1%' },\n  ],\n  explanation: [\n    'Conversions fell to ',\n    { text: '212', tone: 'negative' },\n    ' on Tuesday and stayed low on Wednesday. Sessions and add-to-cart were ',\n    { text: 'normal' },\n    ', so the drop happened at payment, where card errors ',\n    { text: 'rose 4.2 points', tone: 'negative' },\n    '.',\n  ],\n  href: '#',\n  metric: 'Conversions',\n  readings: Array.from({ length: 28 }, (_, index) => {\n    const date = new Date(NOW - (27 - index) * DAY)\n    const weekend = date.getUTCDay() % 6 === 0\n    const expected = (weekend ? 286 : 342) + index * 0.9\n    return {\n      high: Math.round(expected * 1.08),\n      label: formatDate(date, 'day'),\n      low: Math.round(expected * 0.92),\n      value: OUTAGE[index] ?? Math.round(expected + Math.sin(index * 1.7) * 13),\n    }\n  }),\n  title: 'Unusual drop in checkout conversions',\n}\n\nconst SERIES_COLOR = 'var(--color-chart-2)'\nconst BAND_COLOR = 'var(--color-muted-foreground)'\nconst ANOMALY_COLOR = insightKindConfig.anomaly.fill\n\nconst formatChange = (value: number) =>\n  formatSigned(value, (magnitude) => formatPercent(magnitude / 100))\n\nfunction getAnomalyRanges(anomalous: boolean[]) {\n  const ranges: Array<{ end: number; start: number }> = []\n  anomalous.forEach((isAnomalous, index) => {\n    if (!isAnomalous) return\n    const last = ranges[ranges.length - 1]\n    if (last && last.end === index - 1) last.end = index\n    else ranges.push({ end: index, start: index })\n  })\n  return ranges\n}\n\nconst Insights2 = (props: Insights2Props) => {\n  const {\n    description,\n    drivers,\n    explanation,\n    formatter = (value) => formatNumber(value, { maximumFractionDigits: 0 }),\n    href,\n    metric,\n    onMarkExpected,\n    readings = [],\n    errorMessage,\n    status,\n    title,\n  } = props\n  const [markedExpected, setMarkedExpected] = useState(false)\n  const state = getBlockState(status, readings)\n\n  const data = readings.map((reading, index) => {\n    const anomalous = reading.value < reading.low || reading.value > reading.high\n    return {\n      ...reading,\n      anomalous,\n      band: [reading.low, reading.high],\n      index,\n      note: anomalous ? 'Anomaly' : '',\n    }\n  })\n  const ranges = getAnomalyRanges(data.map((point) => point.anomalous))\n  const anomalies = data.filter((point) => point.anomalous)\n  const expectedOf = (point: Reading) => (point.low + point.high) / 2\n  const deviation = (point: Reading) =>\n    Math.abs(point.value - expectedOf(point)) / expectedOf(point)\n  const worst = anomalies.reduce<(typeof data)[number] | undefined>(\n    (current, point) =>\n      !current || deviation(point) > deviation(current) ? point : current,\n    undefined,\n  )\n  const worstChange = worst\n    ? Math.round(((worst.value - expectedOf(worst)) / expectedOf(worst)) * 100)\n    : 0\n  const yMax =\n    Math.ceil(\n      (Math.max(...data.map((point) => Math.max(point.value, point.high))) * 1.1) / 50,\n    ) * 50\n  const last = data.length - 1\n  const ticks = data\n    .filter((point) => (last - point.index) % 7 === 0)\n    .map((point) => point.index)\n\n  return (\n    <Card>\n      <CardContent>\n        <BlockStateProvider errorMessage={errorMessage} state={state}>\n          <section className='@container flex flex-col gap-4'>\n            <header className='flex items-start justify-between gap-3'>\n              <div className='flex min-w-0 flex-col gap-0.5'>\n                <h2 className='font-semibold tracking-tight'>{title}</h2>\n                <p className='text-muted-foreground text-sm'>{description}</p>\n              </div>\n              {!state && (\n                <InsightLabel\n                  className='mt-0.5'\n                  kind={markedExpected ? 'neutral' : 'anomaly'}\n                  label={markedExpected ? 'Expected' : undefined}\n                />\n              )}\n            </header>\n            {state && (\n              <dl className='grid grid-cols-3 gap-4 border-t pt-4'>\n                <div className='col-span-3 flex min-w-0 flex-col gap-1 @md:col-span-1'>\n                  <dt className='text-muted-foreground text-sm'>{metric}</dt>\n                  <dd>\n                    <KPIValue className='text-3xl @2xl:text-4xl' value={undefined} />\n                  </dd>\n                </div>\n                {state === 'loading' && (\n                  <>\n                    <div className='hidden min-w-0 flex-col gap-1 @md:flex'>\n                      <dt className='text-muted-foreground text-sm'>Expected</dt>\n                      <dd>\n                        <KPIValue className='text-2xl' value={undefined} />\n                      </dd>\n                    </div>\n                    <div className='hidden min-w-0 flex-col gap-1 @md:flex'>\n                      <dt className='text-muted-foreground text-sm'>Difference</dt>\n                      <dd>\n                        <KPIValue className='text-2xl' value={undefined} />\n                      </dd>\n                    </div>\n                  </>\n                )}\n              </dl>\n            )}\n            {!state && worst && (\n              <dl className='grid grid-cols-3 gap-4 border-t pt-4'>\n                <div className='flex min-w-0 flex-col gap-1'>\n                  <dt className='text-muted-foreground text-sm'>{worst.label}</dt>\n                  <dd className='text-3xl font-light tracking-tight whitespace-nowrap tabular-nums @2xl:text-4xl'>\n                    {formatter(worst.value)}\n                  </dd>\n                </div>\n                <div className='flex min-w-0 flex-col gap-1'>\n                  <dt className='text-muted-foreground text-sm'>Expected</dt>\n                  <dd className='text-2xl font-light tracking-tight whitespace-nowrap tabular-nums'>\n                    {formatter(worst.low)}–{formatter(worst.high)}\n                  </dd>\n                </div>\n                <div className='flex min-w-0 flex-col gap-1'>\n                  <dt className='text-muted-foreground text-sm'>Difference</dt>\n                  <dd\n                    className={cn(\n                      'text-2xl font-light tracking-tight whitespace-nowrap tabular-nums',\n                      worstChange < 0 && 'text-red-700 dark:text-red-400',\n                    )}\n                  >\n                    {formatChange(worstChange)}\n                  </dd>\n                </div>\n              </dl>\n            )}\n            <div className='flex flex-col gap-3'>\n              {(!state || state === 'loading') && (\n                <ChartPanelLegend\n                  items={[\n                    { color: SERIES_COLOR, label: metric, shape: 'line' },\n                    {\n                      color:\n                        'color-mix(in oklab, var(--color-muted-foreground) 30%, transparent)',\n                      label: 'Expected range',\n                    },\n                    { color: ANOMALY_COLOR, label: 'Anomaly' },\n                  ]}\n                />\n              )}\n              {state ? (\n                <ChartPlaceholder height={208} />\n              ) : (\n                <>\n                  <ChartPanelFigure className='h-52'>\n                    <ResponsiveContainer width='100%' height='100%'>\n                      <ComposedChart\n                        aria-label={`${title} chart`}\n                        data={data}\n                        margin={{ top: 20, right: 8, bottom: 0, left: 0 }}\n                      >\n                        <CartesianGrid {...chartGridProps} />\n                        <XAxis\n                          {...chartAxisProps}\n                          dataKey='index'\n                          domain={[0, last]}\n                          tickFormatter={(index: number) => data[index]?.label ?? ''}\n                          ticks={ticks}\n                          type='number'\n                        />\n                        <YAxis\n                          {...chartAxisProps}\n                          domain={[0, yMax]}\n                          tickFormatter={(value: number) => formatter(value)}\n                          width={chartValueAxisWidth}\n                        />\n                        {ranges.map((range) => (\n                          <ReferenceArea\n                            key={range.start}\n                            fill={ANOMALY_COLOR}\n                            fillOpacity={0.14}\n                            ifOverflow='hidden'\n                            x1={range.start - 0.5}\n                            x2={range.end + 0.5}\n                          />\n                        ))}\n                        <Tooltip\n                          content={({ active, payload }) => {\n                            const point = payload?.[0]?.payload as\n                              | (typeof data)[number]\n                              | undefined\n                            if (!active || !point) return null\n                            return (\n                              <ChartTooltipFrame>\n                                <span className='font-medium'>{point.label}</span>\n                                <ChartTooltipItem\n                                  color={SERIES_COLOR}\n                                  name={metric}\n                                  value={formatter(point.value)}\n                                />\n                                <span className='text-muted-foreground tabular-nums'>\n                                  Expected {formatter(point.low)}–{formatter(point.high)}\n                                </span>\n                                {point.anomalous && (\n                                  <InsightLabel className='text-xs' kind='anomaly' />\n                                )}\n                              </ChartTooltipFrame>\n                            )\n                          }}\n                          cursor={chartLineCursor}\n                        />\n                        <Area\n                          activeDot={false}\n                          dataKey='band'\n                          fill={BAND_COLOR}\n                          fillOpacity={0.14}\n                          name='Expected range'\n                          stroke='none'\n                          type='monotone'\n                        />\n                        <Line\n                          activeDot={chartActiveDot}\n                          dataKey='value'\n                          dot={({ cx, cy, index, payload }) =>\n                            (payload as (typeof data)[number]).anomalous ? (\n                              <circle\n                                key={index}\n                                cx={cx}\n                                cy={cy}\n                                fill={ANOMALY_COLOR}\n                                r={4.5}\n                                stroke='var(--color-background)'\n                                strokeWidth={2}\n                              />\n                            ) : (\n                              <g key={index} />\n                            )\n                          }\n                          name={metric}\n                          stroke={SERIES_COLOR}\n                          strokeLinecap='round'\n                          strokeWidth={2}\n                          type='monotone'\n                        />\n                        {worst && (\n                          <ReferenceDot\n                            x={worst.index}\n                            y={worst.value}\n                            r={0}\n                            label={{\n                              fill: 'var(--color-foreground)',\n                              fontSize: 11,\n                              fontWeight: 500,\n                              position: worst.index > last * 0.75 ? 'left' : 'right',\n                              value: `${formatChange(worstChange)} vs expected`,\n                            }}\n                          />\n                        )}\n                      </ComposedChart>\n                    </ResponsiveContainer>\n                  </ChartPanelFigure>\n                  <ChartPanelTable\n                    caption={`${metric} by day against the expected range. ${anomalies.length} ${anomalies.length === 1 ? 'day was' : 'days were'} outside it.`}\n                    columns={[\n                      { key: 'label', label: 'Day' },\n                      { format: formatter, key: 'value', label: metric },\n                      { format: formatter, key: 'low', label: 'Expected low' },\n                      { format: formatter, key: 'high', label: 'Expected high' },\n                      { key: 'note', label: 'Note' },\n                    ]}\n                    rows={data}\n                  />\n                </>\n              )}\n            </div>\n            {(!state || state === 'loading') && (\n              <div className='flex flex-col gap-3 border-t pt-4'>\n                <BlockReady className='text-sm'>\n                  <InsightText segments={explanation} />\n                  {drivers && <InsightDrivers drivers={drivers} label='Likely causes' />}\n                </BlockReady>\n              </div>\n            )}\n            <div className='flex flex-wrap gap-2'>\n              {href && !state && (\n                <a href={href} className={buttonVariants({ size: 'sm' })}>\n                  Investigate\n                  <IconPlaceholder\n                    lucide='ArrowRightIcon'\n                    tabler='IconArrowRight'\n                    hugeicons='ArrowRight01Icon'\n                    phosphor='ArrowRightIcon'\n                    remixicon='RiArrowRightLine'\n                    data-icon='inline-end'\n                  />\n                </a>\n              )}\n              <Button\n                variant='outline'\n                size='sm'\n                disabled={markedExpected || state !== undefined}\n                onClick={() => {\n                  setMarkedExpected(true)\n                  onMarkExpected?.()\n                }}\n              >\n                {markedExpected ? 'Marked as expected' : 'Mark as expected'}\n              </Button>\n            </div>\n          </section>\n        </BlockStateProvider>\n      </CardContent>\n    </Card>\n  )\n}\n\nexport { Insights2, exampleProps as insights2ExampleProps, type Insights2Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/insights/insights-02.tsx"
    }
  ],
  "meta": {
    "shows": "An unusual reading against the range it was expected to fall in, with the days outside it shaded, the worst day labelled on the chart, the explanation and likely causes.",
    "size": "half",
    "usedWith": [
      "insights-03",
      "chart-panel-01",
      "alerts-01"
    ],
    "component": "Insights2",
    "props": "{ description: string; drivers?: { label: string; value: string; tone?: \"neutral\" | \"positive\" | \"negative\" }[]; explanation: (string | { text: string; tone?: \"neutral\" | \"positive\" | \"negative\" })[]; formatter?: (value: number) => string; href?: string; metric: string; onMarkExpected?: () => void; readings?: { high: number; label: string; low: number; value: number }[]; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
