{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "usage-alerts",
  "title": "Usage alerts",
  "description": "Metered usage bars with forecast overlays and threshold markers, alert rules with channels and toggles, a new-rule dialog and a simulate-a-day button that fires alerts.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/alert.json",
    "https://goodui.dev/r/badge.json",
    "https://goodui.dev/r/button.json",
    "https://goodui.dev/r/dialog.json",
    "https://goodui.dev/r/number-flow.json",
    "https://goodui.dev/r/number-input.json",
    "https://goodui.dev/r/select.json",
    "https://goodui.dev/r/switch.json",
    "https://goodui.dev/r/toggle-group.json",
    "label"
  ],
  "files": [
    {
      "path": "registry/blocks/billing/usage-alerts.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { Bell, BellRing, Database, Hash, Mail, MessageSquare, Plus, Trash2, TrendingUp, Zap } from \"lucide-react\"\nimport { Label } from \"@/components/ui/label\"\nimport { Alert } from \"@/components/goodui/alert\"\nimport { Badge } from \"@/components/goodui/badge\"\nimport { Button } from \"@/components/goodui/button\"\nimport { Dialog } from \"@/components/goodui/dialog\"\nimport { NumberInput } from \"@/components/goodui/number-input\"\nimport { Select } from \"@/components/goodui/select\"\nimport { Switch } from \"@/components/goodui/switch\"\nimport { ToggleGroup, ToggleGroupItem } from \"@/components/goodui/toggle-group\"\nimport { NumberFlow } from \"@/components/goodui/number-flow\"\nimport { cn } from \"@/lib/utils\"\n\n/* ---------- Demo data ---------- */\n\ntype MetricId = \"sms\" | \"bookings\" | \"storage\" | \"api\"\ntype Metric = { id: MetricId; label: string; unit: string; used: number; limit: number; perDay: number; icon: React.ComponentType<{ className?: string }>; format?: (n: number) => string }\ntype Channel = \"email\" | \"slack\" | \"sms\"\ntype Rule = { id: string; metric: MetricId; threshold: number; channels: Channel[]; enabled: boolean; fired?: boolean }\n\nconst METRICS: Metric[] = [\n  { id: \"sms\", label: \"SMS reminders\", unit: \"messages\", used: 1_640, limit: 2_000, perDay: 95, icon: MessageSquare },\n  { id: \"bookings\", label: \"Bookings\", unit: \"this month\", used: 412, limit: 1_000, perDay: 18, icon: Zap },\n  { id: \"storage\", label: \"Storage\", unit: \"GB\", used: 7.2, limit: 10, perDay: 0.12, icon: Database, format: (n) => `${n.toFixed(1)} GB` },\n  { id: \"api\", label: \"API calls\", unit: \"requests\", used: 38_900, limit: 100_000, perDay: 2_400, icon: TrendingUp },\n]\n\nconst INITIAL_RULES: Rule[] = [\n  { id: \"r1\", metric: \"sms\", threshold: 80, channels: [\"email\", \"slack\"], enabled: true, fired: true },\n  { id: \"r2\", metric: \"sms\", threshold: 95, channels: [\"email\", \"sms\"], enabled: true },\n  { id: \"r3\", metric: \"storage\", threshold: 90, channels: [\"email\"], enabled: true },\n  { id: \"r4\", metric: \"api\", threshold: 75, channels: [\"slack\"], enabled: false },\n]\n\nconst CHANNEL_META: Record<Channel, { label: string; icon: React.ComponentType<{ className?: string }> }> = {\n  email: { label: \"Email\", icon: Mail },\n  slack: { label: \"Slack\", icon: Hash },\n  sms: { label: \"SMS\", icon: MessageSquare },\n}\nconst DAY_IN_MONTH = 19\nconst DAYS_IN_MONTH = 30\n\nconst fmt = (m: Metric, n: number) => (m.format ? m.format(n) : Math.round(n).toLocaleString(\"en-US\"))\n\n/* ---------- Pieces ---------- */\n\nfunction UsageBar({ m, rules, day }: { m: Metric; rules: Rule[]; day: number }) {\n  const pct = Math.min(100, (m.used / m.limit) * 100)\n  const forecast = Math.min(100, ((m.used + m.perDay * (DAYS_IN_MONTH - day)) / m.limit) * 100)\n  const tone = pct >= 95 ? \"danger\" : pct >= 80 ? \"warning\" : \"ok\"\n  const willExceed = forecast >= 100\n  return (\n    <div className=\"rounded-2xl border bg-card p-4 shadow-sm\">\n      <div className=\"flex items-start justify-between gap-3\">\n        <div className=\"flex items-center gap-2.5\">\n          <span className={cn(\"flex size-9 items-center justify-center rounded-xl\", tone === \"danger\" ? \"bg-rose-500/10 text-rose-600 dark:text-rose-400\" : tone === \"warning\" ? \"bg-amber-500/10 text-amber-700 dark:text-amber-300\" : \"bg-muted text-muted-foreground\")}>\n            <m.icon className=\"size-4\" />\n          </span>\n          <div>\n            <p className=\"text-sm font-medium\">{m.label}</p>\n            <p className=\"text-xs text-muted-foreground\">\n              {fmt(m, m.used)} of {fmt(m, m.limit)} {m.format ? \"\" : m.unit}\n            </p>\n          </div>\n        </div>\n        <p className={cn(\"font-heading text-xl font-semibold tabular-nums\", tone === \"danger\" ? \"text-rose-600 dark:text-rose-400\" : tone === \"warning\" ? \"text-amber-700 dark:text-amber-300\" : \"\")}>\n          <NumberFlow value={Math.round(pct)} suffix=\"%\" />\n        </p>\n      </div>\n      <div className=\"relative mt-4 h-3 rounded-full bg-muted\" role=\"progressbar\" aria-valuenow={Math.round(pct)} aria-valuemin={0} aria-valuemax={100} aria-label={`${m.label} usage`}>\n        {/* forecast */}\n        <div className=\"absolute inset-y-0 left-0 rounded-full bg-[repeating-linear-gradient(90deg,transparent_0_4px,color-mix(in_oklab,var(--foreground)_18%,transparent)_4px_8px)] transition-all duration-700\" style={{ width: `${forecast}%` }} aria-hidden=\"true\" />\n        {/* used */}\n        <div className={cn(\"absolute inset-y-0 left-0 rounded-full transition-all duration-700\", tone === \"danger\" ? \"bg-rose-500\" : tone === \"warning\" ? \"bg-amber-500\" : \"bg-primary\")} style={{ width: `${pct}%` }} />\n        {/* thresholds */}\n        {rules\n          .filter((r) => r.metric === m.id && r.enabled)\n          .map((r) => (\n            <span key={r.id} className=\"absolute -top-1 -bottom-1 w-0.5 bg-foreground/70\" style={{ left: `${r.threshold}%` }} title={`Alert at ${r.threshold}%`} aria-hidden=\"true\">\n              <span className=\"absolute -top-4 left-1/2 -translate-x-1/2 text-[10px] font-medium tabular-nums text-muted-foreground\">{r.threshold}</span>\n            </span>\n          ))}\n      </div>\n      <p className=\"mt-3 flex items-center gap-1.5 text-xs text-muted-foreground\">\n        <TrendingUp className=\"size-3.5\" />\n        {willExceed ? (\n          <span className=\"text-rose-600 dark:text-rose-400\">On pace to run out around day {Math.max(day + 1, Math.ceil(day + (m.limit - m.used) / m.perDay))}. Dotted bar shows the forecast.</span>\n        ) : (\n          <>\n            Forecast {Math.round(forecast)}% by month end at {fmt(m, m.perDay)}/day.\n          </>\n        )}\n      </p>\n    </div>\n  )\n}\n\n/* ---------- Block ---------- */\n\nexport default function UsageAlerts() {\n  const [metrics, setMetrics] = React.useState(METRICS)\n  const [rules, setRules] = React.useState(INITIAL_RULES)\n  const [day, setDay] = React.useState(DAY_IN_MONTH)\n  const [events, setEvents] = React.useState<{ id: string; text: string }[]>([{ id: \"e0\", text: \"SMS reminders crossed 80% · emailed billing@novasalon.co and posted to #ops\" }])\n  const [addOpen, setAddOpen] = React.useState(false)\n  const [draft, setDraft] = React.useState<{ metric: string | null; threshold: number | null; channels: string[] }>({ metric: \"bookings\", threshold: 80, channels: [\"email\"] })\n  const [autoTopUp, setAutoTopUp] = React.useState(false)\n\n  const simulateDay = () => {\n    const nextDay = Math.min(DAYS_IN_MONTH, day + 1)\n    setDay(nextDay)\n    const next = metrics.map((m) => ({ ...m, used: Math.min(m.limit, m.used + m.perDay * (0.8 + Math.random() * 0.5)) }))\n    setMetrics(next)\n    const fired: string[] = []\n    setRules((rs) =>\n      rs.map((r) => {\n        const m = next.find((x) => x.id === r.metric)!\n        const pct = (m.used / m.limit) * 100\n        if (r.enabled && !r.fired && pct >= r.threshold) {\n          fired.push(`${m.label} crossed ${r.threshold}% · sent by ${r.channels.map((c) => CHANNEL_META[c].label).join(\", \")}`)\n          return { ...r, fired: true }\n        }\n        return r\n      }),\n    )\n    if (fired.length) setEvents((e) => [...fired.map((text, i) => ({ id: `e${Date.now()}${i}`, text })), ...e].slice(0, 4))\n  }\n\n  const addRule = () => {\n    if (!draft.metric || !draft.threshold) throw new Error(\"Pick a metric and a threshold\")\n    if (draft.channels.length === 0) throw new Error(\"Choose at least one channel\")\n    setRules((rs) => [...rs, { id: `r${Date.now()}`, metric: draft.metric as MetricId, threshold: draft.threshold ?? 80, channels: draft.channels as Channel[], enabled: true }])\n  }\n\n  const metricOptions = METRICS.map((m) => ({ value: m.id, label: m.label }))\n\n  return (\n    <div className=\"p-4 md:p-6\">\n      <div className=\"mx-auto max-w-5xl\">\n        <div className=\"flex flex-wrap items-end justify-between gap-3\">\n          <div>\n            <h2 className=\"font-heading text-xl font-semibold tracking-tight\">Usage & alerts</h2>\n            <p className=\"text-sm text-muted-foreground\">\n              Day {day} of {DAYS_IN_MONTH} · Studio plan · resets 1 April.\n            </p>\n          </div>\n          <div className=\"flex gap-2\">\n            <Button variant=\"outline\" tone=\"neutral\" iconLeft={<TrendingUp />} onClick={simulateDay} disabled={day >= DAYS_IN_MONTH}>\n              Simulate a day\n            </Button>\n            <Button iconLeft={<Plus />} onClick={() => setAddOpen(true)}>\n              New alert\n            </Button>\n          </div>\n        </div>\n\n        {/* Fired alerts */}\n        <div className=\"mt-4 grid gap-2\" aria-live=\"polite\">\n          {events.map((e, i) => (\n            <Alert key={e.id} tone={i === 0 ? \"warning\" : \"neutral\"} variant=\"left-accent\" size=\"sm\" icon={<BellRing className=\"size-4\" />} dismissible onDismiss={() => setEvents((list) => list.filter((x) => x.id !== e.id))} animation={i === 0 ? \"slide-down\" : \"none\"}>\n              {e.text}\n            </Alert>\n          ))}\n        </div>\n\n        {/* Meters */}\n        <div className=\"mt-4 grid gap-4 md:grid-cols-2\">\n          {metrics.map((m) => (\n            <UsageBar key={m.id} m={m} rules={rules} day={day} />\n          ))}\n        </div>\n\n        {/* Rules */}\n        <div className=\"mt-6 grid gap-5 lg:grid-cols-[1fr_300px]\">\n          <section aria-labelledby=\"ua-rules\" className=\"min-w-0 rounded-2xl border bg-card shadow-sm\">\n            <div className=\"flex items-center justify-between gap-3 border-b px-5 py-3\">\n              <h3 id=\"ua-rules\" className=\"flex items-center gap-2 font-heading text-base font-semibold\">\n                <Bell className=\"size-4\" /> Alert rules\n              </h3>\n              <span className=\"text-xs text-muted-foreground\">{rules.filter((r) => r.enabled).length} active</span>\n            </div>\n            <ul className=\"divide-y\">\n              {rules.map((r) => {\n                const m = METRICS.find((x) => x.id === r.metric)!\n                return (\n                  <li key={r.id} className={cn(\"flex items-center gap-3 px-5 py-3\", !r.enabled && \"text-muted-foreground\")}>\n                    <Switch size=\"sm\" checked={r.enabled} onCheckedChange={(v) => setRules((rs) => rs.map((x) => (x.id === r.id ? { ...x, enabled: v, fired: v ? x.fired : false } : x)))} aria-label={`${m.label} at ${r.threshold}%`} />\n                    <div className=\"min-w-0 flex-1\">\n                      <p className=\"text-sm\">\n                        <span className=\"font-medium\">{m.label}</span> <span className=\"text-foreground/70\">reaches</span> <span className=\"font-medium tabular-nums\">{r.threshold}%</span>\n                      </p>\n                      <div className=\"mt-1 flex flex-wrap items-center gap-1\">\n                        {r.channels.map((c) => {\n                          const C = CHANNEL_META[c]\n                          return (\n                            <Badge key={c} tone=\"neutral\" variant=\"outline\" size=\"xs\" icon={<C.icon className=\"size-3\" />}>\n                              {C.label}\n                            </Badge>\n                          )\n                        })}\n                        {r.fired && (\n                          <Badge tone=\"warning\" variant=\"dot\" size=\"xs\">\n                            Fired this month\n                          </Badge>\n                        )}\n                      </div>\n                    </div>\n                    <Button size=\"sm\" variant=\"ghost\" tone=\"danger\" iconOnly aria-label={`Delete rule for ${m.label} at ${r.threshold}%`} onClick={() => setRules((rs) => rs.filter((x) => x.id !== r.id))}>\n                      <Trash2 />\n                    </Button>\n                  </li>\n                )\n              })}\n              {rules.length === 0 && <li className=\"p-6 text-center text-sm text-muted-foreground\">No rules. You will only hear from us when something runs out.</li>}\n            </ul>\n          </section>\n\n          <div className=\"grid content-start gap-3\">\n            <Switch label=\"Auto top-up SMS\" description=\"Buy 500 messages for $10 whenever you hit 95%.\" labelPosition=\"left\" checked={autoTopUp} onCheckedChange={setAutoTopUp} className=\"rounded-2xl border bg-card p-4 shadow-sm\" tone=\"success\" />\n            <div className=\"rounded-2xl border border-dashed p-4 text-sm text-muted-foreground\">\n              <p className=\"font-medium text-foreground\">How alerts work</p>\n              <p className=\"mt-1\">Each rule fires once per billing month when usage crosses its line. The dotted bar is a forecast from your last 7 days.</p>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      <Dialog open={addOpen} onOpenChange={setAddOpen} title=\"New alert rule\" description=\"We notify you the moment usage crosses the threshold.\" icon={<Bell />} confirmText=\"Create rule\" onConfirm={addRule}>\n        <div className=\"grid gap-4\">\n          <div className=\"grid gap-1.5\">\n            <Label htmlFor=\"ua-metric\">Metric</Label>\n            <Select id=\"ua-metric\" options={metricOptions} value={draft.metric} onValueChange={(v) => setDraft((d) => ({ ...d, metric: v }))} className=\"w-full\" />\n          </div>\n          <NumberInput id=\"ua-threshold\" label=\"Threshold\" value={draft.threshold} onValueChange={(v) => setDraft((d) => ({ ...d, threshold: v }))} min={10} max={100} step={5} trailing=\"%\" fullWidth />\n          <div className=\"grid gap-1.5\">\n            <span className=\"text-sm font-medium\">Notify by</span>\n            <ToggleGroup type=\"multiple\" value={draft.channels} onValueChange={(v) => setDraft((d) => ({ ...d, channels: v }))} variant=\"outline\" size=\"sm\" aria-label=\"Channels\">\n              {(Object.keys(CHANNEL_META) as Channel[]).map((c) => {\n                const C = CHANNEL_META[c]\n                return (\n                  <ToggleGroupItem key={c} value={c} icon={<C.icon />}>\n                    {C.label}\n                  </ToggleGroupItem>\n                )\n              })}\n            </ToggleGroup>\n          </div>\n        </div>\n      </Dialog>\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/usage-alerts.tsx"
    }
  ],
  "categories": [
    "billing"
  ],
  "type": "registry:block"
}
