Pages
Analytics

Analytics Page

An analytics dashboard page for React with a 7, 30 and 90 day range switcher, stat cards with deltas and sparklines, an animated area chart with a hover tooltip, and top pages, sources and devices breakdowns.

analytics-page.preview

Analytics

alex.dev

Traffic is healthy

Visitors

14.5K

12.4%

Unique visitors

10.5K

9.8%

Page views

37.6K

8.1%

Bounce rate

42.3%

3.2%

Avg. session

2m 14s

5.6%

Active days

29/30

Visitors

HealthyLowNone
Normal
6715033351680
Oct 16Oct 30Nov 14

Visitors vs unique

VisitorsUnique

Traffic health

1 dead · 1 low

Oct 16Today
  • No trafficNov 3 · 0
  • Low trafficOct 25 · 90

Top pages

  • /10,437
  • /pricing5,218
  • /blog/shipping-fast3,670
  • /docs2,810
  • /about1,778

Sources

  • Google8,143
  • Direct5,620
  • Twitter / X2,695
  • GitHub1,950
  • LinkedIn1,090

Countries

  • India7,111
  • United States5,620
  • Germany2,351
  • United Kingdom2,064
  • Brazil1,262

Devices

  • Desktop58%
  • Mobile36%
  • Tablet6%

Install

Copies the source into components/blocks/analytics-page.tsx and installs what it needs.

$ pnpm dlx shadcn@latest add https://makeui.xyz/r/analytics-page.json

Usage

app/page.tsx
import { AnalyticsPage } from "@/components/blocks/analytics-page"

export default function Page() {
  return (
    <AnalyticsPage
      title="Analytics"
      subtitle="alex.dev"
      // optional: pass your own numbers, otherwise sample data is shown
      data={{
        "7d": {
          points: [
            { date: "Nov 8", value: 412 },
            { date: "Nov 9", value: 438 },
          ],
          stats: [{ label: "Visitors", value: "2.9K", delta: 12.4, spark: [412, 438] }],
          pages: [{ label: "/", value: 1820 }],
          sources: [{ label: "Google", value: 1420 }],
          devices: [{ label: "Desktop", value: 58 }],
        },
        "30d": { /* same shape */ },
        "90d": { /* same shape */ },
      }}
    />
  )
}

Source

Prefer to copy by hand? It's one file. Requires motion and the shadcn cn helper.

components/blocks/analytics-page.tsx
"use client"

import { useEffect, useId, useMemo, useState } from "react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import { ArrowDownRight, ArrowUpRight } from "lucide-react"
import { Liveline } from "liveline"
import { cn } from "@/lib/utils"

/* ───────────── types ───────────── */

type Range = "7d" | "30d" | "90d"
type ThemeName = "light" | "dark"
/** good = normal traffic, low = well below normal, down = (almost) no traffic. */
type Health = "good" | "low" | "down"
type Point = { date: string; value: number }
type Stat = {
  label: string
  value: string
  /** Percent change vs the previous period. Leave out to hide it. */
  delta?: number
  /** Set for metrics where down is good, like bounce rate. */
  lowerIsBetter?: boolean
  /** Tiny trend line. Leave out to hide it. */
  spark?: number[]
}
type Row = { label: string; value: number }
type Dataset = Record<
  Range,
  {
    points: Point[]
    uniques?: Point[]
    stats: Stat[]
    pages: Row[]
    sources: Row[]
    devices: Row[]
    countries: Row[]
  }
>

type Props = {
  title?: string
  subtitle?: string
  /** Pass your real numbers here. Leave out for generated sample data. */
  data?: Dataset
  /** Pin a theme. Leave out to follow the site (.dark on <html>). */
  theme?: ThemeName
  className?: string
}

/* ───────────── theme ───────────── */

const themes: Record<ThemeName, Record<string, string>> = {
  light: { "--an-bg": "#fdfdfc", "--an-fg": "#1c1b19", "--an-body": "#5f5d58", "--an-muted": "#8b8983", "--an-line": "rgb(28 27 25 / 0.1)", "--an-card": "#f4f4f2", "--an-accent": "#2f8f5b" },
  dark: { "--an-bg": "#0a0a0a", "--an-fg": "#f5f5f4", "--an-body": "#a8a6a0", "--an-muted": "#7d7b75", "--an-line": "rgb(245 245 244 / 0.1)", "--an-card": "#161615", "--an-accent": "#4ade80" },
}

