{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "glass-segmented",
  "type": "registry:component",
  "title": "Glass Segmented Control",
  "description": "A glass segmented control with a lens that slides between options.",
  "author": "Marcelo Treviño Velázquez <https://furin.dev>",
  "dependencies": [],
  "categories": [
    "Navigation"
  ],
  "docs": "Installed in components/furin/glass-segmented/. Docs, live controls and props table: https://furin.dev/components/glass-segmented/",
  "files": [
    {
      "path": "registry/glass-segmented/GlassSegmented.tsx",
      "content": "\"use client\";\nimport { useCallback, useEffect, useId, useRef, useState } from \"react\";\nimport type { CSSProperties } from \"react\";\nimport \"./GlassSegmented.css\";\n\n/* ---------- Refracción real (solo Chromium): mapa de desplazamiento generado en canvas ---------- */\n\n/** Solo Chromium acepta url(#filtro) dentro de backdrop-filter; el resto cae al desenfoque simple. */\nfunction canRefract(): boolean {\n  if (typeof CSS === \"undefined\" || typeof navigator === \"undefined\") return false;\n  return /Chrome\\//.test(navigator.userAgent) && CSS.supports(\"backdrop-filter\", \"url(#a)\");\n}\n\ninterface RefractionMap { url: string; scale: number; w: number; h: number }\n\n/** Mapa de desplazamiento: en el bisel la luz se curva hacia adentro y, con zoom > 1, el centro también amplía. */\nfunction buildRefractionMap(w: number, h: number, radius: number, bezel: number, zoom = 1): RefractionMap | null {\n  if (w < 4 || h < 4) return null;\n  const c = document.createElement(\"canvas\");\n  c.width = w;\n  c.height = h;\n  const ctx = c.getContext(\"2d\");\n  if (!ctx) return null;\n  const img = ctx.createImageData(w, h);\n  const vx = new Float32Array(w * h);\n  const vy = new Float32Array(w * h);\n  const hw = w / 2, hh = h / 2, r = Math.min(radius, hw, hh);\n  const k = 1 - 1 / zoom;\n  let max = 0.001;\n  for (let y = 0; y < h; y++) {\n    for (let x = 0; x < w; x++) {\n      const px = x + 0.5 - hw, py = y + 0.5 - hh;\n      const qx = Math.abs(px) - (hw - r), qy = Math.abs(py) - (hh - r);\n      const sdf = Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;\n      if (sdf > 0) continue;\n      let nx: number, ny: number;\n      if (qx > 0 && qy > 0) { const l = Math.hypot(qx, qy) || 1; nx = (Math.sign(px) * qx) / l; ny = (Math.sign(py) * qy) / l; }\n      else if (qx > qy) { nx = Math.sign(px); ny = 0; }\n      else { nx = 0; ny = Math.sign(py); }\n      const t = Math.min(1, -sdf / bezel);\n      const m = Math.pow(1 - t, 2.2) * bezel;\n      const dx = -nx * m - px * k, dy = -ny * m - py * k;\n      const i = y * w + x;\n      vx[i] = dx;\n      vy[i] = dy;\n      max = Math.max(max, Math.abs(dx), Math.abs(dy));\n    }\n  }\n  const d = img.data;\n  for (let i = 0; i < w * h; i++) {\n    d[i * 4] = Math.round(127.5 + (127.5 * vx[i]) / max);\n    d[i * 4 + 1] = Math.round(127.5 + (127.5 * vy[i]) / max);\n    d[i * 4 + 2] = 128;\n    d[i * 4 + 3] = 255;\n  }\n  ctx.putImageData(img, 0, 0);\n  return { url: c.toDataURL(\"image/png\"), scale: max * 2, w, h };\n}\n\n/** Mide el elemento y mantiene su mapa de refracción al día (solo si el navegador lo soporta). */\nfunction useRefractionMap(ref: React.RefObject<HTMLElement | null>, radius: number, bezel: number, zoom = 1): RefractionMap | null {\n  const [mapa, setMapa] = useState<RefractionMap | null>(null);\n  useEffect(() => {\n    if (!canRefract()) return;\n    const el = ref.current;\n    if (!el) return;\n    let raf = 0;\n    const run = () => {\n      const m = buildRefractionMap(el.offsetWidth, el.offsetHeight, radius, bezel, zoom);\n      if (m) setMapa((p) => (p && p.w === m.w && p.h === m.h ? p : m));\n    };\n    const ro = new ResizeObserver(() => { cancelAnimationFrame(raf); raf = requestAnimationFrame(run); });\n    ro.observe(el);\n    run();\n    return () => { ro.disconnect(); cancelAnimationFrame(raf); };\n  }, [ref, radius, bezel, zoom]);\n  return mapa;\n}\n\n/** Filtro SVG: desenfoque, desplazamiento por el mapa y saturación; con dispersión separa los canales RGB como un cristal real. */\nfunction RefractionFilter({ id, mapa, strength, blur = 0, saturate = 1.6, dispersion = 0 }: { id: string; mapa: RefractionMap; strength: number; blur?: number; saturate?: number; dispersion?: number }) {\n  const s = mapa.scale * strength;\n  const disp = (scale: number, result: string) => (\n    <feDisplacementMap in=\"src\" in2=\"mapa\" scale={scale} xChannelSelector=\"R\" yChannelSelector=\"G\" result={result} />\n  );\n  return (\n    <svg width=\"0\" height=\"0\" style={{ position: \"absolute\" }} aria-hidden=\"true\" focusable=\"false\">\n      <filter id={id} x=\"0\" y=\"0\" width={mapa.w} height={mapa.h} filterUnits=\"userSpaceOnUse\" colorInterpolationFilters=\"sRGB\">\n        <feImage href={mapa.url} x=\"0\" y=\"0\" width={mapa.w} height={mapa.h} preserveAspectRatio=\"none\" result=\"mapa\" />\n        <feGaussianBlur in=\"SourceGraphic\" stdDeviation={Math.max(blur, 0.01)} result=\"src\" />\n        {dispersion > 0 ? (\n          <>\n            {disp(s * (1 + dispersion), \"dr\")}\n            <feColorMatrix in=\"dr\" type=\"matrix\" values=\"1 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 1 0\" result=\"r\" />\n            {disp(s, \"dg\")}\n            <feColorMatrix in=\"dg\" type=\"matrix\" values=\"0 0 0 0 0  0 1 0 0 0  0 0 0 0 0  0 0 0 1 0\" result=\"g\" />\n            {disp(s * (1 - dispersion), \"db\")}\n            <feColorMatrix in=\"db\" type=\"matrix\" values=\"0 0 0 0 0  0 0 0 0 0  0 0 1 0 0  0 0 0 1 0\" result=\"b\" />\n            <feBlend in=\"r\" in2=\"g\" mode=\"screen\" result=\"rg\" />\n            <feBlend in=\"rg\" in2=\"b\" mode=\"screen\" result=\"rgb\" />\n          </>\n        ) : (\n          disp(s, \"rgb\")\n        )}\n        <feColorMatrix in=\"rgb\" type=\"saturate\" values={String(saturate)} />\n      </filter>\n    </svg>\n  );\n}\n\n/** Valor de backdrop-filter: el filtro SVG si hay refracción; desenfoque + saturación si no. */\nfunction glassBackdrop(id: string, mapa: RefractionMap | null, blur: number, saturate = 1.6): string {\n  return mapa ? `url(#${id})` : `blur(${blur}px) saturate(${saturate}) brightness(1.06)`;\n}\n\n\nexport interface GlassSegmentedProps {\n  /** Textos de las opciones. */\n  options?: string[];\n  /** Opción elegida (modo controlado). */\n  value?: string;\n  /** Opción inicial (modo no controlado). */\n  defaultValue?: string;\n  /** Se llama al elegir otra opción. */\n  onChange?: (value: string) => void;\n  /** Etiqueta accesible del grupo. */\n  label?: string;\n  /** Cuánto amplía la lente lo que hay debajo (1 = nada). */\n  zoom?: number;\n  /** Desenfoque del fondo en el riel, en px. */\n  blur?: number;\n  /** Fuerza de la refracción de la lente (0 = sin curvar la luz). */\n  refraction?: number;\n  /** Rigidez del resorte de la lente: más alto es más seco. */\n  stiffness?: number;\n  /** Segundos entre cambios automáticos (0 = apagado; se detiene al interactuar). */\n  autoplay?: number;\n  /** Pinta una escena de color animada detrás (para verlo refractar). */\n  scene?: boolean;\n  /** Clase extra para el contenedor. */\n  className?: string;\n  /** Estilos extra para el contenedor. */\n  style?: CSSProperties;\n}\n\nconst PAD = 5;\nconst HEIGHT = 56;\n\n/** Control segmentado de vidrio: una lente que se desliza con resorte y amplía la opción elegida. */\nexport function GlassSegmented({\n  options = [\"Day\", \"Week\", \"Month\", \"Year\"],\n  value,\n  defaultValue,\n  onChange,\n  label = \"Options\",\n  zoom = 1.22,\n  blur = 10,\n  refraction = 1,\n  stiffness = 320,\n  autoplay = 0,\n  scene = false,\n  className = \"\",\n  style,\n}: GlassSegmentedProps) {\n  const n = Math.max(options.length, 1);\n  const [interno, setInterno] = useState(defaultValue ?? options[0]);\n  const actual = value ?? interno;\n  const idx = Math.max(options.indexOf(actual), 0);\n  const lente = useRef<HTMLDivElement>(null);\n  const botones = useRef<(HTMLButtonElement | null)[]>([]);\n  const tocado = useRef(false);\n  const fid = \"furin-glass-segmented-\" + useId().replace(/[^a-zA-Z0-9]/g, \"\");\n  const mapa = useRefractionMap(lente, (HEIGHT - PAD * 2) / 2, 9, zoom);\n\n  const elegir = useCallback(\n    (op: string) => {\n      if (value === undefined) setInterno(op);\n      onChange?.(op);\n    },\n    [value, onChange],\n  );\n\n  // Resorte de la lente: posición en \"segmentos\", con velocidad; la lente se estira al correr.\n  const fisica = useRef({ x: idx, v: 0, raf: 0, t: 0 });\n  const objetivo = useRef(idx);\n  objetivo.current = idx;\n  useEffect(() => {\n    const el = lente.current;\n    if (!el) return;\n    const f = fisica.current;\n    const quieto = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const pinta = () => {\n      const sx = 1 + Math.min(0.2, Math.abs(f.v) * 0.045);\n      const sy = 1 - Math.min(0.1, Math.abs(f.v) * 0.02);\n      el.style.transform = `translateX(${(f.x * 100).toFixed(3)}%) scale(${sx.toFixed(3)}, ${sy.toFixed(3)})`;\n      el.style.setProperty(\"--furin-glass-segmented-lit\", String(Math.min(1, Math.abs(f.v) * 0.25).toFixed(2)));\n    };\n    const tick = (t: number) => {\n      const dt = Math.min(0.032, (t - f.t) / 1000 || 0.016);\n      f.t = t;\n      const k = stiffness, c = 2 * Math.sqrt(k) * 0.62;\n      for (let i = 0; i < 2; i++) {\n        const a = k * (objetivo.current - f.x) - c * f.v;\n        f.v += a * (dt / 2);\n        f.x += f.v * (dt / 2);\n      }\n      pinta();\n      if (Math.abs(objetivo.current - f.x) < 0.0008 && Math.abs(f.v) < 0.004) {\n        f.x = objetivo.current;\n        f.v = 0;\n        pinta();\n        f.raf = 0;\n        return;\n      }\n      f.raf = requestAnimationFrame(tick);\n    };\n    if (quieto) { f.x = objetivo.current; f.v = 0; pinta(); return; }\n    f.t = performance.now();\n    if (!f.raf) f.raf = requestAnimationFrame(tick);\n    return () => { cancelAnimationFrame(f.raf); f.raf = 0; };\n  }, [idx, stiffness]);\n\n  // Cambio automático para la demo; deja de hacerlo en cuanto la persona toca el control.\n  useEffect(() => {\n    if (!autoplay || options.length < 2) return;\n    const id = window.setInterval(() => {\n      if (tocado.current || document.hidden) return;\n      const i = (objetivo.current + 1) % options.length;\n      if (value === undefined) setInterno(options[i]);\n      onChange?.(options[i]);\n    }, autoplay * 1000);\n    return () => window.clearInterval(id);\n  }, [autoplay, options, value, onChange]);\n\n  const tecla = (e: React.KeyboardEvent, i: number) => {\n    let j = i;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") j = (i + 1) % n;\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") j = (i - 1 + n) % n;\n    else if (e.key === \"Home\") j = 0;\n    else if (e.key === \"End\") j = n - 1;\n    else return;\n    e.preventDefault();\n    tocado.current = true;\n    elegir(options[j]);\n    botones.current[j]?.focus();\n  };\n\n  const vars = { \"--furin-glass-segmented-n\": n, \"--furin-glass-segmented-pad\": `${PAD}px`, \"--furin-glass-segmented-h\": `${HEIGHT}px` } as CSSProperties;\n  const back = glassBackdrop(fid, mapa, 0.4, 1.4);\n  return (\n    <>\n      {scene ? <Scene /> : null}\n      {mapa ? <RefractionFilter id={fid} mapa={mapa} strength={refraction} blur={0.4} saturate={1.4} dispersion={0.03} /> : null}\n      <div role=\"radiogroup\" aria-label={label} className={`furin-glass-segmented ${className}`} style={{ ...vars, ...style }} onPointerDown={() => { tocado.current = true; }}>\n        <span className=\"furin-glass-segmented__riel\" style={{ backdropFilter: `blur(${blur}px) saturate(1.5)`, WebkitBackdropFilter: `blur(${blur}px) saturate(1.5)` }} />\n        {options.map((op, i) => (\n          <button\n            key={op}\n            ref={(el) => { botones.current[i] = el; }}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={i === idx}\n            tabIndex={i === idx ? 0 : -1}\n            className={`furin-glass-segmented__op${i === idx ? \" is-on\" : \"\"}`}\n            onClick={() => elegir(op)}\n            onKeyDown={(e) => tecla(e, i)}\n          >\n            {op}\n          </button>\n        ))}\n        <div ref={lente} className=\"furin-glass-segmented__lente\" aria-hidden=\"true\">\n          <span className=\"furin-glass-segmented__cristal\" style={{ backdropFilter: back, WebkitBackdropFilter: back }} />\n          <span className=\"furin-glass-segmented__rim\" />\n        </div>\n      </div>\n    </>\n  );\n}\n\nfunction Scene() {\n  return (\n    <div className=\"furin-glass-segmented-scene\" aria-hidden=\"true\">\n      <i /><i /><i /><i /><b />\n    </div>\n  );\n}\n\nexport default GlassSegmented;\n",
      "type": "registry:component",
      "target": "components/furin/glass-segmented/GlassSegmented.tsx"
    },
    {
      "path": "registry/glass-segmented/GlassSegmented.css",
      "content": ".furin-glass-segmented {\n  position: relative;\n  z-index: 1;\n  display: grid;\n  grid-template-columns: repeat(var(--furin-glass-segmented-n), minmax(78px, 1fr));\n  height: var(--furin-glass-segmented-h);\n  padding: var(--furin-glass-segmented-pad);\n  border-radius: 999px;\n  font-family: Geist, system-ui, -apple-system, sans-serif;\n  color: #fff;\n  touch-action: manipulation;\n}\n.furin-glass-segmented__riel {\n  position: absolute;\n  inset: 0;\n  border-radius: inherit;\n  background: linear-gradient(180deg, rgba(10, 14, 50, 0.32), rgba(10, 14, 50, 0.12));\n  /* Riel hundido: sombra interior arriba, luz fina abajo. */\n  box-shadow:\n    inset 0 2px 6px rgba(5, 8, 30, 0.45),\n    inset 0 -1px 0 rgba(255, 255, 255, 0.28),\n    0 10px 20px -10px rgba(5, 8, 30, 0.5),\n    0 0 0 1px rgba(255, 255, 255, 0.08);\n}\n.furin-glass-segmented__op {\n  position: relative;\n  z-index: 1;\n  border: 0;\n  background: none;\n  padding: 0 14px;\n  color: rgba(255, 255, 255, 0.66);\n  font-family: inherit;\n  font-size: 15px;\n  font-weight: 600;\n  line-height: 1;\n  letter-spacing: -0.005em;\n  cursor: pointer;\n  border-radius: 999px;\n  outline: none;\n  transition: color 0.25s;\n  -webkit-tap-highlight-color: transparent;\n}\n.furin-glass-segmented__op:hover { color: rgba(255, 255, 255, 0.9); }\n.furin-glass-segmented__op.is-on { color: #fff; }\n.furin-glass-segmented__op:focus-visible { box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.7); }\n.furin-glass-segmented__lente {\n  --furin-glass-segmented-lit: 0;\n  position: absolute;\n  z-index: 2;\n  top: var(--furin-glass-segmented-pad);\n  bottom: var(--furin-glass-segmented-pad);\n  left: var(--furin-glass-segmented-pad);\n  width: calc((100% - var(--furin-glass-segmented-pad) * 2) / var(--furin-glass-segmented-n));\n  border-radius: 999px;\n  pointer-events: none;\n  transform-origin: center;\n}\n.furin-glass-segmented__cristal {\n  position: absolute;\n  inset: 0;\n  border-radius: inherit;\n  background:\n    linear-gradient(165deg, rgba(255, 255, 255, calc(0.3 + var(--furin-glass-segmented-lit) * 0.15)), rgba(255, 255, 255, 0.05) 55%, rgba(255, 255, 255, 0.14)),\n    rgba(255, 255, 255, 0.06);\n  box-shadow:\n    0 8px 14px -6px rgba(5, 8, 30, 0.55),\n    0 2px 4px rgba(5, 8, 30, 0.3),\n    inset 0 -6px 10px -4px rgba(255, 255, 255, 0.3),\n    inset 0 8px 10px -8px rgba(255, 255, 255, 0.55);\n}\n.furin-glass-segmented__rim {\n  position: absolute;\n  inset: 0;\n  border-radius: inherit;\n  padding: 1.3px;\n  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.1) 32%, rgba(255, 255, 255, 0.04) 62%, rgba(255, 255, 255, 0.6));\n  -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);\n  -webkit-mask-composite: xor;\n  mask: linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0);\n}\n@media (prefers-reduced-motion: reduce) { .furin-glass-segmented__op { transition: none; } }\n\n/* Escena de color: formas con borde nítido para que la refracción se note (solo se pinta con scene). */\n.furin-glass-segmented-scene { position: absolute; inset: 0; z-index: 0; overflow: hidden; pointer-events: none; background: linear-gradient(160deg, #0d1236 0%, #1b0f3d 55%, #0b2335 100%); }\n.furin-glass-segmented-scene i { position: absolute; border-radius: 50%; animation: furin-glass-segmented-flota var(--t, 14s) ease-in-out infinite alternate; }\n.furin-glass-segmented-scene i:nth-child(1) { --t: 13s; --dx: 80px; --dy: 40px; width: 190px; height: 190px; left: 6%; top: 10%; background: radial-gradient(circle at 32% 28%, #ffd0ea 0, #ff5aa5 42%, #c21f78 100%); }\n.furin-glass-segmented-scene i:nth-child(2) { --t: 17s; --dx: -70px; --dy: -50px; width: 230px; height: 230px; right: 0%; top: 28%; background: radial-gradient(circle at 34% 30%, #bcd3ff, #4f7dff 45%, #2437c9); }\n.furin-glass-segmented-scene i:nth-child(3) { --t: 11s; --dx: 90px; --dy: -60px; width: 150px; height: 150px; left: 30%; bottom: -4%; background: radial-gradient(circle at 34% 30%, #d3fff3, #37e0b9 45%, #0a8e86); }\n.furin-glass-segmented-scene i:nth-child(4) { --t: 9s; --dx: -60px; --dy: 70px; width: 90px; height: 90px; right: 28%; top: 4%; background: radial-gradient(circle at 34% 30%, #fff2cc, #ffb347 50%, #e6700f); }\n.furin-glass-segmented-scene b { position: absolute; inset: -10% -14%; background: repeating-linear-gradient(105deg, transparent 0 44px, rgba(255, 255, 255, 0.22) 44px 47px); animation: furin-glass-segmented-lineas 12s ease-in-out infinite alternate; }\n@keyframes furin-glass-segmented-flota { to { transform: translate(var(--dx), var(--dy)) scale(1.1); } }\n@keyframes furin-glass-segmented-lineas { to { transform: translateX(-70px); } }\n@media (prefers-reduced-motion: reduce) { .furin-glass-segmented-scene i, .furin-glass-segmented-scene b { animation: none; } }\n",
      "type": "registry:file",
      "target": "components/furin/glass-segmented/GlassSegmented.css"
    }
  ]
}
