{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cohort",
  "type": "registry:ui",
  "title": "Cohort",
  "description": "Scripted multiplayer cursors over any content: named pointers glide on curved, slightly overshooting springs to percent or [data-cohort] targets, then click with ripples, drag selections, type comment bubbles and float emoji reactions — concurrently and on loop. Pauses politely when a real pointer enters, sleeps offscreen, and parks at first targets under reduced motion.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json",
    "https://crucibleui.com/r/use-visibility-pause.json"
  ],
  "files": [
    {
      "path": "registry/default/cursors/cohort/cohort.tsx",
      "type": "registry:ui",
      "target": "components/crucible/cohort.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, motionValue, useSpring, type MotionValue } from \"motion/react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { useVisibilityPause } from \"@/hooks/use-visibility-pause\";\n\n/** A point in percent of the container: `[x%, y%]`. */\nexport type CohortPoint = readonly [x: number, y: number];\n\n/** A rectangle in percent of the container: `[x%, y%, width%, height%]`. */\nexport type CohortRect = readonly [x: number, y: number, width: number, height: number];\n\n/**\n * Where a step points. Either percent coordinates, or a string: a bare name\n * (`\"title\"`) resolves to `[data-cohort=\"title\"]` inside the children; anything\n * else is used as a CSS selector scoped to the children. Unresolvable targets\n * fall back to the container centre.\n */\nexport type CohortTarget = string | CohortPoint | CohortRect;\n\n/** One step of a cursor's script. Durations are in ms (before `speedScale`). */\nexport type CohortStep =\n  | {\n      /** Glide to a target along a curved, slightly overshooting path. */\n      type: \"move\";\n      to: CohortTarget;\n      /** Point within an element/rect target, as fractions `[0..1, 0..1]`. @default [0.5, 0.5] */\n      anchor?: CohortPoint;\n      /** Travel time. @default derived from distance (~500–1500ms) */\n      duration?: number;\n    }\n  | {\n      /** Press: the pointer dips and a ripple rings out in the cursor's color. */\n      type: \"click\";\n    }\n  | {\n      /** Travel to the target's top-left, then drag a translucent selection over it. */\n      type: \"select\";\n      target: string | CohortRect;\n      /** Drag time. @default 700 */\n      duration?: number;\n    }\n  | {\n      /** A comment bubble beside the name pill types out `text`. */\n      type: \"type\";\n      text: string;\n      /** Typing time. @default 55ms per character */\n      duration?: number;\n      /** How long the finished comment stays before the next step. @default 900 */\n      hold?: number;\n    }\n  | {\n      /** An emoji floats up from the pointer and fades. */\n      type: \"react\";\n      emoji: string;\n    }\n  | {\n      /** Idle in place (with a subtle drift). */\n      type: \"wait\";\n      /** @default 900 */\n      duration?: number;\n    };\n\n/** One scripted collaborator. */\nexport interface CohortCursor {\n  /** Label shown in the name pill. */\n  name: string;\n  /** Pointer, pill, selection and ripple color (any CSS color). */\n  color: string;\n  /** Steps acted out in order; runs concurrently with the other cursors. */\n  script: CohortStep[];\n}\n\n/** Imperative controls exposed via `ref`. */\nexport interface CohortHandle {\n  /** Clear every selection/comment and replay all scripts from the intro. */\n  restart: () => void;\n}\n\nexport interface CohortProps\n  extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  /** The content the cursors perform over. Tag targets with `data-cohort=\"name\"`. */\n  children?: React.ReactNode;\n  /** The scripted collaborators (2–4 reads best). @default three cursors on a percent-based script */\n  cursors?: CohortCursor[];\n  /** Restart each script when it ends. @default true */\n  loop?: boolean;\n  /** Playback rate of every script. @default 1 */\n  speedScale?: number;\n  /** When the visitor's pointer enters, cursors finish their step then idle; they resume 1.5s after it leaves. @default true */\n  pauseOnPointer?: boolean;\n  /** Freeze the scripts where they are. @default false */\n  paused?: boolean;\n  /** Imperative handle — `restart()`. */\n  ref?: React.Ref<CohortHandle>;\n}\n\nconst DEFAULT_CURSORS: CohortCursor[] = [\n  {\n    name: \"Mara\",\n    color: \"#a5b4fc\",\n    script: [\n      { type: \"move\", to: [30, 28] },\n      { type: \"wait\", duration: 400 },\n      { type: \"select\", target: [16, 20, 42, 14] },\n      { type: \"type\", text: \"Tighten this intro?\" },\n      { type: \"move\", to: [66, 64] },\n      { type: \"click\" },\n      { type: \"react\", emoji: \"👍\" },\n      { type: \"wait\", duration: 1100 },\n    ],\n  },\n  {\n    name: \"Jun\",\n    color: \"#f9a8d4\",\n    script: [\n      { type: \"wait\", duration: 600 },\n      { type: \"move\", to: [72, 30] },\n      { type: \"click\" },\n      { type: \"wait\", duration: 500 },\n      { type: \"move\", to: [52, 72] },\n      { type: \"type\", text: \"Love this part\" },\n      { type: \"react\", emoji: \"✨\" },\n      { type: \"move\", to: [38, 82] },\n      { type: \"wait\", duration: 900 },\n    ],\n  },\n  {\n    name: \"Ola\",\n    color: \"#6ee7b7\",\n    script: [\n      { type: \"wait\", duration: 1200 },\n      { type: \"move\", to: [36, 62] },\n      { type: \"react\", emoji: \"🎉\" },\n      { type: \"wait\", duration: 700 },\n      { type: \"select\", target: [56, 42, 30, 16] },\n      { type: \"wait\", duration: 900 },\n      { type: \"move\", to: [78, 78] },\n      { type: \"click\" },\n      { type: \"wait\", duration: 1200 },\n    ],\n  },\n];\n\nconst INTRO_STAGGER = 0.35; // s between cursors fading in\nconst INTRO_FADE = 0.45; // s\nconst RESUME_DELAY = 1.5; // s after the real pointer leaves\nconst CLICK_MS = 320;\nconst PILL_SPRING = { stiffness: 170, damping: 22, mass: 0.9 };\n\n// Underdamped spring step response (ζ≈0.68 → ~5% overshoot), normalized to s∈[0,1].\nconst ZETA = 0.68;\nconst OMEGA = 10;\nconst OMEGA_D = OMEGA * Math.sqrt(1 - ZETA * ZETA);\nfunction springEase(s: number) {\n  if (s >= 1) return 1;\n  const e = Math.exp(-ZETA * OMEGA * s);\n  return 1 - e * (Math.cos(OMEGA_D * s) + ((ZETA * OMEGA) / OMEGA_D) * Math.sin(OMEGA_D * s));\n}\nconst easeInOut = (s: number) => (s < 0.5 ? 2 * s * s : 1 - Math.pow(-2 * s + 2, 2) / 2);\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));\n\n/** Pill text color: white on dark hex fills, near-black otherwise (non-hex colors keep the dark default). */\nfunction inkOn(color: string) {\n  const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim());\n  if (!m) return \"#0a0a0a\";\n  const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join(\"\") : m[1];\n  const [r, g, b] = [0, 2, 4].map((i) => {\n    const c = parseInt(h.slice(i, i + 2), 16) / 255;\n    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n  });\n  const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n  // Contrast vs white (1.05/(L+0.05)) beats contrast vs near-black ((L+0.05)/0.05) below L≈0.18.\n  return lum < 0.18 ? \"#ffffff\" : \"#0a0a0a\";\n}\n\nfunction hashString(str: string) {\n  let h = 2166136261;\n  for (let i = 0; i < str.length; i++) {\n    h ^= str.charCodeAt(i);\n    h = Math.imul(h, 16777619);\n  }\n  return h >>> 0;\n}\nfunction mulberry32(seed: number) {\n  let a = seed;\n  return () => {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\ntype Vec = { x: number; y: number };\ntype Box = { x: number; y: number; w: number; h: number };\n\n// Internal ops: `select` expands to a move to the top-left + a drag.\ntype Op =\n  | { k: \"move\"; to: CohortTarget; anchor: CohortPoint; dur?: number }\n  | { k: \"drag\"; target: string | CohortRect; dur: number }\n  | { k: \"click\" }\n  | { k: \"type\"; text: string; dur: number; hold: number }\n  | { k: \"react\"; emoji: string }\n  | { k: \"wait\"; dur: number };\n\nfunction compile(script: CohortStep[]): Op[] {\n  const ops: Op[] = [];\n  for (const s of script) {\n    switch (s.type) {\n      case \"move\":\n        ops.push({ k: \"move\", to: s.to, anchor: s.anchor ?? [0.5, 0.5], dur: s.duration });\n        break;\n      case \"select\":\n        ops.push({ k: \"move\", to: s.target, anchor: [0, 0] });\n        ops.push({ k: \"drag\", target: s.target, dur: s.duration ?? 700 });\n        break;\n      case \"click\":\n        ops.push({ k: \"click\" });\n        break;\n      case \"type\":\n        ops.push({ k: \"type\", text: s.text, dur: s.duration ?? s.text.length * 55, hold: s.hold ?? 900 });\n        break;\n      case \"react\":\n        ops.push({ k: \"react\", emoji: s.emoji });\n        break;\n      case \"wait\":\n        ops.push({ k: \"wait\", dur: s.duration ?? 900 });\n        break;\n    }\n  }\n  return ops;\n}\n\ninterface Runtime {\n  x: MotionValue<number>;\n  y: MotionValue<number>;\n  scale: MotionValue<number>;\n  opacity: MotionValue<number>;\n  selX: MotionValue<number>;\n  selY: MotionValue<number>;\n  selW: MotionValue<number>;\n  selH: MotionValue<number>;\n  selO: MotionValue<number>;\n  bubbleO: MotionValue<number>;\n  text: MotionValue<string>;\n  pillX?: MotionValue<number>;\n  pillY?: MotionValue<number>;\n  ops: Op[];\n  seed: number;\n  rng: () => number;\n  phase: \"intro\" | \"run\" | \"done\";\n  i: number;\n  /** Current step has finished; waiting for permission to start the next. */\n  pending: boolean;\n  stepStart: number;\n  base: Vec;\n  from: Vec;\n  to: Vec;\n  ctrl: Vec;\n  dur: number;\n  selTarget: number;\n  bubbleTarget: number;\n  drift: number;\n  driftPhase: number;\n  gen: number;\n  /** Last resolved destination spec, re-resolved on resize. */\n  rest: { to: CohortTarget; anchor: CohortPoint } | null;\n  selSpec: string | CohortRect | null;\n}\n\ninterface Fx {\n  id: number;\n  kind: \"ripple\" | \"react\";\n  x: number;\n  y: number;\n  color: string;\n  emoji?: string;\n}\n\nfunction isRect(t: CohortTarget): t is CohortRect {\n  return typeof t !== \"string\" && t.length === 4;\n}\n\n/**\n * Cohort — fake live collaboration for marketing heroes. A handful of named\n * pointers (arrow + name pill in their color) act out looping scripts over\n * the children: gliding along curved, slightly overshooting paths, clicking\n * with ripples, dragging translucent selections, typing comment bubbles and\n * floating emoji reactions. Scripts run concurrently; pointer positions are\n * driven by motion values (no per-frame React renders) and the name pill\n * trails on a softer spring. Targets resolve from percent coordinates or\n * `[data-cohort]` elements inside the children, measured relative to the\n * container and re-measured on resize. When the visitor's pointer enters,\n * cursors finish their current step and idle with a subtle drift, resuming\n * 1.5s after it leaves. The overlay is `aria-hidden` and pointer-transparent;\n * playback pauses offscreen and on hidden tabs. Under reduced motion the\n * cursors park at their first targets with their name pills — no motion.\n */\nexport function Cohort({\n  children,\n  className,\n  cursors = DEFAULT_CURSORS,\n  loop = true,\n  speedScale = 1,\n  pauseOnPointer = true,\n  paused = false,\n  ref,\n  onPointerEnter,\n  onPointerLeave,\n  ...props\n}: CohortProps) {\n  const reducedMotion = useReducedMotion();\n  const [fx, setFx] = React.useState<Fx[]>([]);\n  const fxId = React.useRef(0);\n\n  // Scripts are plain data: key on their content so inline literals don't reset playback.\n  const cursorsKey = JSON.stringify(cursors);\n  const scriptHash = hashString(cursorsKey);\n  const runtimes = React.useMemo<Runtime[]>(\n    () =>\n      cursors.map((c, idx) => {\n        const seed = hashString(`${c.name}:${idx}`);\n        const rng = mulberry32(seed);\n        return {\n          x: motionValue(0),\n          y: motionValue(0),\n          scale: motionValue(1),\n          opacity: motionValue(0),\n          selX: motionValue(0),\n          selY: motionValue(0),\n          selW: motionValue(0),\n          selH: motionValue(0),\n          selO: motionValue(0),\n          bubbleO: motionValue(0),\n          text: motionValue(\"\"),\n          ops: compile(c.script),\n          seed,\n          rng,\n          phase: \"intro\",\n          i: 0,\n          pending: true,\n          stepStart: 0,\n          base: { x: 0, y: 0 },\n          from: { x: 0, y: 0 },\n          to: { x: 0, y: 0 },\n          ctrl: { x: 0, y: 0 },\n          dur: 0,\n          selTarget: 0,\n          bubbleTarget: 0,\n          drift: 1,\n          driftPhase: rng() * Math.PI * 2,\n          gen: 0,\n          rest: null,\n          selSpec: null,\n        };\n      }),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [cursorsKey]\n  );\n\n  const live = React.useRef({\n    clock: 0,\n    real: 0,\n    last: -1,\n    inside: false,\n    leftAt: -Infinity,\n    size: { w: 0, h: 0 },\n    gen: 0,\n  });\n  const opts = React.useRef({ loop, speedScale, pauseOnPointer, cursors, reducedMotion });\n  opts.current = { loop, speedScale, pauseOnPointer, cursors, reducedMotion };\n\n  const containerRef = useVisibilityPause<HTMLDivElement>((elapsed) => tick(elapsed), {\n    paused: reducedMotion || paused,\n  });\n\n  // --- target resolution (container-relative px) -----------------------------\n  const resolveBox = React.useCallback((t: CohortTarget): Box => {\n    const { w, h } = live.current.size;\n    if (typeof t !== \"string\") {\n      if (isRect(t)) return { x: (t[0] / 100) * w, y: (t[1] / 100) * h, w: (t[2] / 100) * w, h: (t[3] / 100) * h };\n      return { x: (t[0] / 100) * w, y: (t[1] / 100) * h, w: 0, h: 0 };\n    }\n    const root = containerRef.current;\n    let el: Element | null = null;\n    if (root) {\n      const sel = /^[\\w-]+$/.test(t) ? `[data-cohort=\"${t}\"]` : t;\n      try {\n        el = root.querySelector(sel);\n      } catch {\n        el = null;\n      }\n    }\n    if (!root || !el) return { x: w / 2, y: h / 2, w: 0, h: 0 };\n    const rr = root.getBoundingClientRect();\n    const er = el.getBoundingClientRect();\n    return { x: er.left - rr.left, y: er.top - rr.top, w: er.width, h: er.height };\n  }, [containerRef]);\n\n  const resolvePoint = React.useCallback(\n    (t: CohortTarget, anchor: CohortPoint): Vec => {\n      const b = resolveBox(t);\n      return { x: b.x + b.w * anchor[0], y: b.y + b.h * anchor[1] };\n    },\n    [resolveBox]\n  );\n\n  const spawn = React.useCallback((f: Omit<Fx, \"id\">) => {\n    const id = ++fxId.current;\n    setFx((prev) => [...prev.slice(-11), { ...f, id }]);\n  }, []);\n\n  const teleport = (r: Runtime, p: Vec) => {\n    r.base = { ...p };\n    r.x.jump(p.x);\n    r.y.jump(p.y);\n    r.pillX?.jump(p.x);\n    r.pillY?.jump(p.y);\n  };\n\n  const clearMarks = (r: Runtime, hard: boolean) => {\n    r.selTarget = 0;\n    r.bubbleTarget = 0;\n    if (hard) {\n      r.selO.set(0);\n      r.bubbleO.set(0);\n      r.text.set(\"\");\n    }\n  };\n\n  const firstTarget = (r: Runtime) => {\n    const first = r.ops.find((o) => o.k === \"move\") as Extract<Op, { k: \"move\" }> | undefined;\n    return first ? { to: first.to, anchor: first.anchor } : null;\n  };\n\n  const measure = () => {\n    const el = containerRef.current;\n    if (!el) return;\n    const rect = el.getBoundingClientRect();\n    live.current.size = { w: rect.width, h: rect.height };\n  };\n\n  /** Park every cursor at its first target, fully visible (reduced motion / paused-from-start frame). */\n  const placeStatic = () => {\n    measure();\n    for (const r of runtimes) {\n      const t = firstTarget(r);\n      const p = t ? resolvePoint(t.to, t.anchor) : { x: live.current.size.w / 2, y: live.current.size.h / 2 };\n      teleport(r, p);\n      r.rest = t;\n      r.opacity.set(1);\n      r.scale.set(1);\n      clearMarks(r, true);\n      r.phase = \"run\";\n      r.i = 0;\n      r.pending = true;\n      r.drift = 1;\n    }\n  };\n\n  /** Fresh start: cursors wait offstage-adjacent, then fade in staggered and run. */\n  const reset = () => {\n    measure();\n    const L = live.current;\n    L.clock = 0;\n    L.last = -1;\n    for (const r of runtimes) {\n      r.rng = mulberry32(r.seed);\n      const t = firstTarget(r);\n      const p = t ? resolvePoint(t.to, t.anchor) : { x: L.size.w / 2, y: L.size.h / 2 };\n      const ang = r.rng() * Math.PI * 2;\n      const dist = 60 + r.rng() * 70;\n      teleport(r, {\n        x: clamp(p.x + Math.cos(ang) * dist, 12, Math.max(12, L.size.w - 60)),\n        y: clamp(p.y + Math.sin(ang) * dist, 12, Math.max(12, L.size.h - 40)),\n      });\n      r.rest = null;\n      r.selSpec = null;\n      r.opacity.set(0);\n      r.scale.set(1);\n      clearMarks(r, true);\n      r.phase = \"intro\";\n      r.i = 0;\n      r.pending = true;\n      r.drift = 1;\n      r.gen = L.gen;\n    }\n    setFx([]);\n  };\n\n  const beginStep = (r: Runtime, now: number) => {\n    const o = opts.current;\n    if (r.i >= r.ops.length) {\n      if (!o.loop || r.ops.length === 0) {\n        r.phase = \"done\";\n        return;\n      }\n      r.i = 0;\n      clearMarks(r, false);\n    }\n    const op = r.ops[r.i];\n    r.pending = false;\n    r.stepStart = now;\n    const color = o.cursors[runtimes.indexOf(r)]?.color ?? \"#fff\";\n    switch (op.k) {\n      case \"move\": {\n        clearMarks(r, false);\n        r.from = { ...r.base };\n        r.to = resolvePoint(op.to, op.anchor);\n        r.rest = { to: op.to, anchor: op.anchor };\n        const dx = r.to.x - r.from.x;\n        const dy = r.to.y - r.from.y;\n        const dist = Math.hypot(dx, dy);\n        const bend = dist * (0.12 + r.rng() * 0.16) * (r.rng() < 0.5 ? -1 : 1);\n        const nx = dist > 0 ? -dy / dist : 0;\n        const ny = dist > 0 ? dx / dist : 0;\n        r.ctrl = { x: (r.from.x + r.to.x) / 2 + nx * bend, y: (r.from.y + r.to.y) / 2 + ny * bend };\n        r.dur = op.dur ?? clamp(520 + dist * 0.9, 500, 1500);\n        if (dist < 3) r.dur = Math.min(r.dur, 200);\n        break;\n      }\n      case \"drag\": {\n        const b = resolveBox(op.target);\n        r.from = { x: b.x, y: b.y };\n        r.to = { x: b.x + b.w, y: b.y + b.h };\n        r.selSpec = op.target;\n        r.rest = { to: op.target, anchor: [1, 1] };\n        r.dur = op.dur;\n        r.selX.set(b.x);\n        r.selY.set(b.y);\n        r.selW.set(0);\n        r.selH.set(0);\n        r.selO.set(0);\n        r.selTarget = 1;\n        break;\n      }\n      case \"click\":\n        r.dur = CLICK_MS;\n        spawn({ kind: \"ripple\", x: r.base.x, y: r.base.y, color });\n        break;\n      case \"type\":\n        r.text.set(\"\");\n        r.bubbleTarget = 1;\n        r.dur = op.dur + op.hold;\n        break;\n      case \"react\":\n        r.dur = 520;\n        spawn({ kind: \"react\", x: r.base.x, y: r.base.y, color, emoji: op.emoji });\n        break;\n      case \"wait\":\n        r.dur = op.dur;\n        break;\n    }\n  };\n\n  function tick(elapsed: number) {\n    const L = live.current;\n    const o = opts.current;\n    const dt = L.last < 0 ? 0 : clamp(elapsed - L.last, 0, 0.1);\n    L.last = elapsed;\n    L.real += dt;\n    L.clock += dt * Math.max(0, o.speedScale);\n    const now = L.clock;\n    const smooth = 1 - Math.exp(-dt * 9);\n    const canAdvance = !o.pauseOnPointer || (!L.inside && L.real - L.leftAt >= RESUME_DELAY);\n\n    runtimes.forEach((r, idx) => {\n      // Re-measure after a resize: snap parked cursors / retarget the live move.\n      if (r.gen !== L.gen) {\n        r.gen = L.gen;\n        const op = r.ops[r.i];\n        if (!r.pending && op?.k === \"move\") {\n          r.to = resolvePoint(op.to, op.anchor);\n        } else if (r.rest && !(op?.k === \"drag\" && !r.pending)) {\n          r.base = resolvePoint(r.rest.to, r.rest.anchor);\n        }\n        if (r.selSpec && r.selTarget > 0 && !(op?.k === \"drag\" && !r.pending)) {\n          const b = resolveBox(r.selSpec);\n          r.selX.set(b.x);\n          r.selY.set(b.y);\n          r.selW.set(b.w);\n          r.selH.set(b.h);\n        }\n      }\n\n      if (r.phase === \"intro\") {\n        const t = now - idx * INTRO_STAGGER;\n        r.opacity.set(clamp(t / INTRO_FADE, 0, 1));\n        if (t >= INTRO_FADE) r.phase = \"run\";\n      }\n\n      let moving = false;\n      if (r.phase === \"run\") {\n        if (r.pending && canAdvance) beginStep(r, now);\n        const op = r.ops[r.i];\n        if (r.phase === \"run\" && !r.pending && op) {\n          const ms = (now - r.stepStart) * 1000;\n          const s = r.dur > 0 ? ms / r.dur : 1;\n          switch (op.k) {\n            case \"move\": {\n              moving = true;\n              const p = springEase(Math.min(s, 1));\n              const q = 1 - p;\n              r.base =\n                s >= 1\n                  ? { ...r.to }\n                  : {\n                      x: q * q * r.from.x + 2 * q * p * r.ctrl.x + p * p * r.to.x,\n                      y: q * q * r.from.y + 2 * q * p * r.ctrl.y + p * p * r.to.y,\n                    };\n              break;\n            }\n            case \"drag\": {\n              moving = true;\n              const e = easeInOut(clamp(s, 0, 1));\n              r.base = { x: r.from.x + (r.to.x - r.from.x) * e, y: r.from.y + (r.to.y - r.from.y) * e };\n              r.selW.set(Math.max(0, r.base.x - r.from.x));\n              r.selH.set(Math.max(0, r.base.y - r.from.y));\n              break;\n            }\n            case \"click\":\n              r.scale.set(1 - 0.18 * Math.sin(Math.PI * clamp(s, 0, 1)));\n              break;\n            case \"type\": {\n              const n = Math.floor(op.text.length * clamp(op.dur > 0 ? ms / op.dur : 1, 0, 1));\n              if (r.text.get().length !== n) r.text.set(op.text.slice(0, n));\n              break;\n            }\n            default:\n              break;\n          }\n          if (s >= 1) {\n            if (op.k === \"click\") r.scale.set(1);\n            r.i += 1;\n            r.pending = true;\n            if (canAdvance) beginStep(r, now);\n          }\n        }\n      }\n\n      // Subtle human drift whenever the pointer isn't travelling.\n      r.drift += ((moving ? 0 : 1) - r.drift) * (1 - Math.exp(-dt * 3));\n      const ph = r.driftPhase;\n      const dx = Math.sin(L.real * 0.9 + ph) * 3.2 * r.drift;\n      const dy = Math.sin(L.real * 1.3 + ph * 1.7) * 2.4 * r.drift;\n      r.x.set(r.base.x + dx);\n      r.y.set(r.base.y + dy);\n\n      r.selO.set(r.selO.get() + (r.selTarget - r.selO.get()) * smooth);\n      const bo = r.bubbleO.get() + (r.bubbleTarget - r.bubbleO.get()) * smooth;\n      r.bubbleO.set(bo);\n      if (r.bubbleTarget === 0 && bo < 0.02 && r.text.get() !== \"\") r.text.set(\"\");\n    });\n  }\n\n  // Mount / script change / motion preference: lay out the opening frame.\n  React.useLayoutEffect(() => {\n    if (reducedMotion) placeStatic();\n    else if (paused && live.current.clock === 0) placeStatic();\n    else if (live.current.clock === 0) reset();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [runtimes, reducedMotion]);\n\n  React.useEffect(() => {\n    if (paused && !reducedMotion && live.current.clock === 0) placeStatic();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [paused]);\n\n  // Container-relative measurement: re-measure on resize; ticks re-resolve targets.\n  React.useEffect(() => {\n    const el = containerRef.current;\n    if (!el || typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(() => {\n      measure();\n      live.current.gen += 1;\n      if (opts.current.reducedMotion) placeStatic();\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [runtimes]);\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      restart: () => {\n        if (opts.current.reducedMotion) placeStatic();\n        else reset();\n      },\n    }),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [runtimes]\n  );\n\n  const removeFx = React.useCallback((id: number) => {\n    setFx((prev) => prev.filter((f) => f.id !== id));\n  }, []);\n\n  return (\n    <div\n      ref={containerRef}\n      data-crucible=\"cohort\"\n      className={cn(\"relative isolate\", className)}\n      onPointerEnter={(e) => {\n        live.current.inside = true;\n        onPointerEnter?.(e);\n      }}\n      onPointerLeave={(e) => {\n        live.current.inside = false;\n        live.current.leftAt = live.current.real;\n        onPointerLeave?.(e);\n      }}\n      {...props}\n    >\n      {children}\n      <div aria-hidden className=\"pointer-events-none absolute inset-0 z-30 select-none\">\n        {runtimes.map((r, i) => {\n          const c = cursors[i];\n          if (!c) return null;\n          return (\n            <motion.div\n              key={`sel-${i}`}\n              className=\"absolute left-0 top-0 rounded-[3px]\"\n              style={{\n                x: r.selX,\n                y: r.selY,\n                width: r.selW,\n                height: r.selH,\n                opacity: r.selO,\n                backgroundColor: `color-mix(in srgb, ${c.color} 16%, transparent)`,\n                boxShadow: `inset 0 0 0 1px color-mix(in srgb, ${c.color} 55%, transparent)`,\n              }}\n            />\n          );\n        })}\n        {fx.map((f) =>\n          f.kind === \"ripple\" ? (\n            <motion.span\n              key={f.id}\n              className=\"absolute block size-9 rounded-full\"\n              style={{ left: f.x - 18, top: f.y - 18, boxShadow: `0 0 0 1.5px ${f.color}` }}\n              initial={{ scale: 0.2, opacity: 0.9 }}\n              animate={{ scale: 1.1, opacity: 0 }}\n              transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}\n              onAnimationComplete={() => removeFx(f.id)}\n            />\n          ) : (\n            <motion.span\n              key={f.id}\n              className=\"absolute block text-xl leading-none\"\n              style={{ left: f.x + 6, top: f.y - 22 }}\n              initial={{ y: 0, opacity: 0, scale: 0.6 }}\n              animate={{ y: -58, opacity: [0, 1, 1, 0], scale: [0.6, 1.15, 1, 0.95] }}\n              transition={{ duration: 1.5, ease: \"easeOut\", times: [0, 0.18, 0.7, 1] }}\n              onAnimationComplete={() => removeFx(f.id)}\n            >\n              {f.emoji}\n            </motion.span>\n          )\n        )}\n        {runtimes.map((r, i) => {\n          const c = cursors[i];\n          if (!c) return null;\n          return <CohortPointer key={`ptr-${scriptHash}-${i}`} runtime={r} cursor={c} still={reducedMotion} />;\n        })}\n      </div>\n    </div>\n  );\n}\n\nfunction CohortPointer({ runtime: r, cursor, still }: { runtime: Runtime; cursor: CohortCursor; still: boolean }) {\n  const springX = useSpring(r.x, PILL_SPRING);\n  const springY = useSpring(r.y, PILL_SPRING);\n  React.useLayoutEffect(() => {\n    r.pillX = springX;\n    r.pillY = springY;\n    springX.jump(r.x.get());\n    springY.jump(r.y.get());\n    return () => {\n      r.pillX = undefined;\n      r.pillY = undefined;\n    };\n  }, [r, springX, springY]);\n\n  const pillX = still ? r.x : springX;\n  const pillY = still ? r.y : springY;\n\n  return (\n    <>\n      <motion.div\n        className=\"absolute left-0 top-0\"\n        style={{ x: pillX, y: pillY, opacity: r.opacity }}\n      >\n        <div className=\"absolute left-[13px] top-[19px] flex flex-col items-start gap-1\">\n          <span\n            className=\"whitespace-nowrap rounded-full px-2 py-[3px] text-[11px] font-medium leading-none shadow-[0_2px_8px_rgba(0,0,0,0.35)]\"\n            style={{ backgroundColor: cursor.color, color: inkOn(cursor.color) }}\n          >\n            {cursor.name}\n          </span>\n          <motion.div\n            className=\"w-max max-w-[190px] rounded-xl rounded-tl-sm border border-white/10 bg-neutral-900/95 px-2.5 py-1.5 text-xs leading-snug text-neutral-100 shadow-[0_6px_20px_rgba(0,0,0,0.45)]\"\n            style={{ opacity: r.bubbleO }}\n          >\n            <motion.span>{r.text}</motion.span>\n            <span\n              className=\"ml-px inline-block h-[0.9em] w-px translate-y-[0.12em] animate-pulse\"\n              style={{ backgroundColor: cursor.color }}\n            />\n          </motion.div>\n        </div>\n      </motion.div>\n      <motion.div\n        className=\"absolute left-0 top-0\"\n        style={{ x: r.x, y: r.y, scale: r.scale, opacity: r.opacity, transformOrigin: \"0px 0px\" }}\n      >\n        <svg\n          width=\"20\"\n          height=\"22\"\n          viewBox=\"0 0 20 22\"\n          className=\"-ml-[2px] -mt-[2px] block drop-shadow-[0_2px_4px_rgba(0,0,0,0.45)]\"\n        >\n          <path\n            d=\"M2 2 L2 18.5 L6.4 14.6 L9.3 21 L12.1 19.8 L9.3 13.5 L15.2 13.2 Z\"\n            fill={cursor.color}\n            stroke=\"rgba(10,10,10,0.85)\"\n            strokeWidth=\"1.1\"\n            strokeLinejoin=\"round\"\n          />\n        </svg>\n      </motion.div>\n    </>\n  );\n}\n"
    }
  ]
}