function useHtmlDark() {
  const [dark, setDark] = useState(false)
  useEffect(() => {
    const el = document.documentElement
    const read = () => setDark(el.classList.contains("dark"))
    read()
    const mo = new MutationObserver(read)
    mo.observe(el, { attributes: true, attributeFilter: ["class"] })
    return () => mo.disconnect()
  }, [])
  return dark
}

/* ───────────── traffic health ───────────── */

const healthBg: Record<Health, string> = { good: "bg-(--an-accent)", low: "bg-amber-500", down: "bg-rose-500" }
const healthHex: Record<Health, string> = { good: "#2f8f5b", low: "#f59e0b", down: "#f43f5e" }
const healthRank: Record<Health, number> = { good: 0, low: 1, down: 2 }

function medianOf(points: Point[]) {
  const sorted = points.map((p) => p.value).sort((a, b) => a - b)
  return sorted[Math.floor(sorted.length / 2)] || 0
}

/**
 * Each day is compared with the median day of the period:
 * under 15% of normal (or zero) = down (red), under 50% = low (amber), otherwise good (green).
 */
function healthOf(points: Point[]): Health[] {
  const median = medianOf(points)
  return points.map((p) => (p.value === 0 || p.value < median * 0.15 ? "down" : p.value < median * 0.5 ? "low" : "good"))
}

function healthLabel(h: Health, value: number) {
  if (h === "good") return "Healthy"
  if (h === "low") return "Low traffic"
  return value === 0 ? "No traffic" : "Almost no traffic"
}

/* ───────────── sample data ───────────── */

const ranges: Range[] = ["7d", "30d", "90d"]
const dayCount: Record<Range, number> = { "7d": 7, "30d": 30, "90d": 90 }
const DAY = 86400
const compact = (n: number) => new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 }).format(n)

function rng(seed: number) {
  return () => {
    seed = (seed * 1664525 + 1013904223) >>> 0
    return seed / 4294967296
  }
}

function series(n: number, base: number, seed: number, phase = 0) {
  const r = rng(seed)
  return Array.from({ length: n }, (_, i) => {
    const trend = 1 + (i / n) * 0.25
    const wave = 1 + 0.1 * Math.sin(i * 0.45 + phase)
    const noise = 1 + (r() - 0.5) * 0.05
    return Math.round(base * trend * wave * noise)
  })
}

/** A few sample outages so the demo shows red and amber days. Real data won't need this. */
const dips: Record<Range, { zero: number[]; low: number[] }> = {
  "7d": { zero: [4], low: [2] },
  "30d": { zero: [18], low: [9] },
  "90d": { zero: [21, 63], low: [40, 80] },
}
function withDips(vals: number[], range: Range) {
  return vals.map((v, i) => (dips[range].zero.includes(i) ? 0 : dips[range].low.includes(i) ? Math.round(v * 0.2) : v))
}

function dayLabel(end: string, back: number) {
  const d = new Date(`${end}T00:00:00Z`)
  d.setUTCDate(d.getUTCDate() - back)
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" })
}

