'use client';

// Confetti Animation — NiceUI (MIT) · https://niceui.dev/c/effects/confetti
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useCallback, useEffect, useRef, useState, 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 PartyPopper = niceIcon([["path",{"d":"M5.8 11.3 2 22l10.7-3.79"}],["path",{"d":"M4 3h.01"}],["path",{"d":"M22 8h.01"}],["path",{"d":"M15 2h.01"}],["path",{"d":"M22 20h.01"}],["path",{"d":"m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10"}],["path",{"d":"m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17"}],["path",{"d":"m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7"}],["path",{"d":"M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z"}]]);
const Sparkles = niceIcon([["path",{"d":"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}],["path",{"d":"M20 3v4"}],["path",{"d":"M22 5h-4"}],["path",{"d":"M4 17v2"}],["path",{"d":"M5 18H3"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = ".focus-ring{outline:none}.focus-ring:focus-visible{box-shadow:0 0 0 2px #000,0 0 0 4px rgba(14,165,233,.6)}";
if (typeof document !== 'undefined' && !document.getElementById('niceui-css-10x759f')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-10x759f';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/effects/pointer/Confetti.tsx ─────────────────────
export type ConfettiOptions = {
  /** Origin in 0–1 of the canvas (x from left, y from top). */
  x?: number;
  y?: number;
  /** Launch angle in degrees (90 = straight up). */
  angle?: number;
  /** Cone width in degrees. */
  spread?: number;
  count?: number;
  /** Initial speed in px per frame. */
  speed?: number;
  colors?: string[];
};

type Piece = { x: number; y: number; vx: number; vy: number; rot: number; vr: number; w: number; h: number; c: string; life: number; shape: 0 | 1 | 2; wob: number };

const DEFAULT_COLORS = ['#7dd3fc', '#38bdf8', '#e0f2fe', '#c4b5fd', '#fda4af', '#fde68a', '#86efac'];

/**
 * Confetti animation on a canvas with an imperative `fire()` API.
 * Attach `ref` to a <canvas> that covers the area you want confetti in.
 */
export function useConfetti() {
  const ref = useRef<HTMLCanvasElement>(null);
  const pieces = useRef<Piece[]>([]);
  const raf = useRef(0);

  const loop = useCallback(() => {
    const c = ref.current;
    const g = c?.getContext('2d');
    if (!c || !g) return;
    const w = c.clientWidth;
    const h = c.clientHeight;
    const dpr = Math.min(2, window.devicePixelRatio || 1);
    if (c.width !== Math.round(w * dpr)) {
      c.width = Math.round(w * dpr);
      c.height = Math.round(h * dpr);
    }
    g.setTransform(dpr, 0, 0, dpr, 0, 0);
    g.clearRect(0, 0, w, h);
    const ps = pieces.current;
    for (let i = ps.length - 1; i >= 0; i--) {
      const p = ps[i];
      p.vy += 0.22;
      p.vx *= 0.985;
      p.vy *= 0.985;
      p.wob += 0.12;
      p.x += p.vx + Math.sin(p.wob) * 0.6;
      p.y += p.vy;
      p.rot += p.vr;
      p.life -= 0.004;
      if (p.y > h + 30 || p.life <= 0) {
        ps.splice(i, 1);
        continue;
      }
      g.save();
      g.globalAlpha = Math.min(1, p.life * 2);
      g.translate(p.x, p.y);
      g.rotate(p.rot);
      g.scale(1, Math.cos(p.wob));
      g.fillStyle = p.c;
      if (p.shape === 0) g.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
      else if (p.shape === 1) {
        g.beginPath();
        g.arc(0, 0, p.w / 2, 0, Math.PI * 2);
        g.fill();
      } else {
        g.beginPath();
        g.moveTo(0, -p.h / 2);
        g.lineTo(p.w / 2, p.h / 2);
        g.lineTo(-p.w / 2, p.h / 2);
        g.closePath();
        g.fill();
      }
      g.restore();
    }
    raf.current = ps.length ? requestAnimationFrame(loop) : 0;
  }, []);

  const fire = useCallback(
    (o: ConfettiOptions = {}) => {
      const c = ref.current;
      if (!c) return;
      const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      const { x = 0.5, y = 0.6, angle = 90, spread = 70, count = 120, speed = 13, colors = DEFAULT_COLORS } = o;
      const n = reduced ? Math.round(count / 4) : count;
      const ox = x * c.clientWidth;
      const oy = y * c.clientHeight;
      for (let i = 0; i < n; i++) {
        const a = ((angle + (Math.random() - 0.5) * spread) * Math.PI) / 180;
        const v = speed * (0.55 + Math.random() * 0.6);
        pieces.current.push({
          x: ox,
          y: oy,
          vx: Math.cos(a) * v,
          vy: -Math.sin(a) * v,
          rot: Math.random() * Math.PI,
          vr: (Math.random() - 0.5) * 0.3,
          w: 6 + Math.random() * 6,
          h: 8 + Math.random() * 8,
          c: colors[Math.floor(Math.random() * colors.length)],
          life: 1,
          shape: (Math.floor(Math.random() * 3) as 0 | 1 | 2),
          wob: Math.random() * 6,
        });
      }
      if (!raf.current) raf.current = requestAnimationFrame(loop);
    },
    [loop],
  );

  /** Two cannons from the bottom corners. */
  const cannons = useCallback(
    (o: Omit<ConfettiOptions, 'x' | 'y' | 'angle'> = {}) => {
      fire({ ...o, x: 0, y: 1, angle: 60, spread: 40, count: o.count ?? 90, speed: o.speed ?? 17 });
      fire({ ...o, x: 1, y: 1, angle: 120, spread: 40, count: o.count ?? 90, speed: o.speed ?? 17 });
    },
    [fire],
  );

  useEffect(() => () => cancelAnimationFrame(raf.current), []);
  return { ref, fire, cannons };
}

export function ConfettiDemo() {
  const { ref, fire, cannons } = useConfetti();
  const [done, setDone] = useState(false);
  return (
    <div className="relative grid h-[340px] w-full max-w-2xl place-items-center overflow-hidden rounded-2xl border border-white/[0.07] bg-[#000000]">
      <canvas ref={ref} aria-hidden className="pointer-events-none absolute inset-0 h-full w-full" />
      <div className="relative text-center">
        <p className={cn('text-sm text-[#8b9099] transition-opacity', done && 'opacity-0')}>Ship it, then celebrate.</p>
        <h3 className="mt-1 text-2xl font-semibold tracking-tight text-[#f3f4f6]">{done ? 'Deployed to production 🎉' : 'Your launch is ready'}</h3>
        <div className="mt-6 flex flex-wrap justify-center gap-2">
          <button
            onClick={(e) => {
              const c = ref.current!.getBoundingClientRect();
              const b = e.currentTarget.getBoundingClientRect();
              fire({ x: (b.left + b.width / 2 - c.left) / c.width, y: (b.top - c.top) / c.height });
              setDone(true);
            }}
            className="focus-ring inline-flex items-center gap-2 rounded-full bg-[#7dd3fc] px-5 py-2.5 text-sm font-medium text-[#000000] transition-transform active:scale-95"
          >
            <PartyPopper className="h-4 w-4" /> Burst
          </button>
          <button onClick={() => (cannons(), setDone(true))} className="focus-ring inline-flex items-center gap-2 rounded-full border border-white/10 px-5 py-2.5 text-sm text-[#c9cdd3] transition-transform active:scale-95">
            <Sparkles className="h-4 w-4" /> Side cannons
          </button>
        </div>
      </div>
    </div>
  );
}
