"use client";import * as React from "react";import { ArrowUpRight, Filter } from "lucide-react";import { NumberRoll } from "./number-roll";import { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS, useInteractionReducedMotion,} from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * METRIC BENTO — free MIT 3-cell asymmetric analytics bento * * cell 1 (left 5 cols, lit hero) headline KPI stack rolled * across 7d / 30d / 90d / 12m * cell 2 (top-right 7 cols) 4-channel interactive share * strip in --chart-1..4 * cell 3 (bottom-right 7 cols) filterable live event feed * with crisp category chips * ───────────────────────────────────────────────────────── */export interface MetricPeriod { id: string; label: string; headlineValue: number; headlinePrefix?: string; headlineSuffix?: string; headlineLabel: string; changeLabel: string; secondaryStats: [ { label: string; value: number; suffix?: string; decimals?: number }, { label: string; value: number; suffix?: string; decimals?: number }, ]; /** Percentage shares (sum = 100) aligned with `channels` */ channelShares: [number, number, number, number];}export interface MetricChannel { id: string; name: string; delta: string;}export interface MetricFeedRow { id: string; category: string; title: string; meta: string; value: string;}export interface MetricBentoProps extends Omit<React.HTMLAttributes<HTMLElement>, "title"> { eyebrow?: string; heading?: string; subheading?: string; periods?: MetricPeriod[]; channelsTitle?: string; channels?: [MetricChannel, MetricChannel, MetricChannel, MetricChannel]; feedTitle?: string; feedRows?: MetricFeedRow[]; accent?: string;}const DEFAULT_PERIODS: MetricPeriod[] = [ { id: "7d", label: "7d", headlineValue: 18420, headlineLabel: "Unique visitors", changeLabel: "+14.2% vs prior 7 days", secondaryStats: [ { label: "Pages / visit", value: 9.4, decimals: 1 }, { label: "Avg. duration", value: 274, suffix: "s" }, ], channelShares: [44, 28, 17, 11], }, { id: "30d", label: "30d", headlineValue: 74910, headlineLabel: "Unique visitors", changeLabel: "+28.6% vs prior 30 days", secondaryStats: [ { label: "Pages / visit", value: 10.2, decimals: 1 }, { label: "Avg. duration", value: 298, suffix: "s" }, ], channelShares: [49, 24, 16, 11], }, { id: "90d", label: "90d", headlineValue: 214600, headlineLabel: "Unique visitors", changeLabel: "+61.4% vs prior quarter", secondaryStats: [ { label: "Pages / visit", value: 9.8, decimals: 1 }, { label: "Avg. duration", value: 286, suffix: "s" }, ], channelShares: [52, 22, 15, 11], }, { id: "12m", label: "12m", headlineValue: 812400, headlineLabel: "Unique visitors", changeLabel: "+142% year over year", secondaryStats: [ { label: "Pages / visit", value: 10.6, decimals: 1 }, { label: "Avg. duration", value: 312, suffix: "s" }, ], channelShares: [56, 20, 14, 10], },];const DEFAULT_CHANNELS: [MetricChannel, MetricChannel, MetricChannel, MetricChannel] = [ { id: "search", name: "Organic search", delta: "+31%" }, { id: "direct", name: "Direct & CLI", delta: "+18%" }, { id: "social", name: "Social clips", delta: "+24%" }, { id: "referrals", name: "Directories", delta: "+12%" },];const DEFAULT_FEED: MetricFeedRow[] = [ { id: "f1", category: "Install", title: "Desktop app installed", meta: "San Francisco · 14s ago", value: "macOS" }, { id: "f2", category: "Signup", title: "New workspace verified", meta: "Berlin · 1m ago", value: "Free plan" }, { id: "f3", category: "Checkout", title: "Team plan, yearly", meta: "Bengaluru · 3m ago", value: "$480" }, { id: "f4", category: "Install", title: "iPhone app installed", meta: "Tokyo · 4m ago", value: "iOS" }, { id: "f5", category: "Checkout", title: "Pro plan, monthly", meta: "London · 7m ago", value: "$24" },];const SERIES_VARS = [ "var(--chart-1, var(--primary))", "var(--chart-2, var(--primary))", "var(--chart-3, var(--primary))", "var(--chart-4, var(--primary))",] as const;const DECIMAL_FORMATS: Record<number, Intl.NumberFormatOptions> = { 0: { maximumFractionDigits: 0 }, 1: { minimumFractionDigits: 1, maximumFractionDigits: 1 }, 2: { minimumFractionDigits: 2, maximumFractionDigits: 2 },};export function MetricBento({ eyebrow = "Analytics overview", heading = "Every number you check, on one surface.", subheading = "Switch time windows to roll traffic and engagement figures, inspect channel share, and filter live product events.", periods = DEFAULT_PERIODS, channelsTitle = "Acquisition mix", channels = DEFAULT_CHANNELS, feedTitle = "Live product stream", feedRows = DEFAULT_FEED, accent = "var(--primary)", className = "", ...rest}: MetricBentoProps) { const reduced = useInteractionReducedMotion(); const [periodIdx, setPeriodIdx] = React.useState(1); const [hoveredChannel, setHoveredChannel] = React.useState<number | null>(null); const [category, setCategory] = React.useState("All"); const period = periods[periodIdx] ?? periods[0]; const categories = React.useMemo(() => ["All", ...new Set(feedRows.map((r) => r.category))], [feedRows]); const visibleRows = React.useMemo( () => (category === "All" ? feedRows : feedRows.filter((r) => r.category === category)), [feedRows, category], ); // Gliding solid-grey period thumb const tabRefs = React.useRef<(HTMLButtonElement | null)[]>([]); const [thumb, setThumb] = React.useState({ left: 0, width: 0, ready: false }); React.useLayoutEffect(() => { const btn = tabRefs.current[periodIdx]; if (!btn) return; const left = btn.offsetLeft; const width = btn.offsetWidth; setThumb((prev) => (prev.left === left && prev.width === width && prev.ready ? prev : { left, width, ready: true })); }, [periodIdx, periods.length]); const litHeroStyle: React.CSSProperties = { backgroundImage: `linear-gradient(160deg, color-mix(in oklab, ${accent} 10%, var(--card)) 0%, var(--card) 58%)`, boxShadow: `inset 0 1px 0 color-mix(in oklab, ${accent} 24%, transparent)`, }; return ( <section data-natural-width className={`grid w-full grid-cols-[minmax(0,1200px)] justify-center ${className}`} {...rest} > <div className="@container w-full"> <div className="rounded-[22px] border border-border bg-background p-4 @[36rem]:p-6 @[54rem]:p-8"> {/* Header + gliding period switcher */} <div className="flex flex-col gap-5 @[48rem]:flex-row @[48rem]:items-end @[48rem]:justify-between"> <div className="max-w-xl"> <p className="text-[13px] font-medium text-muted-foreground">{eyebrow}</p> <h2 className="mt-2 text-balance text-[26px] font-medium leading-[1.1] tracking-[-0.03em] text-foreground @[36rem]:text-[34px]"> {heading} </h2> <p className="mt-2.5 text-pretty text-[14.5px] leading-relaxed text-muted-foreground">{subheading}</p> </div> <div role="tablist" aria-label="Reporting window" className="relative inline-flex w-fit max-w-full shrink-0 items-center overflow-x-auto rounded-full border border-border bg-card p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" > <span aria-hidden="true" className="pointer-events-none absolute bottom-1 top-1 left-0 rounded-full bg-muted" style={{ width: thumb.width, transform: `translateX(${thumb.left}px)`, opacity: thumb.ready ? 1 : 0, transition: thumb.ready && !reduced ? `transform 340ms ${EASE_OUT}, width 280ms ${EASE_OUT}` : "none", }} /> {periods.map((p, i) => { const selected = i === periodIdx; return ( <button key={p.id} ref={(el) => { tabRefs.current[i] = el; }} type="button" role="tab" aria-selected={selected} onClick={() => setPeriodIdx(i)} className={`relative z-10 cursor-pointer whitespace-nowrap rounded-full px-3 py-1.5 text-[12.5px] font-medium tabular-nums transition-colors @[36rem]:text-[13px] ${INTERACTION_FOCUS} ${ selected ? "text-foreground" : "text-muted-foreground hover:text-foreground" }`} > {p.label} </button> ); })} </div> </div> {/* 3-cell asymmetric hairline frame */} <div className="mt-6 overflow-clip rounded-[18px] border border-border bg-card"> <div className="grid grid-cols-1 divide-y divide-border @[52rem]:grid-cols-12 @[52rem]:divide-x @[52rem]:divide-y-0"> {/* CELL 1 (5 cols): Lit hero KPI column */} <div style={litHeroStyle} className="flex flex-col justify-between p-5 @[36rem]:p-6 @[52rem]:col-span-5"> <div> <p className="text-[13px] font-medium text-muted-foreground">{period.headlineLabel}</p> <div className="mt-3 flex items-baseline gap-1 text-[44px] font-medium leading-none tracking-[-0.045em] text-foreground tabular-nums @[36rem]:text-[52px]"> {period.headlinePrefix && <span className="text-[28px] font-normal text-muted-foreground">{period.headlinePrefix}</span>} <NumberRoll value={period.headlineValue} /> {period.headlineSuffix && <span className="text-[20px] font-normal text-muted-foreground">{period.headlineSuffix}</span>} </div> <p className="mt-2.5 inline-flex items-center gap-1 text-[13px] font-medium text-emerald-600 dark:text-emerald-400"> <ArrowUpRight className="size-3.5" aria-hidden="true" /> <span>{period.changeLabel}</span> </p> </div> {/* Hairline secondary stats strip */} <dl className="mt-8 grid grid-cols-2 gap-4 border-t border-border pt-5"> {period.secondaryStats.map((stat) => ( <div key={stat.label}> <dt className="text-[12px] text-muted-foreground">{stat.label}</dt> <dd className="mt-1.5 flex items-baseline gap-0.5 text-[24px] font-medium leading-none tracking-[-0.03em] text-foreground tabular-nums"> <NumberRoll value={stat.value} format={DECIMAL_FORMATS[stat.decimals ?? 0] ?? DECIMAL_FORMATS[0]} /> {stat.suffix && <span className="text-[13px] font-normal text-muted-foreground">{stat.suffix}</span>} </dd> </div> ))} </dl> </div> {/* RIGHT 7 COLS: Stacked Share Strip + Filterable Stream */} <div className="flex min-w-0 flex-col divide-y divide-border @[52rem]:col-span-7"> {/* CELL 2: Interactive 4-channel comparison strip */} <div className="p-5 @[36rem]:p-6"> <div className="flex flex-wrap items-baseline justify-between gap-2"> <h3 className="text-[15.5px] font-medium tracking-[-0.015em] text-foreground">{channelsTitle}</h3> <span className="text-[12.5px] tabular-nums text-muted-foreground"> {hoveredChannel !== null ? `${channels[hoveredChannel].name} · ${period.channelShares[hoveredChannel]}% (${channels[hoveredChannel].delta})` : "Hover or focus a channel"} </span> </div> {/* Proportional 4-segment stacked bar */} <div role="list" aria-label="Channel share breakdown" className="mt-4 flex h-3 w-full gap-1 overflow-clip rounded-full bg-muted/50" > {channels.map((ch, i) => { const share = period.channelShares[i] ?? 25; const dimmed = hoveredChannel !== null && hoveredChannel !== i; return ( <button key={ch.id} type="button" aria-label={`${ch.name}: ${share}% (${ch.delta})`} onPointerEnter={() => setHoveredChannel(i)} onPointerLeave={() => setHoveredChannel(null)} onFocus={() => setHoveredChannel(i)} onBlur={() => setHoveredChannel(null)} className={`h-full cursor-pointer rounded-full transition-[width,opacity] duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none ${INTERACTION_FOCUS}`} style={{ width: `${share}%`, backgroundColor: SERIES_VARS[i], opacity: dimmed ? 0.28 : 1, }} /> ); })} </div> {/* Aligned channel legend */} <div className="mt-4 grid grid-cols-2 gap-2.5 @[36rem]:grid-cols-4"> {channels.map((ch, i) => { const share = period.channelShares[i] ?? 25; const focused = hoveredChannel === i; return ( <button key={ch.id} type="button" onPointerEnter={() => setHoveredChannel(i)} onPointerLeave={() => setHoveredChannel(null)} onFocus={() => setHoveredChannel(i)} onBlur={() => setHoveredChannel(null)} className={`flex min-w-0 cursor-pointer flex-col rounded-[10px] px-2.5 py-2 text-left transition-colors ${INTERACTION_FOCUS} ${ focused ? "bg-muted" : "hover:bg-muted/60" }`} > <span className="flex items-center gap-1.5 text-[12px] text-muted-foreground"> <span aria-hidden="true" className="h-[2px] w-2.5 rounded-full" style={{ backgroundColor: SERIES_VARS[i] }} /> <span className="truncate">{ch.name}</span> </span> <span className="mt-1 flex items-baseline gap-1.5 tabular-nums"> <span className="whitespace-nowrap text-[16px] font-medium text-foreground"> <NumberRoll value={share} />% </span> <span className="text-[11.5px] text-emerald-600 dark:text-emerald-400">{ch.delta}</span> </span> </button> ); })} </div> </div> {/* CELL 3: Filterable live event stream */} <div className="p-5 @[36rem]:p-6"> <div className="flex flex-wrap items-center justify-between gap-2.5"> <h3 className="flex items-center gap-2 text-[15.5px] font-medium tracking-[-0.015em] text-foreground"> <Filter className="size-3.5 text-muted-foreground" aria-hidden="true" /> <span>{feedTitle}</span> </h3> <div role="radiogroup" aria-label="Filter stream by type" className="flex flex-wrap items-center gap-1"> {categories.map((cat) => { const selected = cat === category; return ( <button key={cat} type="button" role="radio" aria-checked={selected} onClick={() => setCategory(cat)} className={`cursor-pointer rounded-full px-2.5 py-1 text-[12px] font-medium transition-colors ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${ selected ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-muted/60 hover:text-foreground" }`} > {cat} </button> ); })} </div> </div> <ul className="mt-4 divide-y divide-border/70 border-t border-border/70"> {visibleRows.map((row) => ( <li key={row.id} className="flex items-center justify-between gap-3 py-2.5 text-[13px]"> <div className="min-w-0"> <p className="truncate font-medium text-foreground">{row.title}</p> <p className="truncate text-[12px] text-muted-foreground"> {row.category} · {row.meta} </p> </div> <span className="shrink-0 rounded-full bg-muted px-2.5 py-0.5 font-mono text-[11.5px] tabular-nums text-foreground"> {row.value} </span> </li> ))} </ul> </div> </div> </div> </div> </div> </div> </section> );}