function buildData(end = "2026-11-14"): Dataset {
  const out = {} as Dataset
  let baseTotal = 0
  ranges.forEach((r, k) => {
    const n = dayCount[r]
    const vals = withDips(series(n, 420 + k * 40, 11 + k), r)
    const total = vals.reduce((a, b) => a + b, 0)
    if (k === 0) baseTotal = total
    const f = total / baseTotal
    const scale = (rows: Row[]) => rows.map((x) => ({ ...x, value: Math.round(x.value * f) }))
    const points = vals.map((value, i) => ({ date: dayLabel(end, n - 1 - i), value }))
    const uniqueVals = withDips(series(n, 300 + k * 30, 51 + k, 1.4), r)
    const uniques = points.map((p, i) => ({ date: p.date, value: uniqueVals[i] }))
    const quiet = healthOf(points).filter((h) => h === "down").length

    out[r] = {
      points,
      uniques,
      stats: [
        { label: "Visitors", value: compact(total), delta: 12.4, spark: vals },
        { label: "Unique visitors", value: compact(uniqueVals.reduce((a, b) => a + b, 0)), delta: 9.8, spark: uniqueVals },
        { label: "Page views", value: compact(Math.round(total * 2.6)), delta: 8.1, spark: withDips(series(n, 1100, 21 + k, 2.6), r) },
        { label: "Bounce rate", value: "42.3%", delta: -3.2, lowerIsBetter: true, spark: series(n, 44, 31 + k, 0.8).map((v, i, a) => v * (1.2 - (i / a.length) * 0.3)) },
        { label: "Avg. session", value: "2m 14s", delta: 5.6, spark: series(n, 120, 41 + k, 3.7) },
        { label: "Active days", value: `${n - quiet}/${n}` },
      ],
      pages: scale([
        { label: "/", value: 1820 },
        { label: "/pricing", value: 910 },
        { label: "/blog/shipping-fast", value: 640 },
        { label: "/docs", value: 490 },
        { label: "/about", value: 310 },
      ]),
      sources: scale([
        { label: "Google", value: 1420 },
        { label: "Direct", value: 980 },
        { label: "Twitter / X", value: 470 },
        { label: "GitHub", value: 340 },
        { label: "LinkedIn", value: 190 },
      ]),
      countries: scale([
        { label: "India", value: 1240 },
        { label: "United States", value: 980 },
        { label: "Germany", value: 410 },
        { label: "United Kingdom", value: 360 },
        { label: "Brazil", value: 220 },
      ]),
      devices: [
        { label: "Desktop", value: 58 },
        { label: "Mobile", value: 36 },
        { label: "Tablet", value: 6 },
      ],
    }
  })
  return out
}

const defaultData = buildData()

/* ───────────── pieces ───────────── */

const pillText: Record<Health, string> = { good: "Traffic is healthy", low: "Traffic is low", down: "No traffic" }

function StatusPill({ health }: { health: Health }) {
  return (
    <span className="inline-flex h-8 items-center gap-2 rounded-full bg-(--an-card) px-3 text-xs text-(--an-fg)">
      <span className={cn("size-2 rounded-full", healthBg[health])} />
      {pillText[health]}
    </span>
  )
}

function Spark({ values }: { values: number[] }) {
  const w = 80
  const h = 24
  const min = Math.min(...values)
  const span = Math.max(...values) - min || 1
  const d = values.map((v, i) => `${i ? "L" : "M"}${((i / (values.length - 1)) * w).toFixed(1)} ${(h - 2 - ((v - min) / span) * (h - 4)).toFixed(1)}`).join(" ")
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="h-6 w-20 shrink-0" fill="none" aria-hidden>
      <path d={d} className="stroke-(--an-accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
    </svg>
  )
}

/** Smooth, overshoot-free curve through the points (monotone cubic). Coordinates are in the 0 to 100 viewBox. */
function smoothPath(pts: (readonly [number, number])[]) {
  const n = pts.length
  if (n < 2) return ""
  const dx: number[] = []
  const m: number[] = []
  for (let i = 0; i < n - 1; i++) {
    dx[i] = pts[i + 1][0] - pts[i][0]
    m[i] = (pts[i + 1][1] - pts[i][1]) / dx[i]
  }
  const t: number[] = new Array(n)
  t[0] = m[0]
  t[n - 1] = m[n - 2]
  for (let i = 1; i < n - 1; i++) t[i] = m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2
  for (let i = 0; i < n - 1; i++) {
    if (m[i] === 0) {
      t[i] = 0
      t[i + 1] = 0
      continue
    }
    const a = t[i] / m[i]
    const b = t[i + 1] / m[i]
    const s = a * a + b * b
    if (s > 9) {
      const tau = 3 / Math.sqrt(s)
      t[i] = tau * a * m[i]
      t[i + 1] = tau * b * m[i]
    }
  }
  let d = `M${pts[0][0].toFixed(2)} ${pts[0][1].toFixed(2)}`
  for (let i = 0; i < n - 1; i++) {
    const h = dx[i] / 3
    d += ` C${(pts[i][0] + h).toFixed(2)} ${(pts[i][1] + t[i] * h).toFixed(2)} ${(pts[i + 1][0] - h).toFixed(2)} ${(pts[i + 1][1] - t[i + 1] * h).toFixed(2)} ${pts[i + 1][0].toFixed(2)} ${pts[i + 1][1].toFixed(2)}`
  }
  return d
}

