{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "fear-greed-index-chart",
  "title": "Fear & Greed Index Chart",
  "description": "Crypto Fear & Greed index history as a band-colored line with optional BTC price and volume.",
  "dependencies": [
    "lightweight-charts",
    "next-themes"
  ],
  "registryDependencies": [
    "button",
    "utils"
  ],
  "files": [
    {
      "path": "registry/voraui/fear-greed-index-chart/index.ts",
      "content": "export { FearGreedIndexChart, type FearGreedIndexChartProps } from \"./fear-greed-index-chart\";\nexport { FearGreedIndexChartSkeleton } from \"./components/skeleton\";\nexport type { FearGreedPoint, BtcDailyPoint } from \"./lib/fear-greed-bands\";\n",
      "type": "registry:lib",
      "target": "components/voraui/fear-greed-index-chart/index.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/fear-greed-index-chart.tsx",
      "content": "\"use client\";\n\nimport { useMemo, useState } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport type { UTCTimestamp } from \"lightweight-charts\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\nimport { FearGreedIndexChartSkeleton } from \"./components/skeleton\";\nimport { useFearGreedHistory } from \"./hooks/use-fear-greed-history\";\nimport { useBtcDaily } from \"./hooks/use-btc-daily\";\nimport { useIndexChart, type IndexPoint, type ValuePoint } from \"./hooks/use-index-chart\";\nimport {\n  clipToRange,\n  normalizeByTime,\n  toIndexLineData,\n  type BtcDailyPoint,\n  type FearGreedPoint,\n} from \"./lib/fear-greed-bands\";\nimport type { Preset } from \"./lib/chart-range\";\n\nexport interface FearGreedIndexChartProps {\n  /** Draw the BTC price line on the left scale. */\n  showPrice?: boolean;\n  /** Draw the BTC volume histogram along the bottom. */\n  showVolume?: boolean;\n  /** Provide your own index series to bypass the alternative.me fetcher. */\n  data?: FearGreedPoint[];\n  /** Provide your own BTC series to bypass the Binance fetcher. */\n  btcData?: BtcDailyPoint[];\n  className?: string;\n}\n\nconst PRESETS: Preset[] = [\"30D\", \"1Y\", \"ALL\"];\nconst INDEX_LEGEND_COLOR = \"#f0c929\";\n\n/** Crypto Fear & Greed index history as a band-colored line with optional BTC price and volume. */\nexport function FearGreedIndexChart({\n  showPrice = true,\n  showVolume = false,\n  data,\n  btcData,\n  className,\n}: FearGreedIndexChartProps) {\n  const { resolvedTheme } = useTheme();\n  const fetched = useFearGreedHistory({ enabled: data === undefined });\n  // Fetched history is already normalized by its parser.\n  const index = useMemo(\n    () => (data ? normalizeByTime(data) : (fetched.data ?? [])),\n    [data, fetched.data],\n  );\n  const loading = data === undefined && fetched.loading;\n  const error = data === undefined ? fetched.error : null;\n\n  const btcWanted = showPrice || showVolume;\n  const firstIndexTime = index[0]?.time;\n  const lastIndexTime = index[index.length - 1]?.time;\n  const fetchedBtc = useBtcDaily({\n    enabled: btcWanted && btcData === undefined,\n    from: firstIndexTime ?? null,\n  });\n  const btc = useMemo(() => {\n    if (!btcWanted || firstIndexTime === undefined || lastIndexTime === undefined) return [];\n    const source = btcData ?? fetchedBtc.data ?? [];\n    return clipToRange(normalizeByTime(source), firstIndexTime, lastIndexTime);\n  }, [btcWanted, btcData, fetchedBtc.data, firstIndexTime, lastIndexTime]);\n\n  const indexLine = useMemo<IndexPoint[]>(\n    () => toIndexLineData(index).map((p) => ({ ...p, time: p.time as UTCTimestamp })),\n    [index],\n  );\n  const priceLine = useMemo<ValuePoint[]>(\n    () =>\n      btc\n        .filter((p) => Number.isFinite(p.price) && p.price > 0)\n        .map((p) => ({ time: p.time as UTCTimestamp, value: p.price })),\n    [btc],\n  );\n  const volumeBars = useMemo<ValuePoint[]>(\n    () =>\n      btc\n        .filter((p) => Number.isFinite(p.volume) && p.volume >= 0)\n        .map((p) => ({ time: p.time as UTCTimestamp, value: p.volume })),\n    [btc],\n  );\n\n  const hasIndex = indexLine.length > 0;\n  const drawPrice = showPrice && priceLine.length > 0;\n  const drawVolume = showVolume && volumeBars.length > 0;\n  // Holding the price scale open while BTC loads keeps the plot from narrowing when it lands.\n  const reservePriceScale = drawPrice || (showPrice && fetchedBtc.loading);\n\n  const [preset, setPreset] = useState<Preset>(\"ALL\");\n  const {\n    containerRef,\n    failed: chartFailed,\n    refit,\n  } = useIndexChart({\n    indexLine,\n    priceLine,\n    volumeBars,\n    drawPrice,\n    drawVolume,\n    reservePriceScale,\n    theme: resolvedTheme,\n    preset,\n  });\n\n  if (loading) {\n    return <FearGreedIndexChartSkeleton className={className} />;\n  }\n\n  if (!hasIndex || chartFailed) {\n    return (\n      <div\n        role=\"alert\"\n        className={cn(\n          \"flex h-[220px] items-center justify-center rounded-md border border-dashed border-border text-xs text-muted-foreground\",\n          className,\n        )}\n      >\n        Fear &amp; Greed history is unavailable{error ? ` (${error})` : \"\"}.\n      </div>\n    );\n  }\n\n  return (\n    <div className={cn(\"@container space-y-2\", className)}>\n      <div className=\"flex flex-col items-start gap-2 @lg:flex-row @lg:items-center @lg:justify-between\">\n        <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n          <LegendEntry label=\"Fear & Greed Index\" dotStyle={{ backgroundColor: INDEX_LEGEND_COLOR }} />\n          {drawPrice && <LegendEntry label=\"Bitcoin Price\" dotClassName=\"bg-muted-foreground\" />}\n          {drawVolume && <LegendEntry label=\"Bitcoin Volume\" dotClassName=\"bg-muted-foreground/40\" />}\n        </div>\n        <div className=\"flex items-center gap-1\">\n          {PRESETS.map((p) => (\n            <Button\n              key={p}\n              size=\"sm\"\n              variant={preset === p ? \"default\" : \"outline\"}\n              className=\"h-7 px-2.5 text-[11px] font-medium\"\n              // Clicking the active preset snaps a zoomed or panned view back to it.\n              onClick={() => {\n                if (p === preset) refit();\n                else setPreset(p);\n              }}\n            >\n              {p}\n            </Button>\n          ))}\n        </div>\n      </div>\n      <div\n        ref={containerRef}\n        className={cn(\"relative h-[360px] w-full overflow-hidden sm:h-[420px]\", \"[&_canvas]:!touch-pan-y\")}\n      />\n    </div>\n  );\n}\n\nfunction LegendEntry({\n  label,\n  dotClassName,\n  dotStyle,\n}: {\n  label: string;\n  dotClassName?: string;\n  dotStyle?: { backgroundColor: string };\n}) {\n  return (\n    <div className=\"flex h-4 items-center gap-1.5 text-[11px] text-muted-foreground\">\n      <span className={cn(\"size-2 shrink-0 rounded-full\", dotClassName)} style={dotStyle} aria-hidden />\n      <span>{label}</span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/voraui/fear-greed-index-chart/fear-greed-index-chart.tsx"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/components/skeleton.tsx",
      "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface FearGreedIndexChartSkeletonProps {\n  className?: string;\n}\n\nconst PRESET_COUNT = 3;\nconst LEGEND_WIDTHS = [\"w-16\", \"w-20\"];\nconst VIEW_WIDTH = 400;\nconst VIEW_HEIGHT = 200;\nconst LINE_POINTS = 70;\nconst FEAR_COLOR = \"#c0392b\";\nconst GREED_COLOR = \"#2e7d32\";\nconst ZONE_OPACITY = 0.1;\n\n/** Deterministic wavy index line; Math.random would cause a hydration mismatch. */\nfunction indexLinePoints(): string {\n  const points: string[] = [];\n  for (let i = 0; i < LINE_POINTS; i++) {\n    const x = (i / (LINE_POINTS - 1)) * VIEW_WIDTH;\n    const y =\n      VIEW_HEIGHT / 2 +\n      Math.sin(i * 0.22) * 38 +\n      Math.sin(i * 0.67) * 14 +\n      Math.sin(i * 1.9) * 4;\n    points.push(`${x.toFixed(1)},${y.toFixed(1)}`);\n  }\n  return points.join(\" \");\n}\n\nexport function FearGreedIndexChartSkeleton({ className }: FearGreedIndexChartSkeletonProps) {\n  const linePoints = useMemo(() => indexLinePoints(), []);\n  const zoneHeight = VIEW_HEIGHT / 4;\n\n  return (\n    <div className={cn(\"@container space-y-2\", className)} role=\"status\">\n      <span className=\"sr-only\">Loading Fear &amp; Greed history</span>\n      <style href=\"voraui-fear-greed-index-chart-skeleton\" precedence=\"low\">{`\n        @keyframes voraui-fear-greed-index-chart-skeleton-shimmer {\n          from { transform: translateX(-100%); }\n          to { transform: translateX(100%); }\n        }\n        .voraui-fear-greed-index-chart-skeleton-shimmer::after {\n          content: \"\";\n          position: absolute;\n          inset: 0;\n          background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.25), transparent);\n          animation: voraui-fear-greed-index-chart-skeleton-shimmer 1.8s ease-in-out infinite;\n        }\n        @media (prefers-reduced-motion: reduce) {\n          .voraui-fear-greed-index-chart-skeleton-shimmer::after {\n            animation: none;\n          }\n        }\n      `}</style>\n      <div className=\"flex flex-col items-start gap-2 @lg:flex-row @lg:items-center @lg:justify-between\">\n        <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n          {LEGEND_WIDTHS.map((width) => (\n            <div key={width} className=\"flex h-4 items-center gap-1.5\">\n              <div className=\"size-2 rounded-full bg-muted\" />\n              <div className={cn(\"h-3 rounded bg-muted\", width)} />\n            </div>\n          ))}\n        </div>\n        <div className=\"flex items-center gap-1\">\n          {Array.from({ length: PRESET_COUNT }, (_, i) => (\n            <div key={i} className=\"h-7 w-10 rounded-md bg-muted\" />\n          ))}\n        </div>\n      </div>\n      <div className=\"voraui-fear-greed-index-chart-skeleton-shimmer relative h-[360px] w-full overflow-hidden rounded-md bg-muted/30 sm:h-[420px]\">\n        <svg\n          viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}\n          preserveAspectRatio=\"none\"\n          className=\"absolute inset-0 h-full w-full\"\n          aria-hidden=\"true\"\n        >\n          <rect x={0} y={0} width={VIEW_WIDTH} height={zoneHeight} fill={GREED_COLOR} opacity={ZONE_OPACITY} />\n          <rect\n            x={0}\n            y={VIEW_HEIGHT - zoneHeight}\n            width={VIEW_WIDTH}\n            height={zoneHeight}\n            fill={FEAR_COLOR}\n            opacity={ZONE_OPACITY}\n          />\n          <polyline\n            points={linePoints}\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={2}\n            strokeLinejoin=\"round\"\n            strokeLinecap=\"round\"\n            vectorEffect=\"non-scaling-stroke\"\n            className=\"text-muted-foreground/55\"\n          />\n        </svg>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/voraui/fear-greed-index-chart/components/skeleton.tsx"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/hooks/use-fear-greed-history.ts",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { isPresent, normalizeByTime, type FearGreedPoint } from \"../lib/fear-greed-bands\";\n\nexport type { FearGreedPoint };\n\nconst FNG_HISTORY_URL = \"https://api.alternative.me/fng/?limit=0\";\n\ntype FngRow = { value?: unknown; timestamp?: unknown } | null;\n\n/** Parse the alternative.me history payload (newest first) into ascending points. */\nexport function parseFngHistory(raw: unknown): FearGreedPoint[] {\n  const rows = (raw as { data?: unknown } | null)?.data;\n  if (!Array.isArray(rows)) return [];\n  const points: FearGreedPoint[] = [];\n  for (const row of rows as FngRow[]) {\n    if (!isPresent(row?.value) || !isPresent(row?.timestamp)) continue;\n    const value = Number(row?.value);\n    const time = Number(row?.timestamp);\n    if (Number.isFinite(value) && Number.isFinite(time)) points.push({ time, value });\n  }\n  return normalizeByTime(points);\n}\n\ntype Result = { data: FearGreedPoint[] | null; error: string | null };\n\n/** Load the full index history. Idle while disabled; `loading` holds until a fetch settles. */\nexport function useFearGreedHistory(options: { enabled?: boolean } = {}) {\n  const { enabled = true } = options;\n  const [result, setResult] = useState<Result | null>(null);\n\n  useEffect(() => {\n    if (!enabled) return;\n    const controller = new AbortController();\n\n    const load = async () => {\n      try {\n        const res = await fetch(FNG_HISTORY_URL, { signal: controller.signal });\n        if (!res.ok) throw new Error(`Fear & Greed request failed: ${res.status}`);\n        const json: unknown = await res.json();\n        if (controller.signal.aborted) return;\n        setResult({ data: parseFngHistory(json), error: null });\n      } catch (err) {\n        if (controller.signal.aborted) return;\n        setResult({\n          data: null,\n          error: err instanceof Error ? err.message : \"Fear & Greed request failed\",\n        });\n      }\n    };\n\n    load();\n\n    return () => controller.abort();\n  }, [enabled]);\n\n  return {\n    data: result?.data ?? null,\n    loading: enabled && result === null,\n    error: result?.error ?? null,\n  };\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/fear-greed-index-chart/hooks/use-fear-greed-history.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/hooks/use-btc-daily.ts",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { isPresent, type BtcDailyPoint } from \"../lib/fear-greed-bands\";\n\nexport type { BtcDailyPoint };\n\nconst BINANCE_KLINES_URL = \"https://api.binance.com/api/v3/klines\";\nconst DAY_MS = 86_400_000;\nconst PAGE_LIMIT = 1000;\n\n/** Parse a Binance klines batch into daily points (open time, close price, quote volume). */\nexport function parseDailyKlines(batch: unknown): BtcDailyPoint[] {\n  if (!Array.isArray(batch)) return [];\n  const points: BtcDailyPoint[] = [];\n  for (const k of batch) {\n    if (!Array.isArray(k) || !isPresent(k[0]) || !isPresent(k[4]) || !isPresent(k[7])) continue;\n    const openMs = Number(k[0]);\n    const price = Number(k[4]);\n    const volume = Number(k[7]);\n    if (Number.isFinite(openMs) && Number.isFinite(price) && Number.isFinite(volume)) {\n      points.push({ time: Math.floor(openMs / 1000), price, volume });\n    }\n  }\n  return points;\n}\n\n/** Fetch BTCUSDT daily klines from `fromSeconds` onward, paginating forward. */\nexport async function fetchBtcDaily(\n  fromSeconds: number,\n  signal?: AbortSignal,\n): Promise<BtcDailyPoint[]> {\n  const out: BtcDailyPoint[] = [];\n  let cursorMs = fromSeconds * 1000;\n  // Hard cap on iterations; 20 batches of 1000 daily candles is ~54 years.\n  for (let i = 0; i < 20; i++) {\n    const params = new URLSearchParams({\n      symbol: \"BTCUSDT\",\n      interval: \"1d\",\n      startTime: String(cursorMs),\n      limit: String(PAGE_LIMIT),\n    });\n    const res = await fetch(`${BINANCE_KLINES_URL}?${params}`, { signal });\n    if (!res.ok) throw new Error(`Binance klines request failed: ${res.status}`);\n    const batch: unknown = await res.json();\n    if (!Array.isArray(batch) || batch.length === 0) break;\n    out.push(...parseDailyKlines(batch));\n    if (batch.length < PAGE_LIMIT) break;\n    const last: unknown = batch[batch.length - 1];\n    const lastOpenMs = Array.isArray(last) && isPresent(last[0]) ? Number(last[0]) : NaN;\n    if (!Number.isFinite(lastOpenMs)) break;\n    cursorMs = lastOpenMs + DAY_MS;\n  }\n  return out;\n}\n\ntype Result = { from: number; data: BtcDailyPoint[] | null };\n\n/**\n * Load BTC daily price and volume from `from` (unix seconds). Idle while disabled or `from` is\n * null; a failed request settles with no data, so the chart falls back to the index alone.\n */\nexport function useBtcDaily(options: { enabled: boolean; from: number | null }) {\n  const { enabled, from } = options;\n  const [result, setResult] = useState<Result | null>(null);\n  const active = enabled && from !== null;\n\n  useEffect(() => {\n    if (!enabled || from === null) return;\n    const controller = new AbortController();\n\n    const load = async () => {\n      try {\n        const data = await fetchBtcDaily(from, controller.signal);\n        if (controller.signal.aborted) return;\n        setResult({ from, data });\n      } catch {\n        if (!controller.signal.aborted) setResult({ from, data: null });\n      }\n    };\n\n    load();\n\n    return () => controller.abort();\n  }, [enabled, from]);\n\n  const current = active && result?.from === from ? result : null;\n  return { data: current?.data ?? null, loading: active && current === null };\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/fear-greed-index-chart/hooks/use-btc-daily.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/hooks/use-index-chart.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type {\n  IChartApi,\n  ISeriesApi,\n  LogicalRange,\n  Time,\n  UTCTimestamp,\n} from \"lightweight-charts\";\nimport { FearGreedZonesPrimitive } from \"../lib/zones-primitive\";\nimport { createIndexTooltip, type IndexTooltip } from \"../lib/index-tooltip\";\nimport {\n  DENSE_BAR_SPACING,\n  INDEX_SERIES_OPTIONS,\n  PRICE_SCALE_MIN_WIDTH,\n  VOLUME_SCALE_ID,\n  VOLUME_SCALE_MARGINS,\n  chartOptions,\n  chartPalette,\n  indexPriceFormat,\n  priceScaleMargins,\n  priceSeriesOptions,\n  themeOptions,\n  volumeSeriesOptions,\n} from \"../lib/chart-options\";\nimport {\n  DAY_SECONDS,\n  PRESET_DAYS,\n  clampLogicalRange,\n  distinctTimeCount,\n  labelGutterPixels,\n  minBarSpacingFor,\n  presetLogicalRange,\n  tickDetailFor,\n  tickLabelFor,\n  type Preset,\n  type TickDetail,\n} from \"../lib/chart-range\";\n\nexport type IndexPoint = { time: UTCTimestamp; value: number; color: string };\nexport type ValuePoint = { time: UTCTimestamp; value: number };\ntype LightweightCharts = typeof import(\"lightweight-charts\");\n\nexport interface UseIndexChartOptions {\n  indexLine: IndexPoint[];\n  priceLine: ValuePoint[];\n  volumeBars: ValuePoint[];\n  drawPrice: boolean;\n  drawVolume: boolean;\n  /** Keep the left price scale open (e.g. while BTC loads) so the plot width stays put. */\n  reservePriceScale: boolean;\n  theme: string | undefined;\n  preset: Preset;\n}\n\n/**\n * Owns the lightweight-charts instance: mounts once when the index has data, then applies data,\n * BTC layers, theme, and presets in place so the view and zoom survive every update.\n */\nexport function useIndexChart({\n  indexLine,\n  priceLine,\n  volumeBars,\n  drawPrice,\n  drawVolume,\n  reservePriceScale,\n  theme,\n  preset,\n}: UseIndexChartOptions) {\n  const hasIndex = indexLine.length > 0;\n\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  const lwcRef = useRef<LightweightCharts | null>(null);\n  const chartRef = useRef<IChartApi | null>(null);\n  const indexSeriesRef = useRef<ISeriesApi<\"Line\", Time> | null>(null);\n  const priceSeriesRef = useRef<ISeriesApi<\"Line\", Time> | null>(null);\n  const volumeSeriesRef = useRef<ISeriesApi<\"Histogram\", Time> | null>(null);\n  const primitiveRef = useRef<FearGreedZonesPrimitive | null>(null);\n\n  const [failed, setFailed] = useState(false);\n\n  const palette = useMemo(() => chartPalette(theme), [theme]);\n  // Latest props for the chart callbacks, which outlive the render that created them.\n  const latestProps = {\n    indexLine,\n    priceLine,\n    volumeBars,\n    drawPrice,\n    drawVolume,\n    reservePriceScale,\n    preset,\n    palette,\n  };\n  const latest = useRef(latestProps);\n  // Declared first so every effect below reads this render's props.\n  useEffect(() => {\n    latest.current = latestProps;\n  });\n\n  // Time bounds the visible range was last fitted to; unchanged bounds keep the user's zoom.\n  const rangeKeyRef = useRef<string | null>(null);\n  // Pixels reserved right of the latest day for the band labels; 0 while they are hidden.\n  const gutterRef = useRef(0);\n\n  // Zoom-out stops where every day plus the label gutter fits, like fixed edges would.\n  const applyZoomLimit = useCallback(() => {\n    const chart = chartRef.current;\n    if (!chart) return;\n    const timeScale = chart.timeScale();\n    const bars = distinctTimeCount([\n      latest.current.indexLine,\n      latest.current.priceLine,\n      latest.current.volumeBars,\n    ]);\n    timeScale.applyOptions({\n      minBarSpacing: minBarSpacingFor(timeScale.width(), gutterRef.current, bars),\n    });\n  }, []);\n\n  const applyVisibleRange = useCallback(() => {\n    const chart = chartRef.current;\n    const points = latest.current.indexLine;\n    if (!chart || points.length === 0) return;\n    const timeScale = chart.timeScale();\n\n    if (latest.current.preset === \"ALL\") {\n      timeScale.fitContent();\n      return;\n    }\n\n    const first = points[0].time as number;\n    const last = points[points.length - 1].time as number;\n    const from = Math.max(first, last - PRESET_DAYS[latest.current.preset] * DAY_SECONDS);\n    const fromIndex = timeScale.timeToIndex(from as UTCTimestamp, true);\n    const toIndex = timeScale.timeToIndex(last as UTCTimestamp, true);\n    if (fromIndex === null || toIndex === null) return;\n    timeScale.setVisibleLogicalRange(\n      presetLogicalRange(fromIndex, toIndex, timeScale.width(), gutterRef.current),\n    );\n  }, []);\n\n  const applyLatestData = useCallback(() => {\n    const indexSeries = indexSeriesRef.current;\n    const points = latest.current.indexLine;\n    if (!chartRef.current || !indexSeries || points.length === 0) return;\n\n    indexSeries.setData(points);\n    // The series color drives the last-value label, so it follows the latest band.\n    const latestPoint = points[points.length - 1];\n    indexSeries.applyOptions({\n      color: latestPoint.color,\n      priceFormat: indexPriceFormat(latestPoint.value),\n    });\n    priceSeriesRef.current?.setData(latest.current.priceLine);\n    volumeSeriesRef.current?.setData(latest.current.volumeBars);\n\n    applyZoomLimit();\n    const rangeKey = `${points[0].time}:${points[points.length - 1].time}`;\n    if (rangeKeyRef.current !== rangeKey) {\n      rangeKeyRef.current = rangeKey;\n      applyVisibleRange();\n    }\n    primitiveRef.current?.requestUpdate();\n  }, [applyVisibleRange, applyZoomLimit]);\n\n  // Adds or removes the BTC layers on the live chart so the index view and zoom survive.\n  const syncLayers = useCallback(() => {\n    const lwc = lwcRef.current;\n    const chart = chartRef.current;\n    if (!lwc || !chart) return;\n    const palette = latest.current.palette;\n\n    if (latest.current.drawVolume && !volumeSeriesRef.current) {\n      const volumeSeries = chart.addSeries(lwc.HistogramSeries, volumeSeriesOptions(palette));\n      chart.priceScale(VOLUME_SCALE_ID).applyOptions({ scaleMargins: VOLUME_SCALE_MARGINS });\n      volumeSeries.setData(latest.current.volumeBars);\n      volumeSeriesRef.current = volumeSeries;\n    } else if (!latest.current.drawVolume && volumeSeriesRef.current) {\n      chart.removeSeries(volumeSeriesRef.current);\n      volumeSeriesRef.current = null;\n    }\n\n    if (latest.current.drawPrice && !priceSeriesRef.current) {\n      const priceSeries = chart.addSeries(lwc.LineSeries, priceSeriesOptions(palette));\n      priceSeries.setData(latest.current.priceLine);\n      priceSeriesRef.current = priceSeries;\n    } else if (!latest.current.drawPrice && priceSeriesRef.current) {\n      chart.removeSeries(priceSeriesRef.current);\n      priceSeriesRef.current = null;\n    }\n\n    // Paint order: volume, then price, then the index on top.\n    volumeSeriesRef.current?.setSeriesOrder(0);\n    priceSeriesRef.current?.setSeriesOrder(volumeSeriesRef.current ? 1 : 0);\n    chart.applyOptions({\n      leftPriceScale: {\n        visible: latest.current.reservePriceScale,\n        minimumWidth: PRICE_SCALE_MIN_WIDTH,\n        scaleMargins: priceScaleMargins(latest.current.drawVolume),\n      },\n    });\n  }, []);\n\n  useEffect(() => applyLatestData(), [indexLine, priceLine, volumeBars, applyLatestData]);\n\n  useEffect(() => syncLayers(), [drawPrice, drawVolume, reservePriceScale, syncLayers]);\n\n  useEffect(() => {\n    const chart = chartRef.current;\n    if (!chart) return;\n    chart.applyOptions(themeOptions(palette));\n    priceSeriesRef.current?.applyOptions({ color: palette.price });\n    volumeSeriesRef.current?.applyOptions({ color: palette.volume });\n    primitiveRef.current?.setColors(palette.label, palette.halo);\n  }, [palette]);\n\n  useEffect(() => applyVisibleRange(), [preset, applyVisibleRange]);\n\n  // Mount once; theme, layers, and data are applied in place by the effects above.\n  useEffect(() => {\n    if (!hasIndex) return;\n\n    let disposed = false;\n    let ro: ResizeObserver | null = null;\n    let chartInitialized = false;\n    let tooltip: IndexTooltip | null = null;\n\n    const initChart = async (container: HTMLDivElement) => {\n      const lwc = await import(\"lightweight-charts\");\n      if (disposed) return;\n      lwcRef.current = lwc;\n      const palette = latest.current.palette;\n\n      const chart = lwc.createChart(\n        container,\n        chartOptions(\n          palette,\n          container.clientWidth,\n          container.clientHeight,\n          // The canvas does not inherit CSS, so the axis labels are handed the app's font.\n          getComputedStyle(container).fontFamily,\n        ),\n      );\n      chartRef.current = chart;\n      const timeScale = chart.timeScale();\n\n      const indexSeries = chart.addSeries(lwc.LineSeries, INDEX_SERIES_OPTIONS);\n      indexSeriesRef.current = indexSeries;\n\n      const primitive = new FearGreedZonesPrimitive({\n        labelColor: palette.label,\n        haloColor: palette.halo,\n      });\n      primitiveRef.current = primitive;\n      indexSeries.attachPrimitive(primitive);\n\n      // Fires on the first layout too, so the label column is decided from the real plot width.\n      timeScale.subscribeSizeChange((plotWidth) => {\n        const gutter = labelGutterPixels(plotWidth);\n        if (gutter !== gutterRef.current) {\n          gutterRef.current = gutter;\n          primitive.setLabelsVisible(gutter > 0);\n          timeScale.applyOptions({ rightOffsetPixels: gutter });\n          applyZoomLimit();\n          applyVisibleRange();\n          return;\n        }\n        applyZoomLimit();\n      });\n\n      let tickDetail: TickDetail | null = null;\n      timeScale.subscribeVisibleLogicalRangeChange((range) => {\n        const barSpacing = timeScale.options().barSpacing;\n        // Setting the formatter also drops the library's cached labels for the old zoom level.\n        const detail = tickDetailFor(barSpacing);\n        if (detail !== tickDetail) {\n          tickDetail = detail;\n          chart.applyOptions({\n            timeScale: { tickMarkFormatter: (_time: Time, type: number) => tickLabelFor(type, detail) },\n          });\n        }\n\n        // Thin the index line when days are packed tighter than its stroke.\n        const lineWidth = barSpacing < DENSE_BAR_SPACING ? 1 : 2;\n        if (indexSeries.options().lineWidth !== lineWidth) indexSeries.applyOptions({ lineWidth });\n\n        // Without fixRightEdge, panning is bounded here: never past the label column.\n        const points = latest.current.indexLine;\n        if (!range || points.length === 0) return;\n        const lastIndex = timeScale.timeToIndex(points[points.length - 1].time, true);\n        if (lastIndex === null) return;\n        const clamped = clampLogicalRange(range, lastIndex + 1, gutterRef.current / barSpacing);\n        // The clamp's tolerance, not a guard here, is what stops this from re-triggering itself.\n        if (clamped !== range) timeScale.setVisibleLogicalRange(clamped as LogicalRange);\n      });\n\n      syncLayers();\n      applyLatestData();\n\n      tooltip = createIndexTooltip(\n        container,\n        () => ({\n          index: indexSeriesRef.current,\n          price: priceSeriesRef.current,\n          volume: volumeSeriesRef.current,\n        }),\n        // 0 while the left scale is hidden (index only), or shown but not laid out yet: the\n        // library throws for that one frame instead of reporting 0.\n        () => {\n          try {\n            return chart.priceScale(\"left\").width();\n          } catch {\n            return 0;\n          }\n        },\n      );\n      chart.subscribeCrosshairMove(tooltip.onCrosshairMove);\n    };\n\n    if (containerRef.current) {\n      ro = new ResizeObserver((entries) => {\n        const rect = entries[0].contentRect;\n        if (rect.width > 0 && rect.height > 0 && !chartInitialized) {\n          chartInitialized = true;\n          initChart(containerRef.current!).catch(() => {\n            if (!disposed) setFailed(true);\n          });\n        } else if (chartInitialized && chartRef.current) {\n          chartRef.current.applyOptions({ width: rect.width, height: rect.height });\n        }\n      });\n      ro.observe(containerRef.current);\n    }\n\n    return () => {\n      disposed = true;\n      if (ro) ro.disconnect();\n      tooltip?.dispose();\n      // remove() also drops the time scale subscriptions made above.\n      chartRef.current?.remove();\n      chartRef.current = null;\n      indexSeriesRef.current = null;\n      priceSeriesRef.current = null;\n      volumeSeriesRef.current = null;\n      primitiveRef.current = null;\n      rangeKeyRef.current = null;\n      gutterRef.current = 0;\n    };\n  }, [applyLatestData, applyVisibleRange, applyZoomLimit, syncLayers, hasIndex]);\n\n  return { containerRef, failed, refit: applyVisibleRange };\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/fear-greed-index-chart/hooks/use-index-chart.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/lib/fear-greed-bands.ts",
      "content": "export interface FearGreedBand {\n  key: string;\n  label: string;\n  min: number;\n  max: number;\n  color: string;\n}\n\nexport interface FearGreedPoint {\n  /** Unix seconds. */\n  time: number;\n  /** Index value, 0-100. */\n  value: number;\n}\n\nexport interface BtcDailyPoint {\n  /** Unix seconds. */\n  time: number;\n  price: number;\n  volume: number;\n}\n\n/** Sentiment bands, ascending, mirroring the alternative.me thresholds. */\nexport const FEAR_GREED_BANDS: FearGreedBand[] = [\n  { key: \"extreme-fear\", label: \"Extreme Fear\", min: 0, max: 24, color: \"#c0392b\" },\n  { key: \"fear\", label: \"Fear\", min: 25, max: 44, color: \"#e0672b\" },\n  { key: \"neutral\", label: \"Neutral\", min: 45, max: 55, color: \"#f0c929\" },\n  { key: \"greed\", label: \"Greed\", min: 56, max: 75, color: \"#4caf50\" },\n  { key: \"extreme-greed\", label: \"Extreme Greed\", min: 76, max: 100, color: \"#2e7d32\" },\n];\n\n/** Returns the band for a value, rounding to an integer and clamping to 0-100. */\nexport function findFearGreedBand(value: number): FearGreedBand {\n  const v = Math.min(100, Math.max(0, Math.round(value)));\n  return (\n    FEAR_GREED_BANDS.find((band) => v >= band.min && v <= band.max) ??\n    FEAR_GREED_BANDS[0]\n  );\n}\n\n/** False for the null, undefined and \"\" fields that `Number()` would otherwise turn into 0. */\nexport const isPresent = (value: unknown) => value !== null && value !== undefined && value !== \"\";\n\n/** Sorts ascending by time, keeps the last duplicate, and drops non-positive or non-finite times. */\nexport function normalizeByTime<T extends { time: number }>(points: readonly T[]): T[] {\n  const byTime = new Map<number, T>();\n  for (const point of points) {\n    if (Number.isFinite(point.time) && point.time > 0) byTime.set(point.time, point);\n  }\n  return [...byTime.values()].sort((a, b) => a.time - b.time);\n}\n\n/** Maps index points to line data colored by band, dropping non-finite values. */\nexport function toIndexLineData(\n  points: FearGreedPoint[],\n): { time: number; value: number; color: string }[] {\n  return points\n    .filter((point) => Number.isFinite(point.value))\n    .map((point) => ({\n      time: point.time,\n      value: point.value,\n      color: findFearGreedBand(point.value).color,\n    }));\n}\n\n/** Keeps points whose time is within the inclusive range. */\nexport function clipToRange<T extends { time: number }>(\n  points: T[],\n  from: number,\n  to: number,\n): T[] {\n  return points.filter((point) => point.time >= from && point.time <= to);\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/fear-greed-index-chart/lib/fear-greed-bands.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/lib/zones-primitive.ts",
      "content": "import type {\n  IPrimitivePaneRenderer,\n  IPrimitivePaneView,\n  ISeriesApi,\n  ISeriesPrimitive,\n  SeriesAttachedParameter,\n  SeriesType,\n  Time,\n} from \"lightweight-charts\";\nimport { FEAR_GREED_BANDS } from \"./fear-greed-bands\";\n\n// Structural subset of fancy-canvas's CanvasRenderingTarget2D (not a direct dependency).\ninterface MediaScope {\n  context: CanvasRenderingContext2D;\n  mediaSize: { width: number; height: number };\n}\ninterface CanvasRenderingTarget2D {\n  useMediaCoordinateSpace<T>(fn: (scope: MediaScope) => T): T;\n}\n\nconst ZONES = [\n  { from: 0, to: 25, color: \"#c0392b\" },\n  { from: 75, to: 100, color: \"#2e7d32\" },\n];\nconst ZONE_OPACITY = 0.1;\nconst LABEL_FONT_SIZE = 11;\nconst LABEL_INSET = 8;\nconst LABEL_HALO_WIDTH = 3;\n\nexport interface FearGreedZonesOptions {\n  labelColor: string;\n  /** Outline drawn around each label so it stays legible over the lines. */\n  haloColor: string;\n}\n\nclass FearGreedZonesRenderer implements IPrimitivePaneRenderer {\n  constructor(private series: ISeriesApi<SeriesType, Time> | null) {}\n\n  draw(target: CanvasRenderingTarget2D): void {\n    const series = this.series;\n    if (!series) return;\n\n    target.useMediaCoordinateSpace(({ context: ctx, mediaSize }) => {\n      const width = mediaSize.width;\n      if (width <= 0) return;\n\n      ctx.save();\n      ctx.globalAlpha = ZONE_OPACITY;\n      for (const zone of ZONES) {\n        const top = series.priceToCoordinate(zone.to);\n        const bottom = series.priceToCoordinate(zone.from);\n        if (top === null || bottom === null) continue;\n        ctx.fillStyle = zone.color;\n        ctx.fillRect(0, top, width, bottom - top);\n      }\n      ctx.restore();\n    });\n  }\n}\n\nclass FearGreedLabelsRenderer implements IPrimitivePaneRenderer {\n  constructor(\n    private series: ISeriesApi<SeriesType, Time> | null,\n    private labelColor: string,\n    private haloColor: string,\n    private fontFamily: string,\n  ) {}\n\n  draw(target: CanvasRenderingTarget2D): void {\n    const series = this.series;\n    if (!series) return;\n\n    target.useMediaCoordinateSpace(({ context: ctx, mediaSize }) => {\n      const width = mediaSize.width;\n      if (width <= 0) return;\n\n      ctx.save();\n      ctx.font = `${LABEL_FONT_SIZE}px ${this.fontFamily}`;\n      ctx.textAlign = \"right\";\n      ctx.textBaseline = \"middle\";\n      ctx.lineJoin = \"round\";\n      ctx.lineWidth = LABEL_HALO_WIDTH;\n      ctx.strokeStyle = this.haloColor;\n      ctx.fillStyle = this.labelColor;\n      for (const band of FEAR_GREED_BANDS) {\n        const y = series.priceToCoordinate((band.min + band.max) / 2);\n        if (y === null) continue;\n        ctx.strokeText(band.label, width - LABEL_INSET, y);\n        ctx.fillText(band.label, width - LABEL_INSET, y);\n      }\n      ctx.restore();\n    });\n  }\n}\n\nclass FearGreedZonesPaneView implements IPrimitivePaneView {\n  constructor(private primitive: FearGreedZonesPrimitive) {}\n\n  zOrder() {\n    return \"bottom\" as const;\n  }\n\n  renderer(): IPrimitivePaneRenderer | null {\n    return new FearGreedZonesRenderer(this.primitive.series);\n  }\n}\n\nclass FearGreedLabelsPaneView implements IPrimitivePaneView {\n  constructor(private primitive: FearGreedZonesPrimitive) {}\n\n  zOrder() {\n    return \"top\" as const;\n  }\n\n  renderer(): IPrimitivePaneRenderer | null {\n    const { series, labelColor, haloColor, labelsVisible, fontFamily } = this.primitive;\n    if (!labelsVisible) return null;\n    return new FearGreedLabelsRenderer(series, labelColor, haloColor, fontFamily);\n  }\n}\n\n/** Series primitive painting the fear (0-25) and greed (75-100) tints plus optional band labels. */\nexport class FearGreedZonesPrimitive implements ISeriesPrimitive<Time> {\n  series: ISeriesApi<SeriesType, Time> | null = null;\n  labelColor: string;\n  haloColor: string;\n  /** Off until the chart reserves a label column; narrow plots never show the labels. */\n  labelsVisible = false;\n  /** The chart's own font, so the band labels match the axis labels. */\n  fontFamily = \"sans-serif\";\n\n  private paneViewsList: readonly IPrimitivePaneView[];\n  private requestChartUpdate: (() => void) | null = null;\n\n  constructor(options: FearGreedZonesOptions) {\n    this.labelColor = options.labelColor;\n    this.haloColor = options.haloColor;\n    this.paneViewsList = [new FearGreedZonesPaneView(this), new FearGreedLabelsPaneView(this)];\n  }\n\n  setColors(labelColor: string, haloColor: string): void {\n    this.labelColor = labelColor;\n    this.haloColor = haloColor;\n    this.requestUpdate();\n  }\n\n  setLabelsVisible(visible: boolean): void {\n    this.labelsVisible = visible;\n    this.requestUpdate();\n  }\n\n  requestUpdate(): void {\n    this.requestChartUpdate?.();\n  }\n\n  attached(param: SeriesAttachedParameter<Time, SeriesType>): void {\n    this.series = param.series;\n    this.fontFamily = param.chart.options().layout.fontFamily;\n    this.requestChartUpdate = param.requestUpdate;\n  }\n\n  detached(): void {\n    this.series = null;\n    this.requestChartUpdate = null;\n  }\n\n  paneViews(): readonly IPrimitivePaneView[] {\n    return this.paneViewsList;\n  }\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/fear-greed-index-chart/lib/zones-primitive.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/lib/index-tooltip.ts",
      "content": "import type { ISeriesApi, MouseEventParams, Time } from \"lightweight-charts\";\nimport { findFearGreedBand, type FearGreedBand } from \"./fear-greed-bands\";\n\n/** Compact USD for tooltip rows, e.g. \"$64.00K\". */\nexport function compactUsd(n: number): string {\n  if (!Number.isFinite(n) || n === 0) return \"-\";\n  if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;\n  if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;\n  if (n >= 1e3) return `$${(n / 1e3).toFixed(2)}K`;\n  if (n >= 1) return `$${n.toFixed(2)}`;\n  return `$${n.toFixed(4)}`;\n}\n\n/** Compact USD for axis ticks: drops trailing \".00\" so the price scale stays narrow; blank below 0. */\nexport function compactUsdTick(n: number): string {\n  if (!Number.isFinite(n)) return \"-\";\n  // The scale's bottom margin reaches $0 and under, below the index floor; prices never do.\n  if (n <= 0) return \"\";\n  const trim = (v: number) => v.toFixed(2).replace(/\\.?0+$/, \"\");\n  if (n >= 1e9) return `$${trim(n / 1e9)}B`;\n  if (n >= 1e6) return `$${trim(n / 1e6)}M`;\n  if (n >= 1e3) return `$${trim(n / 1e3)}K`;\n  if (n >= 1) return `$${trim(n)}`;\n  return `$${n.toFixed(4).replace(/0+$/, \"\")}`;\n}\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\");\n}\n\n/** Pure renderer for the tooltip body; exported for tests. */\nexport function renderIndexTooltipHtml(\n  dateStr: string,\n  value: number,\n  band: FearGreedBand,\n  btc?: { price?: number; volume?: number },\n): string {\n  const row = (label: string, text: string) =>\n    `<div class=\"mt-1 flex items-center justify-between gap-4\">\n       <span class=\"text-zinc-400\">${label}</span>\n       <span class=\"text-zinc-200 tabular-nums\">${text}</span>\n     </div>`;\n  return `\n    <div class=\"text-zinc-400\">${escapeHtml(dateStr)}</div>\n    <div class=\"mt-1 flex items-center gap-1.5\">\n      <span class=\"h-2 w-2 shrink-0 rounded-full\" style=\"background-color:${band.color}\"></span>\n      <span class=\"font-semibold text-white tabular-nums\">${Math.round(value)}</span>\n      <span class=\"text-[11px] text-zinc-300\">${escapeHtml(band.label)}</span>\n    </div>\n    ${btc?.price !== undefined ? row(\"BTC\", compactUsd(btc.price)) : \"\"}\n    ${btc?.volume !== undefined ? row(\"Vol\", compactUsd(btc.volume)) : \"\"}\n  `;\n}\n\nconst TOOLTIP_OFFSET = 12;\nconst TOOLTIP_EDGE_INSET = 4;\n\ninterface TooltipBox {\n  width: number;\n  height: number;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n  if (max < min) return min;\n  return Math.min(Math.max(value, min), max);\n}\n\n/**\n * Places the tooltip right of and above a pane-relative cursor, in container coordinates,\n * flipping left or below at the edges and never leaving the container.\n */\nexport function getIndexTooltipPosition(\n  point: { x: number; y: number },\n  paneLeft: number,\n  tooltip: TooltipBox,\n  container: TooltipBox,\n): { left: number; top: number } {\n  const x = paneLeft + point.x;\n  let left = x + TOOLTIP_OFFSET;\n  if (left + tooltip.width > container.width - TOOLTIP_EDGE_INSET) {\n    left = x - tooltip.width - TOOLTIP_OFFSET;\n  }\n  let top = point.y - tooltip.height - TOOLTIP_OFFSET;\n  if (top < TOOLTIP_EDGE_INSET) top = point.y + TOOLTIP_OFFSET;\n  return {\n    left: clamp(left, TOOLTIP_EDGE_INSET, container.width - tooltip.width - TOOLTIP_EDGE_INSET),\n    top: clamp(top, TOOLTIP_EDGE_INSET, container.height - tooltip.height - TOOLTIP_EDGE_INSET),\n  };\n}\n\nexport interface IndexTooltipSeries {\n  index: ISeriesApi<\"Line\", Time> | null;\n  price: ISeriesApi<\"Line\", Time> | null;\n  volume: ISeriesApi<\"Histogram\", Time> | null;\n}\n\nexport interface IndexTooltip {\n  /** Pass to chart.subscribeCrosshairMove. */\n  onCrosshairMove: (param: MouseEventParams<Time>) => void;\n  dispose: () => void;\n}\n\n/**\n * Floating tooltip for the index chart; hidden on days with no index value.\n * `getPaneLeft` returns the plot pane's left offset in the container (the left scale width).\n */\nexport function createIndexTooltip(\n  container: HTMLElement,\n  getSeries: () => IndexTooltipSeries,\n  getPaneLeft: () => number,\n): IndexTooltip {\n  const tooltip = document.createElement(\"div\");\n  tooltip.style.position = \"absolute\";\n  tooltip.style.zIndex = \"30\";\n  tooltip.style.pointerEvents = \"none\";\n  tooltip.style.display = \"none\";\n  tooltip.className =\n    \"rounded-lg border border-zinc-800 bg-zinc-900/95 px-3 py-2 text-xs shadow-xl backdrop-blur-sm\";\n  container.appendChild(tooltip);\n\n  const hide = () => {\n    tooltip.style.display = \"none\";\n  };\n\n  const valueAt = (\n    series: ISeriesApi<\"Line\", Time> | ISeriesApi<\"Histogram\", Time> | null,\n    param: MouseEventParams<Time>,\n  ): number | undefined => {\n    if (!series) return undefined;\n    const data = param.seriesData.get(series) as { value?: number } | undefined;\n    return typeof data?.value === \"number\" && Number.isFinite(data.value)\n      ? data.value\n      : undefined;\n  };\n\n  const onCrosshairMove = (param: MouseEventParams<Time>) => {\n    const { index, price, volume } = getSeries();\n    // Pointless events (the cursor left the pane) end here, before the price scale is measured.\n    if (!index || !param.point || !param.time || param.point.x < 0 || param.point.y < 0) {\n      hide();\n      return;\n    }\n    const paneLeft = getPaneLeft();\n    if (paneLeft + param.point.x > container.clientWidth || param.point.y > container.clientHeight) {\n      hide();\n      return;\n    }\n    const value = valueAt(index, param);\n    const ts = typeof param.time === \"number\" ? param.time * 1000 : NaN;\n    if (value === undefined || !Number.isFinite(ts)) {\n      hide();\n      return;\n    }\n\n    const dateStr = new Date(ts).toISOString().slice(0, 10);\n    tooltip.innerHTML = renderIndexTooltipHtml(dateStr, value, findFearGreedBand(value), {\n      price: valueAt(price, param),\n      volume: valueAt(volume, param),\n    });\n\n    tooltip.style.display = \"block\";\n    const { left, top } = getIndexTooltipPosition(\n      param.point,\n      paneLeft,\n      { width: tooltip.offsetWidth || 140, height: tooltip.offsetHeight || 60 },\n      { width: container.clientWidth, height: container.clientHeight },\n    );\n    tooltip.style.left = `${left}px`;\n    tooltip.style.top = `${top}px`;\n  };\n\n  return {\n    onCrosshairMove,\n    dispose: () => tooltip.remove(),\n  };\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/fear-greed-index-chart/lib/index-tooltip.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/lib/chart-options.ts",
      "content": "import type {\n  ChartOptions,\n  ColorType,\n  DeepPartial,\n  HistogramSeriesPartialOptions,\n  LineSeriesPartialOptions,\n  PriceScaleMode,\n} from \"lightweight-charts\";\nimport { compactUsdTick } from \"./index-tooltip\";\n\nexport const VOLUME_SCALE_ID = \"volume\";\nexport const SCALE_MARGIN = 0.05;\n/** Volume bars stay in the bottom ~15% and share the index zero line. */\nexport const VOLUME_SCALE_MARGINS = { top: 0.8, bottom: SCALE_MARGIN };\n\n/** Left price scale margins: the line's low sits clear of the zone floor, or above the volume bars. */\nexport function priceScaleMargins(withVolume: boolean): { top: number; bottom: number } {\n  return { top: SCALE_MARGIN, bottom: withVolume ? 0.26 : 0.12 };\n}\n// Fits half-step ticks like \"$112.5K\", so the plot keeps its left edge across presets.\nexport const PRICE_SCALE_MIN_WIDTH = 68;\n// Below this many pixels per day the index line drops to 1px so it stays readable.\nexport const DENSE_BAR_SPACING = 1;\n\nexport interface ChartPalette {\n  text: string;\n  grid: string;\n  label: string;\n  halo: string;\n  price: string;\n  volume: string;\n}\n\nexport function chartPalette(theme: string | undefined): ChartPalette {\n  return theme === \"dark\"\n    ? {\n        text: \"#9CA3AF\",\n        grid: \"rgba(148,163,184,0.10)\",\n        label: \"rgba(156,163,175,0.85)\",\n        halo: \"rgba(10,10,10,0.85)\",\n        price: \"rgba(161,161,170,0.85)\",\n        volume: \"rgba(161,161,170,0.22)\",\n      }\n    : {\n        text: \"#52525b\",\n        grid: \"rgba(0,0,0,0.05)\",\n        label: \"rgba(82,82,91,0.85)\",\n        halo: \"rgba(255,255,255,0.85)\",\n        price: \"rgba(82,82,91,0.8)\",\n        volume: \"rgba(82,82,91,0.16)\",\n      };\n}\n\n/** Theme-dependent chart options, applied at creation and on theme changes. */\nexport function themeOptions(palette: ChartPalette): DeepPartial<ChartOptions> {\n  return {\n    layout: {\n      // \"solid\" = ColorType.Solid; importing the enum would eagerly bundle the library.\n      background: { type: \"solid\" as ColorType.Solid, color: \"rgba(0,0,0,0)\" },\n      textColor: palette.text,\n      // The library's license then asks for a TradingView credit with a link elsewhere in the app.\n      attributionLogo: false,\n    },\n    grid: {\n      vertLines: { color: palette.grid },\n      horzLines: { color: palette.grid },\n    },\n  };\n}\n\n/** Full options for createChart; `fontFamily` is the host app's font, for the axis labels. */\nexport function chartOptions(\n  palette: ChartPalette,\n  width: number,\n  height: number,\n  fontFamily?: string,\n): DeepPartial<ChartOptions> {\n  const theme = themeOptions(palette);\n  return {\n    width,\n    height,\n    autoSize: false,\n    ...theme,\n    layout: fontFamily ? { ...theme.layout, fontFamily } : theme.layout,\n    rightPriceScale: {\n      borderVisible: false,\n      scaleMargins: { top: SCALE_MARGIN, bottom: SCALE_MARGIN },\n    },\n    leftPriceScale: {\n      visible: false,\n      // 0 = PriceScaleMode.Normal.\n      mode: 0 as PriceScaleMode.Normal,\n      borderVisible: false,\n      scaleMargins: priceScaleMargins(false),\n    },\n    timeScale: {\n      borderVisible: false,\n      timeVisible: false,\n      secondsVisible: false,\n      // The label column is reserved once the plot width is known.\n      rightOffsetPixels: 0,\n      barSpacing: 4,\n      // No fixRightEdge: it would force the right offset, and with it the label gutter, to 0.\n      fixLeftEdge: true,\n      lockVisibleTimeRangeOnResize: true,\n    },\n    // The tooltip carries the values; a horizontal crosshair label would read past 0-100.\n    crosshair: { mode: 0, horzLine: { visible: false, labelVisible: false } },\n    handleScroll: {\n      mouseWheel: true,\n      pressedMouseMove: true,\n      horzTouchDrag: true,\n      vertTouchDrag: false,\n    },\n    handleScale: {\n      mouseWheel: true,\n      pinch: true,\n      axisPressedMouseMove: false,\n      axisDoubleClickReset: true,\n    },\n  };\n}\n\n// Index points within which an axis tick would sit half under the latest-value label.\nconst LATEST_LABEL_CLEARANCE = 5;\n\n/** Index scale format: whole numbers, minus any tick the latest-value label would half cover. */\nexport function indexPriceFormat(latest: number) {\n  return {\n    type: \"custom\" as const,\n    minMove: 1,\n    formatter: (value: number) =>\n      value !== latest && Math.abs(value - latest) < LATEST_LABEL_CLEARANCE\n        ? \"\"\n        : String(Math.round(value)),\n  };\n}\n\nexport const INDEX_SERIES_OPTIONS: LineSeriesPartialOptions = {\n  lineWidth: 2,\n  priceScaleId: \"right\",\n  priceLineVisible: false,\n  lastValueVisible: true,\n  crosshairMarkerVisible: true,\n  crosshairMarkerRadius: 4,\n  priceFormat: { type: \"price\", precision: 0, minMove: 1 },\n  autoscaleInfoProvider: () => ({ priceRange: { minValue: 0, maxValue: 100 } }),\n};\n\nexport function priceSeriesOptions(palette: ChartPalette): LineSeriesPartialOptions {\n  return {\n    color: palette.price,\n    lineWidth: 1,\n    priceScaleId: \"left\",\n    priceLineVisible: false,\n    lastValueVisible: false,\n    crosshairMarkerVisible: false,\n    priceFormat: { type: \"custom\", formatter: compactUsdTick },\n  };\n}\n\nexport function volumeSeriesOptions(palette: ChartPalette): HistogramSeriesPartialOptions {\n  return {\n    color: palette.volume,\n    priceScaleId: VOLUME_SCALE_ID,\n    priceFormat: { type: \"volume\" },\n    priceLineVisible: false,\n    lastValueVisible: false,\n  };\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/fear-greed-index-chart/lib/chart-options.ts"
    },
    {
      "path": "registry/voraui/fear-greed-index-chart/lib/chart-range.ts",
      "content": "export type Preset = \"30D\" | \"1Y\" | \"ALL\";\n\n/** Days shown by each fixed-length preset; \"ALL\" fits the whole history. */\nexport const PRESET_DAYS: Record<Exclude<Preset, \"ALL\">, number> = { \"30D\": 30, \"1Y\": 365 };\nexport const DAY_SECONDS = 86_400;\n\n// Fits \"Extreme Greed\" at 11px plus the inset on both sides.\nconst LABEL_GUTTER = 92;\n/** Plot width from which the band labels get their own column; narrower plots hide them. */\nexport const LABEL_GUTTER_MIN_PLOT_WIDTH = 480;\n\n/** Right offset in pixels reserved for the band labels; 0 means the labels are hidden. */\nexport function labelGutterPixels(plotWidth: number): number {\n  return plotWidth >= LABEL_GUTTER_MIN_PLOT_WIDTH ? LABEL_GUTTER : 0;\n}\n\n/** Logical range showing bars `from..to` with the gutter kept free right of `to`. */\nexport function presetLogicalRange(\n  from: number,\n  to: number,\n  plotWidth: number,\n  gutter: number,\n): { from: number; to: number } {\n  const usable = plotWidth - gutter;\n  if (gutter <= 0 || usable <= 0 || to <= from) return { from, to };\n  return { from, to: to + (gutter * (to - from)) / usable };\n}\n\n// lightweight-charts' default minBarSpacing.\nconst DEFAULT_MIN_BAR_SPACING = 0.5;\n\n/** Smallest bar spacing at which all `bars` plus the gutter still fit, so zoom-out stops at \"all\". */\nexport function minBarSpacingFor(plotWidth: number, gutter: number, bars: number): number {\n  const usable = plotWidth - gutter;\n  if (bars <= 0 || usable <= 0) return DEFAULT_MIN_BAR_SPACING;\n  return usable / bars;\n}\n\n/** Number of distinct times across all series: the bars the time scale actually lays out. */\nexport function distinctTimeCount(series: ReadonlyArray<ReadonlyArray<{ time: number }>>): number {\n  const times = new Set<number>();\n  for (const points of series) for (const p of points) times.add(p.time);\n  return times.size;\n}\n\ntype LogicalSpan = { from: number; to: number };\n\n// Half a bar either side of the first and last bar centers.\nconst FIRST_BAR_EDGE = -0.5;\n// Overshoot the chart produces on its own edge corrections; clamping it would loop.\nconst CLAMP_TOLERANCE = 0.5;\n\n/**\n * Keeps a requested logical range between the first bar and the reserved padding past the last\n * bar, preserving its span; a span wider than everything fits everything.\n */\nexport function clampLogicalRange(\n  range: LogicalSpan,\n  barCount: number,\n  rightPaddingBars: number,\n): LogicalSpan {\n  if (barCount <= 0) return range;\n  const maxTo = barCount - 1 + rightPaddingBars;\n  const span = range.to - range.from;\n  if (span > maxTo - FIRST_BAR_EDGE + 2 * CLAMP_TOLERANCE) return { from: FIRST_BAR_EDGE, to: maxTo };\n  if (range.to > maxTo + CLAMP_TOLERANCE) return { from: maxTo - span, to: maxTo };\n  if (range.from < FIRST_BAR_EDGE - CLAMP_TOLERANCE) {\n    return { from: FIRST_BAR_EDGE, to: FIRST_BAR_EDGE + span };\n  }\n  return range;\n}\n\n/** Finest calendar unit the time axis labels at the current zoom. */\nexport type TickDetail = \"year\" | \"month\" | \"day\";\n\n// Pixels a year (or month) must span before the unit below it gets its own labels.\nconst MIN_UNIT_WIDTH = 180;\n\nexport function tickDetailFor(barSpacing: number): TickDetail {\n  if (barSpacing * 30 >= MIN_UNIT_WIDTH) return \"day\";\n  if (barSpacing * 365 >= MIN_UNIT_WIDTH) return \"month\";\n  return \"year\";\n}\n\n// lightweight-charts' TickMarkType: 0 = Year, 1 = Month, 2 = DayOfMonth.\nconst TICK_DETAIL_RANK: Record<TickDetail, number> = { year: 0, month: 1, day: 2 };\n\n/**\n * Blanks marks finer than `detail`: the library drops one into any leftover gap, which reads as\n * a lone \"11\" or \"jun\" in a row of years. `null` keeps the library's default label.\n */\nexport function tickLabelFor(tickMarkType: number, detail: TickDetail): \"\" | null {\n  return tickMarkType > TICK_DETAIL_RANK[detail] ? \"\" : null;\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/fear-greed-index-chart/lib/chart-range.ts"
    }
  ],
  "type": "registry:block"
}