'use client';

// Grid Voice Orb — NiceUI (MIT) · https://niceui.dev/c/ai-agents/grid-orb
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useEffect, useRef, useState, type RefObject, type ReactNode, createElement, type SVGProps } from 'react';

function cn(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(' ');
}

// Icons from Lucide (ISC licence, lucide.dev), inlined so there is nothing to install.
type NiceIconProps = SVGProps<SVGSVGElement> & { size?: number | string; absoluteStrokeWidth?: boolean };
type LucideIcon = (props: NiceIconProps) => JSX.Element;
type LucideProps = NiceIconProps;
const niceIcon = (node: Array<[string, Record<string, string>]>): LucideIcon =>
  function Icon({ size = 24, strokeWidth = 2, absoluteStrokeWidth, children, ...rest }: NiceIconProps) {
    const sw = absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth;
    return createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, ...rest }, ...node.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })), children);
  };
const Brain = niceIcon([["path",{"d":"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}],["path",{"d":"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}],["path",{"d":"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}],["path",{"d":"M17.599 6.5a3 3 0 0 0 .399-1.375"}],["path",{"d":"M6.003 5.125A3 3 0 0 0 6.401 6.5"}],["path",{"d":"M3.477 10.896a4 4 0 0 1 .585-.396"}],["path",{"d":"M19.938 10.5a4 4 0 0 1 .585.396"}],["path",{"d":"M6 18a4 4 0 0 1-1.967-.516"}],["path",{"d":"M19.967 17.484A4 4 0 0 1 18 18"}]]);
const Circle = niceIcon([["circle",{"cx":"12","cy":"12","r":"10"}]]);
const Mic = niceIcon([["path",{"d":"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}],["path",{"d":"M19 10v2a7 7 0 0 1-14 0v-2"}],["line",{"x1":"12","x2":"12","y1":"19","y2":"22"}]]);
const MicOff = niceIcon([["line",{"x1":"2","x2":"22","y1":"2","y2":"22"}],["path",{"d":"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2"}],["path",{"d":"M5 10v2a7 7 0 0 0 12 5"}],["path",{"d":"M15 9.34V5a3 3 0 0 0-5.68-1.33"}],["path",{"d":"M9 9v3a3 3 0 0 0 5.12 2.12"}],["line",{"x1":"12","x2":"12","y1":"19","y2":"22"}]]);
const Volume2 = niceIcon([["path",{"d":"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{"d":"M16 9a5 5 0 0 1 0 6"}],["path",{"d":"M19.364 18.364a9 9 0 0 0 0-12.728"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = "@keyframes fade-up{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\n.animate-fade-up{animation:fade-up 400ms cubic-bezier(0.16,1,0.3,1) both}\n@keyframes shimmer{from{background-position:200% 0}to{background-position:-200% 0}}\n.animate-shimmer{animation:shimmer 2.4s linear infinite}\n.focus-ring{outline:none}.focus-ring:focus-visible{box-shadow:0 0 0 2px #000,0 0 0 4px rgba(14,165,233,.6)}\n.shimmer-text{background:linear-gradient(90deg,#6b6b77 0%,#6b6b77 40%,#f7f7f8 50%,#6b6b77 60%,#6b6b77 100%);background-size:200% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shimmer 2.4s linear infinite}";
if (typeof document !== 'undefined' && !document.getElementById('niceui-css-lw7c5r')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-lw7c5r';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/ai/voice/engine.ts ───────────────────────────────
type VoiceState = 'idle' | 'listening' | 'thinking' | 'speaking';

/** One frame of voice: overall loudness and 16 frequency bands, all 0..1. */
type VoiceFrame = { level: number; bands: Float32Array; state: VoiceState; t: number };

const BANDS = 16;

/** Smooth, speech-like loudness for each state when there is no live audio. */
function simulate(state: VoiceState, t: number) {
  const n = (Math.sin(t * 7.3) + Math.sin(t * 13.1 + 1.7) * 0.6 + Math.sin(t * 23.7 + 0.4) * 0.35) / 1.95;
  switch (state) {
    case 'speaking': {
      // syllables inside phrases, with short breaths between phrases
      const syl = Math.pow(Math.max(0, Math.sin(t * Math.PI * 4.1 + Math.sin(t * 1.3) * 2.2)), 0.55);
      const phrase = Math.sin(t * 0.72 + 0.4) > -0.55 ? 1 : 0.12;
      return (0.18 + syl * 0.72 + n * 0.1) * phrase;
    }
    case 'listening': {
      const syl = Math.pow(Math.max(0, Math.sin(t * Math.PI * 3.3 + Math.sin(t * 0.9) * 2.6)), 0.8);
      const phrase = Math.sin(t * 0.55 + 2) > -0.35 ? 1 : 0.2;
      return (0.1 + syl * 0.42 + n * 0.08) * phrase;
    }
    case 'thinking':
      return 0.16 + Math.sin(t * 3.2) * 0.06 + n * 0.03;
    default:
      return 0.06 + Math.sin(t * 1.3) * 0.03;
  }
}

/**
 * Drives an orb from a live microphone or a simulated voice.
 * `sample(now)` is cheap and meant to be called once per animation frame.
 */
function useVoice(state: VoiceState, opts: { mic?: boolean; level?: number } = {}) {
  const stateRef = useRef(state);
  stateRef.current = state;
  const levelRef = useRef(opts.level);
  levelRef.current = opts.level;
  const analyser = useRef<AnalyserNode | null>(null);
  const bins = useRef<Uint8Array | null>(null);
  const [micError, setMicError] = useState<string | null>(null);
  const [micLive, setMicLive] = useState(false);

  const frame = useRef<VoiceFrame>({ level: 0, bands: new Float32Array(BANDS), state, t: 0 });
  const raw = useRef(new Float32Array(BANDS));

  useEffect(() => {
    if (!opts.mic) return;
    let stream: MediaStream | null = null;
    let ctx: AudioContext | null = null;
    let cancelled = false;
    setMicError(null);
    (async () => {
      try {
        if (!navigator.mediaDevices?.getUserMedia) throw new Error('This browser has no microphone access.');
        stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } });
        if (cancelled) return stream.getTracks().forEach((tr) => tr.stop());
        ctx = new AudioContext();
        const node = ctx.createAnalyser();
        node.fftSize = 512;
        node.smoothingTimeConstant = 0.6;
        ctx.createMediaStreamSource(stream).connect(node);
        analyser.current = node;
        bins.current = new Uint8Array(node.frequencyBinCount);
        setMicLive(true);
      } catch (e) {
        setMicError(e instanceof Error && e.name === 'NotAllowedError' ? 'Microphone permission was denied.' : e instanceof Error ? e.message : 'Microphone unavailable.');
      }
    })();
    return () => {
      cancelled = true;
      analyser.current = null;
      setMicLive(false);
      stream?.getTracks().forEach((tr) => tr.stop());
      ctx?.close().catch(() => {});
    };
  }, [opts.mic]);

  const last = useRef(0);
  const sample = (now: number): VoiceFrame => {
    const t = now / 1000;
    const dt = Math.min(0.05, last.current ? t - last.current : 0.016);
    last.current = t;
    const f = frame.current;
    const st = stateRef.current;
    const r = raw.current;
    let target: number;

    const node = analyser.current;
    if (node && bins.current) {
      node.getByteFrequencyData(bins.current);
      const b = bins.current;
      // speech lives roughly in the first ~60 bins (0–5.5 kHz at 48 kHz / 512)
      let sum = 0;
      for (let i = 0; i < BANDS; i++) {
        const a = Math.floor(Math.pow(i / BANDS, 1.6) * 60) + 1;
        const z = Math.floor(Math.pow((i + 1) / BANDS, 1.6) * 60) + 2;
        let s = 0;
        for (let k = a; k < z; k++) s += b[k];
        r[i] = Math.min(1, (s / (z - a) / 255) * 1.5);
        sum += r[i];
      }
      target = Math.min(1, (sum / BANDS) * 1.9);
    } else {
      target = levelRef.current ?? simulate(st, t);
      for (let i = 0; i < BANDS; i++) {
        const shape = 1 - Math.abs(i / (BANDS - 1) - 0.32) * 0.9;
        r[i] = Math.max(0, target * shape * (0.55 + 0.45 * Math.sin(t * (3.1 + i * 0.83) + i * 1.9)));
      }
    }

    // fast attack, slower release, like a VU meter
    const k = target > f.level ? 18 : 5;
    f.level += (target - f.level) * Math.min(1, dt * k);
    for (let i = 0; i < BANDS; i++) {
      const kk = r[i] > f.bands[i] ? 20 : 6;
      f.bands[i] += (r[i] - f.bands[i]) * Math.min(1, dt * kk);
    }
    f.state = node ? 'listening' : st;
    f.t = t;
    return f;
  };

  return { sample, micError, micLive };
}

/**
 * A HiDPI canvas loop that pauses off-screen and slows for reduced motion.
 * `draw` receives the 2D context in CSS pixels and the frame time.
 */
function useCanvasLoop(
  ref: RefObject<HTMLCanvasElement | null>,
  size: number,
  draw: (g: CanvasRenderingContext2D, now: number, slow: number) => void,
  opts: { dpr?: number } = {},
) {
  const drawRef = useRef(draw);
  drawRef.current = draw;
  useEffect(() => {
    const c = ref.current;
    if (!c) return;
    const dpr = opts.dpr ?? Math.min(2, window.devicePixelRatio || 1);
    c.width = Math.round(size * dpr);
    c.height = Math.round(size * dpr);
    const g = c.getContext('2d');
    if (!g) return;
    g.setTransform(dpr, 0, 0, dpr, 0, 0);
    const slow = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 0.35 : 1;
    let raf = 0;
    let visible = true;
    const loop = (now: number) => {
      raf = 0;
      if (!visible) return;
      drawRef.current(g, now, slow);
      raf = requestAnimationFrame(loop);
    };
    const io = new IntersectionObserver(([e]) => {
      visible = e.isIntersecting;
      if (visible && !raf) raf = requestAnimationFrame(loop);
    });
    io.observe(c);
    raf = requestAnimationFrame(loop);
    return () => {
      io.disconnect();
      cancelAnimationFrame(raf);
    };
  }, [ref, size, opts.dpr]);
}

/** Hex → [r, g, b]. */
function rgb(hex: string): [number, number, number] {
  const v = parseInt(hex.replace('#', ''), 16);
  return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
}

/** Mix two RGB colours. */
const mixRgb = (a: [number, number, number], b: [number, number, number], t: number): [number, number, number] => [
  a[0] + (b[0] - a[0]) * t,
  a[1] + (b[1] - a[1]) * t,
  a[2] + (b[2] - a[2]) * t,
];

/** Smoothly eases a value toward the target for the current state, so state changes never snap. */
function easer() {
  const vals: Record<string, number> = {};
  return (key: string, target: number, dt: number, rate = 3) => {
    const v = vals[key] ?? target;
    const n = v + (target - v) * Math.min(1, dt * rate);
    vals[key] = n;
    return n;
  };
}

// ── components/ai/voice/VoiceStage.tsx ──────────────────────────
const STATES: Array<{ id: VoiceState; label: string; icon: typeof Mic; caption: string }> = [
  { id: 'idle', label: 'Idle', icon: Circle, caption: 'Tap the orb to talk' },
  { id: 'listening', label: 'Listening', icon: Mic, caption: 'Listening…' },
  { id: 'thinking', label: 'Thinking', icon: Brain, caption: 'Thinking…' },
  { id: 'speaking', label: 'Speaking', icon: Volume2, caption: '“Sure — I moved your 3pm to Thursday.”' },
];

/**
 * Demo shell for the voice orbs: a state switcher, a live-mic toggle and a caption.
 * It cycles through the states on its own until you pick one.
 */
function VoiceStage({
  children,
  className,
}: {
  children: (p: { state: VoiceState; mic: boolean; setMicError: (e: string | null) => void; toggle: () => void }) => ReactNode;
  className?: string;
}) {
  const [state, setState] = useState<VoiceState>('speaking');
  const [auto, setAuto] = useState(true);
  const [mic, setMic] = useState(false);
  const [micError, setMicError] = useState<string | null>(null);

  useEffect(() => {
    if (!auto) return;
    const order: VoiceState[] = ['speaking', 'listening', 'thinking', 'speaking', 'idle'];
    let i = 0;
    const id = window.setInterval(() => {
      i = (i + 1) % order.length;
      setState(order[i]);
    }, 3600);
    return () => window.clearInterval(id);
  }, [auto]);

  const pick = (s: VoiceState) => {
    setAuto(false);
    setMic(false);
    setState(s);
  };
  const toggle = () => pick(state === 'idle' ? 'listening' : 'idle');
  const index = STATES.findIndex((s) => s.id === state);
  const caption = mic && !micError ? 'Live microphone — say something' : STATES[index].caption;

  return (
    <div className={cn('flex flex-col items-center gap-7', className)}>
      {children({ state: mic ? 'listening' : state, mic, setMicError, toggle })}
      <p key={caption} className={cn('h-5 animate-fade-up text-center text-sm', state === 'thinking' && !mic ? 'shimmer-text font-medium' : 'text-[#a3a8b0]')}>
        {micError ?? caption}
      </p>
      <div className="flex flex-wrap items-center justify-center gap-2">
        <div role="radiogroup" aria-label="Voice state" className="relative grid grid-cols-4 rounded-xl bg-[#0b0c0e] p-1 shadow-[0_0_0_1px_rgba(255,255,255,0.06),0_1px_2px_rgba(0,0,0,0.4),0_8px_24px_-8px_rgba(0,0,0,0.5)]">
          <span
            aria-hidden
            className={cn('absolute inset-y-1 left-1 w-[calc((100%-8px)/4)] rounded-lg bg-[#1c1e22] shadow-[0_0_0_1px_rgba(255,255,255,0.06)] transition-all duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)]', mic && 'opacity-0')}
            style={{ transform: `translateX(${index * 100}%)` }}
          />
          {STATES.map(({ id, label, icon: Icon }) => (
            <button
              key={id}
              role="radio"
              aria-checked={!mic && state === id}
              onClick={() => pick(id)}
              className={cn(
                'focus-ring relative z-10 flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-xs font-medium transition-colors sm:px-3.5',
                !mic && state === id ? 'text-[#f3f4f6]' : 'text-[#8b9099] hover:text-[#c9cdd3]',
              )}
            >
              <Icon className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">{label}</span>
            </button>
          ))}
        </div>
        <button
          onClick={() => {
            setAuto(false);
            setMicError(null);
            setMic((m) => !m);
          }}
          aria-pressed={mic}
          className={cn(
            'focus-ring flex h-[42px] items-center gap-1.5 rounded-xl px-3.5 text-xs font-medium shadow-[0_0_0_1px_rgba(255,255,255,0.06),0_1px_2px_rgba(0,0,0,0.4),0_8px_24px_-8px_rgba(0,0,0,0.5)] transition-colors',
            mic ? 'bg-[#0ea5e9] text-[#000000] hover:bg-[#38bdf8]' : 'bg-[#0b0c0e] text-[#a3a8b0] hover:text-[#f3f4f6]',
          )}
        >
          {mic ? <MicOff className="h-3.5 w-3.5" /> : <Mic className="h-3.5 w-3.5" />}
          {mic ? 'Stop mic' : 'Use my mic'}
        </button>
      </div>
    </div>
  );
}

// ── components/ai/voice/GridOrb.tsx ─────────────────────────────
const TARGET: Record<VoiceState, { spin: number; twist: number; bulge: number; pulse: number }> = {
  idle: { spin: 0.15, twist: 0, bulge: 0.2, pulse: 0 },
  listening: { spin: 0.25, twist: 0, bulge: 0.75, pulse: 0.6 },
  thinking: { spin: 0.9, twist: 1, bulge: 0.15, pulse: 0 },
  speaking: { spin: 0.35, twist: 0.1, bulge: 1, pulse: 1 },
};

const BUCKETS = 6;

export type GridOrbProps = {
  state?: VoiceState;
  mic?: boolean;
  /** Optional 0..1 loudness from your own audio pipeline. */
  level?: number;
  size?: number;
  /** Latitude rings and longitude meridians. */
  rings?: number;
  meridians?: number;
  color?: string;
  /** Show the floor reflection under the orb. */
  floor?: boolean;
  onMicError?: (message: string | null) => void;
  className?: string;
};

/** A shaded wireframe globe whose grid bulges, pulses and twists with the voice. */
export function GridOrb({ state = 'idle', mic, level, size = 300, rings = 11, meridians = 20, color = '#7dd3fc', floor = true, onMicError, className }: GridOrbProps) {
  const ref = useRef<HTMLCanvasElement>(null);
  const voice = useVoice(state, { mic, level });
  useEffect(() => onMicError?.(voice.micError), [voice.micError, onMicError]);
  const ease = useRef(easer());
  const clock = useRef({ last: 0, rot: 0, ph: 0 });
  const [cr, cg, cb] = rgb(color);
  const height = floor ? Math.round(size * 1.18) : size;

  // reusable depth-bucketed paths
  const paths = useRef<Path2D[]>([]);

  useCanvasLoop(ref, Math.max(size, height), (g, now, slow) => {
    const f = voice.sample(now);
    const c = clock.current;
    const dt = c.last ? Math.min(0.05, (now - c.last) / 1000) : 0.016;
    c.last = now;
    const tg = TARGET[f.state];
    const e = ease.current;
    const spin = e('spin', tg.spin, dt, 1.6);
    const twist = e('twist', tg.twist, dt, 2);
    const bulge = e('bulge', tg.bulge, dt, 3);
    const pulse = e('pulse', tg.pulse, dt, 3);
    c.rot += dt * spin * slow;
    c.ph += dt * (1.5 + f.level * 3) * slow;
    const L = f.level;
    const t = f.t;
    const W = Math.max(size, height);
    const cx = W / 2;
    const cy = size / 2 + (W - height) / 2;
    const R = size * 0.33 * (1 + L * 0.06 * pulse);
    const tilt = 0.42;
    const ct = Math.cos(tilt);
    const st = Math.sin(tilt);

    const project = (lat: number, lon: number) => {
      // twist: meridians wind around the axis while thinking
      const lo = lon + c.rot + twist * Math.sin(c.ph * 0.8) * lat * 1.4;
      const cl = Math.cos(lat);
      let x = cl * Math.cos(lo);
      let y = Math.sin(lat);
      let z = cl * Math.sin(lo);
      // voice: bands bulge the grid outward by latitude, strongest facing the viewer
      const bi = Math.min(BANDS - 1, Math.floor(((lat / Math.PI) + 0.5) * BANDS));
      const facing = Math.max(0, z);
      const k = 1 + bulge * (f.bands[bi] * 0.22 * (0.4 + facing * 0.9)) + Math.sin(lat * 5 - c.ph * 2) * 0.02 * pulse * L;
      x *= k;
      y *= k;
      z *= k;
      const y2 = y * ct - z * st;
      const z2 = y * st + z * ct;
      const p = 3.4 / (3.4 - z2);
      return [cx + x * R * p, cy + y2 * R * p, z2] as const;
    };

    g.clearRect(0, 0, W, W);

    // shaded core behind the grid
    const core = g.createRadialGradient(cx - R * 0.35, cy - R * 0.45, R * 0.05, cx, cy, R * 1.15);
    core.addColorStop(0, `rgba(${cr},${cg},${cb},${0.22 + L * 0.25})`);
    core.addColorStop(0.55, `rgba(${cr * 0.25},${cg * 0.3},${cb * 0.45},0.35)`);
    core.addColorStop(1, 'rgba(0,0,0,0)');
    g.fillStyle = core;
    g.beginPath();
    g.arc(cx, cy, R * 1.12, 0, Math.PI * 2);
    g.fill();

    // halo
    const halo = g.createRadialGradient(cx, cy, R * 0.9, cx, cy, R * 1.7);
    halo.addColorStop(0, `rgba(${cr},${cg},${cb},${0.1 + L * 0.3})`);
    halo.addColorStop(1, 'rgba(0,0,0,0)');
    g.fillStyle = halo;
    g.fillRect(0, 0, W, W);

    // build depth buckets
    for (let b = 0; b < BUCKETS; b++) paths.current[b] = new Path2D();
    const seg = (a: readonly [number, number, number], b: readonly [number, number, number]) => {
      const d = ((a[2] + b[2]) / 2 + 1) / 2;
      const p = paths.current[Math.max(0, Math.min(BUCKETS - 1, Math.floor(d * BUCKETS)))];
      p.moveTo(a[0], a[1]);
      p.lineTo(b[0], b[1]);
    };
    const STEPS = 56;
    for (let i = 1; i < rings; i++) {
      const lat = -Math.PI / 2 + (i / rings) * Math.PI;
      let prev = project(lat, 0);
      for (let s = 1; s <= STEPS; s++) {
        const cur = project(lat, (s / STEPS) * Math.PI * 2);
        seg(prev, cur);
        prev = cur;
      }
    }
    for (let m = 0; m < meridians; m++) {
      const lon = (m / meridians) * Math.PI * 2;
      let prev = project(-Math.PI / 2, lon);
      for (let s = 1; s <= STEPS / 2; s++) {
        const cur = project(-Math.PI / 2 + (s / (STEPS / 2)) * Math.PI, lon);
        seg(prev, cur);
        prev = cur;
      }
    }

    g.lineCap = 'round';
    g.globalCompositeOperation = 'lighter';
    for (let b = 0; b < BUCKETS; b++) {
      const d = (b + 0.5) / BUCKETS;
      const a = 0.05 + Math.pow(d, 2.2) * (0.55 + L * 0.45);
      const w = (0.5 + d * 0.9) * Math.max(0.8, size / 300);
      const mix = Math.pow(d, 3) * (0.3 + L * 0.7);
      const r = cr + (255 - cr) * mix;
      const gg = cg + (255 - cg) * mix;
      const bl = cb + (255 - cb) * mix;
      g.strokeStyle = `rgba(${r | 0},${gg | 0},${bl | 0},${a})`;
      g.lineWidth = w;
      g.stroke(paths.current[b]);
    }

    // specular sheen
    const sheen = g.createRadialGradient(cx - R * 0.4, cy - R * 0.5, 0, cx - R * 0.4, cy - R * 0.5, R * 0.7);
    sheen.addColorStop(0, `rgba(255,255,255,${0.12 + L * 0.12})`);
    sheen.addColorStop(1, 'rgba(255,255,255,0)');
    g.fillStyle = sheen;
    g.fillRect(0, 0, W, W);
    g.globalCompositeOperation = 'source-over';

    if (floor) {
      // a soft reflection pool and a perspective floor grid
      const fy = cy + R * 1.32;
      const pool = g.createRadialGradient(cx, fy, 0, cx, fy, R * 1.1);
      pool.addColorStop(0, `rgba(${cr},${cg},${cb},${0.16 + L * 0.3})`);
      pool.addColorStop(1, 'rgba(0,0,0,0)');
      g.save();
      g.translate(cx, fy);
      g.scale(1, 0.18);
      g.translate(-cx, -fy);
      g.fillStyle = pool;
      g.fillRect(cx - R * 1.2, fy - R * 1.2, R * 2.4, R * 2.4);
      g.restore();
      g.lineWidth = 0.6;
      for (let i = 1; i <= 4; i++) {
        const yy = fy + i * i * 1.6 * (size / 300);
        const half = R * (0.5 + i * 0.18);
        g.strokeStyle = `rgba(${cr},${cg},${cb},${0.11 - i * 0.02})`;
        g.beginPath();
        g.moveTo(cx - half, yy);
        g.lineTo(cx + half, yy);
        g.stroke();
      }
    }
  });

  const W = Math.max(size, height);
  return (
    <canvas
      ref={ref}
      role="img"
      aria-label={`Voice assistant, ${voice.micLive ? 'listening to your microphone' : state}`}
      className={cn('block shrink-0', className)}
      style={{ width: W, height: W }}
    />
  );
}

export function GridOrbDemo() {
  return (
    <VoiceStage>
      {({ state, mic, setMicError, toggle }) => (
        <button onClick={toggle} aria-label="Toggle voice" className="focus-ring rounded-full transition-transform duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] active:scale-95">
          <GridOrb state={state} mic={mic} onMicError={setMicError} size={280} />
        </button>
      )}
    </VoiceStage>
  );
}