function Legend() {
  return (
    <div className="flex items-center gap-3 text-xs text-(--an-muted)">
      {(["good", "low", "down"] as Health[]).map((h) => (
        <span key={h} className="inline-flex items-center gap-1.5">
          <span className={cn("size-1.5 rounded-full", healthBg[h])} />
          {h === "good" ? "Healthy" : h === "low" ? "Low" : "None"}
        </span>
      ))}
    </div>
  )
}

/**
 * Visitors per day. One clean green line + soft area fill.
 * Low / dead days are marked with a faint column and a dot, nothing else touches the line.
 */
function VisitorsChart({ points }: { points: Point[] }) {
  const reduce = useReducedMotion()
  const id = useId().replace(/:/g, "")
  const [hover, setHover] = useState<number | null>(null)
  const health = useMemo(() => healthOf(points), [points])

  const n = points.length
  const hi = Math.max(...points.map((p) => p.value), 1) * 1.12
  const normal = medianOf(points)

  const xy = (i: number, v: number) => [(i / (n - 1)) * 100, 100 - (v / hi) * 100] as const

  const coords = points.map((p, i) => xy(i, p.value))
  const line = smoothPath(coords)
  const area = `${line} L100 100 L0 100Z`
  const normalY = 100 - (normal / hi) * 100
  const ticks = [1, 0.75, 0.5, 0.25, 0]
  const slot = 100 / (n - 1)

  const active = hover !== null ? points[hover] : null
  const [hx, hy] = hover !== null && active ? xy(hover, active.value) : [0, 0]
  const tx = hx < 15 ? "0%" : hx > 85 ? "-100%" : "-50%"

  return (
    <div>
      <div className="relative h-56">
        <div
          className="absolute inset-y-0 left-0 right-10 touch-none"
          onPointerMove={(e) => {
            const r = e.currentTarget.getBoundingClientRect()
            setHover(Math.max(0, Math.min(n - 1, Math.round(((e.clientX - r.left) / r.width) * (n - 1)))))
          }}
          onPointerLeave={() => setHover(null)}
        >
          {/* faint columns behind flagged days */}
          {points.map((p, i) => {
            if (health[i] === "good") return null
            const x = (i / (n - 1)) * 100
            return (
              <span
                key={`band-${i}`}
                className="pointer-events-none absolute inset-y-0 rounded-sm"
                style={{
                  left: `${x}%`,
                  width: `max(${slot}%, 6px)`,
                  transform: "translateX(-50%)",
                  background: healthHex[health[i]],
                  opacity: 0.1,
                }}
              />
            )
          })}

          {/* line + area, revealed with a clip (no pathLength, it breaks non-scaling strokes) */}
          <motion.div
            className="absolute inset-0"
            initial={reduce ? false : { clipPath: "inset(-8px 100% -8px 0px)" }}
            animate={{ clipPath: "inset(-8px 0% -8px 0px)" }}
            transition={{ duration: 0.8, ease: "easeOut" }}
          >
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 size-full overflow-visible" aria-hidden>
              <defs>
                <linearGradient id={`${id}-fill`} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="var(--an-accent)" stopOpacity="0.16" />
                  <stop offset="100%" stopColor="var(--an-accent)" stopOpacity="0" />
                </linearGradient>
              </defs>

              {ticks.map((f) => (
                <line
                  key={f}
                  x1="0"
                  x2="100"
                  y1={(1 - f) * 100}
                  y2={(1 - f) * 100}
                  className="stroke-(--an-line)"
                  strokeWidth="1"
                  strokeDasharray={f === 0 ? undefined : "2 4"}
                  vectorEffect="non-scaling-stroke"
                />
              ))}

              <line
                x1="0"
                x2="100"
                y1={normalY}
                y2={normalY}
                className="stroke-(--an-muted)"
                strokeWidth="1"
                strokeDasharray="4 4"
                vectorEffect="non-scaling-stroke"
                opacity="0.5"
              />

              <path d={area} fill={`url(#${id}-fill)`} />
              <path
                d={line}
                fill="none"
                className="stroke-(--an-accent)"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                vectorEffect="non-scaling-stroke"
              />
            </svg>
          </motion.div>

          <span
            className="pointer-events-none absolute right-1 text-[10px] uppercase tracking-wide text-(--an-muted)"
            style={{ top: `calc(${normalY}% - 14px)` }}
          >
            Normal
          </span>

          {/* dots on flagged days */}
          {points.map((p, i) => {
            if (health[i] === "good") return null
            const [x, y] = xy(i, p.value)
            return (
              <span
                key={`dot-${i}`}
                className="pointer-events-none absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2 ring-(--an-bg)"
                style={{ left: `${x}%`, top: `${y}%`, background: healthHex[health[i]] }}
              />
            )
          })}

          {/* hover */}
          {active && (
            <>
              <span className="pointer-events-none absolute inset-y-0 w-px bg-(--an-muted)/30" style={{ left: `${hx}%` }} />
              <span
                className="pointer-events-none absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full ring-4 ring-(--an-bg)"
                style={{ left: `${hx}%`, top: `${hy}%`, background: healthHex[health[hover!]] }}
              />
              <div
                className="pointer-events-none absolute top-0 z-10 whitespace-nowrap rounded-lg bg-(--an-fg) px-2.5 py-1.5 text-xs text-(--an-bg) shadow-lg"
                style={{ left: `${hx}%`, transform: `translate(${tx}, -110%)` }}
              >
                {active.date} · {active.value.toLocaleString("en-US")} visitors
                {health[hover!] !== "good" ? ` · ${healthLabel(health[hover!], active.value)}` : ""}
              </div>
            </>
          )}
        </div>

        {/* y-axis */}
        {ticks.map((f) => (
          <span
            key={f}
            className="pointer-events-none absolute right-0 -translate-y-1/2 text-xs tabular-nums text-(--an-muted)"
            style={{ top: `${(1 - f) * 100}%` }}
          >
            {compact(Math.round(hi * f))}
          </span>
        ))}
      </div>

      <div className="mr-10 mt-3 flex justify-between text-xs text-(--an-muted)">
        <span>{points[0].date}</span>
        <span>{points[Math.floor((n - 1) / 2)].date}</span>
        <span>{points[n - 1].date}</span>
      </div>
    </div>
  )
}

