{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "forecast-02",
  "description": "The running total heading for a goal line, with the forecast, its 80% range, the deadline and the date it gets there.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "card",
    "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/forecast.json",
    "https://www.dashboardblocks.com/r/radix/kpi.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/forecast/forecast-02.tsx",
      "content": "'use client'\n\nimport {\n  BlockReady,\n  BlockStateProvider,\n  BlockStateText,\n  type BlockStateProps,\n  SkeletonText,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartPlaceholder,\n  chartActiveDot,\n  chartAxisProps,\n  chartGridProps,\n  chartLineCursor,\n  chartReferenceLabel,\n  chartReferenceProps,\n  chartValueAxisWidth,\n  useChartId,\n} from '@/registry/components/dashboardblocks/chart'\nimport {\n  ChartPanelFigure,\n  ChartPanelTable,\n} from '@/registry/components/dashboardblocks/chart-panel'\nimport {\n  type ConfidenceLevel,\n  ForecastLegend,\n  ForecastStatusLabel,\n  ForecastTooltip,\n  buildForecast,\n  fitLinear,\n  forecastColors,\n  forecastDash,\n  getDeadlineStatus,\n  getForecastAxis,\n  solveForTarget,\n} from '@/registry/components/dashboardblocks/forecast'\nimport { KPIValue } from '@/registry/components/dashboardblocks/kpi'\nimport {\n  formatCompact,\n  formatDate,\n  formatDateRange,\n  formatNumber,\n  formatPercent,\n} from '@/registry/lib/dashboardblocks/format'\nimport {\n  Area,\n  CartesianGrid,\n  ComposedChart,\n  Line,\n  ReferenceDot,\n  ReferenceLine,\n  ResponsiveContainer,\n  Tooltip,\n  XAxis,\n  YAxis,\n} from 'recharts'\n\nimport { Card, CardContent } from '@/components/ui/card'\n\ninterface Forecast2Props extends BlockStateProps {\n  /** Running totals so far, oldest first, one step apart. Leave out, or pass none, to show the empty state. */\n  actuals?: number[]\n  deadline: Date\n  formatter?: (value: number) => string\n  lastDate: Date\n  /** @default 0.8 */\n  level?: ConfidenceLevel\n  metric: string\n  now: Date\n  stepDays?: number\n  target: number\n  title: string\n}\n\nconst exampleProps: Forecast2Props = {\n  actuals: Array.from({ length: 12 }, (_, week) =>\n    Math.round(\n      7_320 + week * 155 + Math.sin(week / 1.3) * 110 - (week % 4 === 1 ? 80 : 0),\n    ),\n  ),\n  deadline: new Date(Date.UTC(2026, 11, 31)),\n  formatter: (value) => formatNumber(value, { maximumFractionDigits: 0 }),\n  lastDate: new Date(Date.UTC(2026, 8, 20)),\n  metric: 'paying customers',\n  now: new Date(Date.UTC(2026, 8, 26)),\n  target: 10_000,\n  title: 'Paying customers goal',\n}\n\nconst DAY = 86_400_000\n\nconst Forecast2 = (props: Forecast2Props) => {\n  const {\n    actuals = [],\n    deadline,\n    formatter = (value) => formatNumber(value, { maximumFractionDigits: 0 }),\n    lastDate,\n    level = 0.8,\n    metric,\n    now,\n    errorMessage,\n    status: blockStatus,\n    stepDays = 7,\n    target,\n    title,\n  } = props\n  const state = getBlockState(blockStatus, actuals)\n\n  const gradientId = useChartId()\n  const stepMs = stepDays * DAY\n  const deadlineSteps = (deadline.getTime() - lastDate.getTime()) / stepMs\n  const forecast = solveForTarget(actuals, target, {\n    level,\n    maxSteps: Math.max(52, deadlineSteps * 2),\n    resolution: 1 / stepDays,\n  })\n  const status = getDeadlineStatus(forecast, deadlineSteps)\n  const toDate = (steps: number) =>\n    new Date(lastDate.getTime() + Math.ceil(steps * stepDays) * DAY)\n  const expected = forecast.expected !== null ? toDate(forecast.expected) : null\n  const earliest = forecast.earliest !== null ? toDate(forecast.earliest) : null\n  const latest = forecast.latest !== null ? toDate(forecast.latest) : null\n\n  const current = actuals[actuals.length - 1] ?? 0\n  const trend = fitLinear(actuals).slope\n  const stepsLeft = Math.max(0, (deadline.getTime() - now.getTime()) / stepMs)\n  const needed = stepsLeft > 0 ? Math.max(0, (target - current) / stepsLeft) : 0\n  const unit = stepDays === 7 ? 'week' : `${stepDays} days`\n  const margin = expected\n    ? Math.round((deadline.getTime() - expected.getTime()) / DAY)\n    : null\n  const percent = `${level * 100}%`\n\n  const horizon = Math.max(\n    1,\n    Math.ceil(\n      Math.min(Math.max(deadlineSteps, forecast.expected ?? 0), deadlineSteps * 1.5 + 4) +\n        1,\n    ),\n  )\n  const last = actuals.length - 1\n  const rows = buildForecast(actuals, horizon, level).rows.map((row, index) => ({\n    ...row,\n    date: lastDate.getTime() + (index - last) * stepMs,\n  }))\n  const yAxis = getForecastAxis([\n    ...rows.flatMap((row) => [row.actual, row.forecast]),\n    target,\n  ])\n  const ticks = rows\n    .filter((_, index) => (rows.length - 1 - index) % 4 === 0)\n    .map((row) => row.date)\n\n  return (\n    <BlockStateProvider errorMessage={errorMessage} state={state}>\n      <Card>\n        <CardContent>\n          <section className='@container flex flex-col gap-4'>\n            <header className='flex items-start justify-between gap-4'>\n              <div className='flex flex-col gap-0.5'>\n                <h2 className='font-semibold tracking-tight'>{title}</h2>\n                <p className='text-muted-foreground text-sm'>\n                  {formatter(target)} {metric} by {formatDate(deadline, 'day')}.\n                </p>\n              </div>\n              <ForecastStatusLabel status={status} />\n            </header>\n            <dl className='flex flex-wrap items-start gap-x-10 gap-y-3 border-t pt-4'>\n              <div className='flex flex-col gap-1'>\n                <dt className='text-muted-foreground text-sm'>\n                  {forecast.reached && !state\n                    ? `Reached ${formatter(target)}`\n                    : `Projected to reach ${formatter(target)}`}\n                </dt>\n                <dd className='text-4xl font-light tracking-tight tabular-nums'>\n                  {state === 'loading' ? (\n                    <SkeletonText className='w-[4.5em]' />\n                  ) : state ? (\n                    <BlockStateText variant='short' />\n                  ) : forecast.reached ? (\n                    formatter(current)\n                  ) : expected ? (\n                    formatDate(expected, 'day')\n                  ) : (\n                    'Not in view'\n                  )}\n                </dd>\n                {!state && !forecast.reached && margin !== null && (\n                  <dd className='text-muted-foreground text-xs'>\n                    {margin === 0\n                      ? 'On the deadline'\n                      : `${Math.abs(margin)} ${Math.abs(margin) === 1 ? 'day' : 'days'} ${margin > 0 ? 'before' : 'after'} the deadline`}\n                  </dd>\n                )}\n              </div>\n              {state !== 'empty' && state !== 'error' && (\n                <div className='flex flex-col gap-1'>\n                  <dt className='text-muted-foreground text-sm'>Now</dt>\n                  <dd>\n                    <KPIValue className='text-2xl' value={current} format={formatter} />\n                  </dd>\n                  <dd className='text-muted-foreground text-xs tabular-nums'>\n                    <BlockReady className='text-xs'>\n                      {formatPercent(current / (target || 1), {\n                        maximumFractionDigits: 0,\n                      })}{' '}\n                      of the goal\n                    </BlockReady>\n                  </dd>\n                </div>\n              )}\n            </dl>\n            <ForecastLegend\n              items={[\n                { label: 'Actual', shape: 'line' },\n                { label: 'Forecast', shape: 'dashed' },\n                { label: `${percent} range`, shape: 'band' },\n                { label: 'Goal', shape: 'dotted' },\n              ]}\n            />\n            {state ? (\n              <ChartPlaceholder height={208} />\n            ) : (\n              <ChartPanelFigure className='h-52'>\n                <ResponsiveContainer width='100%' height='100%'>\n                  <ComposedChart\n                    aria-label={title}\n                    data={rows}\n                    margin={{ top: 20, right: 12, bottom: 0, left: 0 }}\n                  >\n                    <defs>\n                      <linearGradient id={gradientId} x1='0' y1='0' x2='0' y2='1'>\n                        <stop\n                          offset='0%'\n                          stopColor={forecastColors.actual}\n                          stopOpacity={0.3}\n                        />\n                        <stop\n                          offset='100%'\n                          stopColor={forecastColors.actual}\n                          stopOpacity={0}\n                        />\n                      </linearGradient>\n                    </defs>\n                    <CartesianGrid {...chartGridProps} />\n                    <XAxis\n                      {...chartAxisProps}\n                      dataKey='date'\n                      domain={['dataMin', 'dataMax']}\n                      interval='preserveStartEnd'\n                      minTickGap={24}\n                      scale='time'\n                      tickFormatter={(value: number) => formatDate(value, 'day')}\n                      ticks={ticks}\n                      type='number'\n                    />\n                    <YAxis\n                      {...chartAxisProps}\n                      domain={yAxis.domain}\n                      tickFormatter={(value: number) => formatCompact(value)}\n                      ticks={yAxis.ticks}\n                      width={chartValueAxisWidth}\n                    />\n                    <ReferenceLine\n                      {...chartReferenceProps}\n                      y={target}\n                      label={{\n                        ...chartReferenceLabel,\n                        position: 'insideTopLeft',\n                        value: `Goal ${formatter(target)}`,\n                      }}\n                    />\n                    <ReferenceLine\n                      x={deadline.getTime()}\n                      stroke={forecastColors.marker}\n                      strokeWidth={1}\n                      label={{\n                        fill: 'var(--color-foreground)',\n                        fontSize: 11,\n                        position: 'top',\n                        value: 'Deadline',\n                      }}\n                    />\n                    <Tooltip\n                      content={(tooltipProps) => (\n                        <ForecastTooltip\n                          {...tooltipProps}\n                          formatLabel={(label) => formatDate(Number(label), 'day')}\n                          level={level}\n                          valueFormatter={formatter}\n                        />\n                      )}\n                      cursor={chartLineCursor}\n                    />\n                    <Area\n                      activeDot={false}\n                      dataKey='band'\n                      fill={forecastColors.band}\n                      fillOpacity={1}\n                      name={`${percent} range`}\n                      stroke='none'\n                      type='linear'\n                    />\n                    <Line\n                      activeDot={chartActiveDot}\n                      dataKey='forecast'\n                      dot={false}\n                      name='Forecast'\n                      stroke={forecastColors.forecast}\n                      strokeDasharray={forecastDash.forecast}\n                      strokeWidth={2}\n                      type='linear'\n                    />\n                    <Area\n                      activeDot={chartActiveDot}\n                      dataKey='actual'\n                      dot={false}\n                      fill={`url(#${gradientId})`}\n                      fillOpacity={1}\n                      name='Actual'\n                      stroke={forecastColors.actual}\n                      strokeLinecap='round'\n                      strokeWidth={2}\n                      type='monotone'\n                    />\n                    {expected && !forecast.reached && (\n                      <ReferenceDot\n                        x={expected.getTime()}\n                        y={target}\n                        r={5}\n                        fill={forecastColors.forecast}\n                        stroke='var(--color-background)'\n                        strokeWidth={2}\n                      />\n                    )}\n                  </ComposedChart>\n                </ResponsiveContainer>\n              </ChartPanelFigure>\n            )}\n            {!forecast.reached && (\n              <BlockReady className='text-sm'>\n                <p className='text-sm text-pretty'>\n                  {`Growing by ${formatter(Math.max(0, trend))} a ${unit}. Hitting the deadline takes ${formatter(needed)} a ${unit}`}\n                  {earliest\n                    ? latest\n                      ? `, and the ${percent} range is ${formatDateRange({ end: latest, start: earliest })}.`\n                      : `, and the ${percent} range starts on ${formatDate(earliest, 'day')}.`\n                    : '.'}\n                </p>\n              </BlockReady>\n            )}\n            {!state && (\n              <ChartPanelTable\n                caption={`${title}: ${formatter(target)} ${metric} by ${formatDate(deadline, 'day')}. The forecast is a straight-line fit with a ${percent} range.`}\n                columns={[\n                  { key: 'label', label: 'Week ending' },\n                  { format: formatter, key: 'actual', label: 'Actual' },\n                  { format: formatter, key: 'forecast', label: 'Forecast' },\n                ]}\n                rows={rows.map((row, index) => ({\n                  actual: row.actual ?? '—',\n                  forecast: index > last ? (row.forecast ?? '—') : '—',\n                  label: formatDate(row.date, 'day'),\n                }))}\n              />\n            )}\n          </section>\n        </CardContent>\n      </Card>\n    </BlockStateProvider>\n  )\n}\n\nexport { Forecast2, exampleProps as forecast2ExampleProps, type Forecast2Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/forecast/forecast-02.tsx"
    }
  ],
  "meta": {
    "shows": "The running total heading for a goal line, with the forecast, its 80% range, the deadline and the date it gets there.",
    "size": "half",
    "usedWith": [
      "forecast-01",
      "goals-01",
      "progress-kpi-01"
    ],
    "component": "Forecast2",
    "props": "{ actuals?: number[]; deadline: Date; formatter?: (value: number) => string; lastDate: Date; level?: 0.8 | 0.9 | 0.95; metric: string; now: Date; stepDays?: number; target: number; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