/**
 * Liveline plots unix-second timestamps. This is a daily report, not a live feed, so we spread
 * the days out ending "now" and map timestamps back to your own date labels for the axis and tooltip.
 */
function useDaily(points: Point[]) {
  const n = points.length
  return useMemo(() => {
    const now = Math.floor(Date.now() / 1000)
    const times = points.map((_, i) => now - (n - 1 - i) * DAY)
    const labelAt = (t: number) => points[Math.max(0, Math.min(n - 1, n - 1 - Math.round((now - t) / DAY)))].date
    return { times, labelAt, window: n * DAY }
  }, [points, n])
}

/** Visitors vs unique visitors, drawn by Liveline. */
function CompareChart({ points, uniques, theme }: { points: Point[]; uniques: Point[]; theme: ThemeName }) {
  const { times, labelAt, window } = useDaily(points)
  const lines = useMemo(
    () => [
      { id: "visitors", label: "Visitors", color: themes[theme]["--an-accent"], data: points.map((p, i) => ({ time: times[i], value: p.value })), value: points[points.length - 1].value },
      { id: "unique", label: "Unique", color: "#60a5fa", data: uniques.map((p, i) => ({ time: times[i], value: p.value })), value: uniques[uniques.length - 1].value },
    ],
    [points, uniques, times, theme]
  )

  return (
    <div className="h-60">
      <Liveline
        data={[]}
        value={0}
        series={lines}
        theme={theme}
        window={window}
        grid
        pulse={false}
        scrub
        formatValue={(v) => Math.round(v).toLocaleString("en-US")}
        formatTime={labelAt}
      />
    </div>
  )
}

/** One bar per day: green healthy, amber low, red no traffic. Hover a bar to read the day. */
function TrafficHealth({ points }: { points: Point[] }) {
  const health = useMemo(() => healthOf(points), [points])
  const [hover, setHover] = useState<number | null>(null)
  const flagged = points
    .map((p, i) => ({ p, h: health[i] }))
    .filter((x) => x.h !== "good")
    .sort((a, b) => healthRank[b.h] - healthRank[a.h])
  const quiet = health.filter((h) => h === "down").length
  const low = health.filter((h) => h === "low").length
  const active = hover !== null ? points[hover] : null

  return (
    <section className="rounded-2xl border border-(--an-line) p-4 @3xl:p-5">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h2 className="text-sm text-(--an-fg)">Traffic health</h2>
        <p className="text-xs text-(--an-muted)">
          {quiet === 0 && low === 0 ? "Every day healthy" : `${quiet} dead · ${low} low`}
        </p>
      </div>

      <div className="mt-4 flex h-8 gap-0.5" onPointerLeave={() => setHover(null)}>
        {health.map((h, i) => (
          <span
            key={i}
            onPointerEnter={() => setHover(i)}
            className={cn("h-full flex-1 rounded-[3px] transition-opacity", healthBg[h], h === "good" && "opacity-30", hover !== null && hover !== i && "opacity-20")}
            style={hover === i ? { opacity: 1 } : undefined}
          />
        ))}
      </div>

      <div className="mt-3 flex h-4 justify-between text-xs text-(--an-muted)">
        {active ? (
          <span className="text-(--an-fg)">
            {active.date} · {healthLabel(health[hover!], active.value)} · {active.value.toLocaleString("en-US")} visitors
          </span>
        ) : (
          <>
            <span>{points[0].date}</span>
            <span>Today</span>
          </>
        )}
      </div>

      {flagged.length > 0 && (
        <ul className="mt-4 divide-y divide-(--an-line) text-sm">
          {flagged.slice(0, 4).map(({ p, h }, i) => (
            <li key={i} className="flex items-center justify-between gap-3 py-2">
              <span className="inline-flex items-center gap-2 text-(--an-fg)">
                <span className={cn("size-2 rounded-full", healthBg[h])} />
                {healthLabel(h, p.value)}
              </span>
              <span className="tabular-nums text-(--an-muted)">
                {p.date} · {p.value.toLocaleString("en-US")}
              </span>
            </li>
          ))}
        </ul>
      )}
    </section>
  )
}

function BarList({ title, rows }: { title: string; rows: Row[] }) {
  const max = Math.max(...rows.map((r) => r.value))
  return (
    <section>
      <h2 className="text-sm text-(--an-fg)">{title}</h2>
      <ul className="mt-3 space-y-1">
        {rows.map((r, i) => (
          <li key={r.label} className="relative flex items-center justify-between gap-3 rounded-lg px-2.5 py-1.5 text-sm">
            <motion.span
              aria-hidden
              className="absolute inset-y-0 left-0 rounded-lg bg-(--an-card)"
              initial={{ width: 0 }}
              animate={{ width: `${(r.value / max) * 100}%` }}
              transition={{ type: "spring", stiffness: 260, damping: 30, delay: i * 0.04 }}
            />
            <span className="relative truncate text-(--an-fg)">{r.label}</span>
            <span className="relative tabular-nums text-(--an-muted)">{r.value.toLocaleString("en-US")}</span>
          </li>
        ))}
      </ul>
    </section>
  )
}

function Devices({ rows }: { rows: Row[] }) {
  const mix = [100, 60, 30]
  const shade = (i: number) => `color-mix(in oklab, var(--an-accent) ${mix[i] ?? 20}%, var(--an-card))`
  return (
    <section>
      <h2 className="text-sm text-(--an-fg)">Devices</h2>
      <div className="mt-4 flex h-2 gap-0.5 overflow-hidden rounded-full">
        {rows.map((r, i) => (
          <motion.span key={r.label} className="h-full" style={{ background: shade(i) }} initial={{ width: 0 }} animate={{ width: `${r.value}%` }} transition={{ type: "spring", stiffness: 200, damping: 28, delay: i * 0.05 }} />
        ))}
      </div>
      <ul className="mt-4 space-y-2 text-sm">
        {rows.map((r, i) => (
          <li key={r.label} className="flex items-center justify-between">
            <span className="inline-flex items-center gap-2 text-(--an-fg)">
              <span className="size-2 rounded-full" style={{ background: shade(i) }} />
              {r.label}
            </span>
            <span className="tabular-nums text-(--an-muted)">{r.value}%</span>
          </li>
        ))}
      </ul>
    </section>
  )
}

const pill = "rounded-full outline-none focus-visible:ring-2 focus-visible:ring-(--an-muted)/50"

/* ───────────── page ───────────── */

export function AnalyticsPage({ title = "Analytics", subtitle = "alex.dev", data = defaultData, theme, className }: Props) {
  const reduce = useReducedMotion()
  const siteDark = useHtmlDark()
  const id = useId()
  const [range, setRange] = useState<Range>("30d")

  const current: ThemeName = theme ?? (siteDark ? "dark" : "light")
  const vars = themes[current] as React.CSSProperties
  const spring = { type: "spring" as const, stiffness: 420, damping: 34 }
  const d = data[range]
  const latest = healthOf(d.points).at(-1) ?? "good"

  return (
    <div className="@container">
      <div style={vars} className={cn("bg-(--an-bg) text-(--an-body) transition-colors duration-500", className)}>
        <div className="mx-auto max-w-4xl px-6 py-10">
          <header className="flex flex-wrap items-end justify-between gap-4">
            <div>
              <h1 className="text-base font-medium text-(--an-fg)">{title}</h1>
              <p className="mt-0.5 text-sm text-(--an-muted)">{subtitle}</p>
            </div>
            <div className="flex flex-wrap items-center gap-3">
              <StatusPill health={latest} />
              <div role="tablist" aria-label="Date range" className="flex items-center gap-1">
                {ranges.map((r) => (
                  <button
                    key={r}
                    type="button"
                    role="tab"
                    aria-selected={r === range}
                    onClick={() => setRange(r)}
                    className={cn(pill, "relative h-8 px-3 text-sm transition-colors", r === range ? "text-(--an-fg)" : "text-(--an-muted) hover:text-(--an-fg)")}
                  >
                    {r === range && <motion.span layoutId={`range-${id}`} transition={spring} className="absolute inset-0 rounded-full bg-(--an-card)" />}
                    <span className="relative">{r}</span>
                  </button>
                ))}
              </div>
            </div>
          </header>

          <AnimatePresence mode="wait" initial={false}>
            <motion.div
              key={range}
              initial={reduce ? false : { opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -6 }}
              transition={{ duration: 0.2 }}
              className="mt-8"
            >
              {/* stats: one bordered grid with hairline dividers */}
              <div className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border border-(--an-line) bg-(--an-line) @3xl:grid-cols-3">
                {d.stats.map((s) => {
                  const good = s.lowerIsBetter ? (s.delta ?? 0) < 0 : (s.delta ?? 0) > 0
                  const Arrow = (s.delta ?? 0) >= 0 ? ArrowUpRight : ArrowDownRight
                  return (
                    <div key={s.label} className="bg-(--an-bg) p-4">
                      <p className="text-xs text-(--an-muted)">{s.label}</p>
                      <p className="mt-1.5 text-2xl tabular-nums text-(--an-fg)">{s.value}</p>
                      <div className="mt-3 flex h-6 items-center justify-between gap-2">
                        {s.delta !== undefined ? (
                          <span className={cn("inline-flex items-center gap-0.5 text-xs tabular-nums", good ? "text-(--an-accent)" : "text-rose-500")}>
                            <Arrow className="size-3.5" />
                            {Math.abs(s.delta)}%
                          </span>
                        ) : (
                          <span />
                        )}
                        {s.spark && <Spark values={s.spark} />}
                      </div>
                    </div>
                  )
                })}
              </div>

              <section className="mt-6 rounded-2xl border border-(--an-line) p-4 @3xl:p-5">
                <div className="mb-5 flex items-center justify-between">
                  <h2 className="text-sm text-(--an-fg)">Visitors</h2>
                  <Legend />
                </div>
                <VisitorsChart points={d.points} />
              </section>

              {d.uniques && (
                <section className="mt-6 rounded-2xl border border-(--an-line) p-4 @3xl:p-5">
                  <div className="mb-5 flex items-center justify-between">
                    <h2 className="text-sm text-(--an-fg)">Visitors vs unique</h2>
                    <div className="flex items-center gap-3 text-xs text-(--an-muted)">
                      <span className="inline-flex items-center gap-1.5">
                        <span className="size-1.5 rounded-full bg-(--an-accent)" />
                        Visitors
                      </span>
                      <span className="inline-flex items-center gap-1.5">
                        <span className="size-1.5 rounded-full bg-[#60a5fa]" />
                        Unique
                      </span>
                    </div>
                  </div>
                  <CompareChart points={d.points} uniques={d.uniques} theme={current} />
                </section>
              )}

              <div className="mt-6">
                <TrafficHealth points={d.points} />
              </div>

              <div className="mt-10 grid gap-10 @3xl:grid-cols-2">
                <BarList title="Top pages" rows={d.pages} />
                <BarList title="Sources" rows={d.sources} />
                <BarList title="Countries" rows={d.countries} />
                <Devices rows={d.devices} />
              </div>
            </motion.div>
          </AnimatePresence>
        </div>
      </div>
    </div>
  )
}