"use client";

// components/ui/SuccessCheck.tsx
// The Transitions.dev "success check" (recipe 10): a checkmark that fades in,
// rotates upright, settles with a Y-bob, and draws its stroke. Used at the
// donation-confirmed moment so the payoff feels earned, not instantaneous.
//
// The animation + reduced-motion guard live in globals.css (.t-success-check).
// This component only: (1) measures the path length so the stroke draws cleanly,
// and (2) flips data-state to "in" on mount to play the appear. Under reduced
// motion the CSS forces the check visible + fully drawn with no animation, so no
// JS motion guard is needed here.
//
// Decorative: aria-hidden. The surrounding copy ("Listo. Ya estás participando")
// carries the meaning for assistive tech.

import * as React from "react";

export interface SuccessCheckProps {
  /** Rendered size in px (square). */
  size?: number;
  className?: string;
}

export function SuccessCheck({ size = 56, className }: SuccessCheckProps) {
  const ref = React.useRef<HTMLSpanElement>(null);

  React.useEffect(() => {
    const wrap = ref.current;
    if (!wrap) return;
    const path = wrap.querySelector<SVGPathElement>("path[data-check-stroke]");
    if (path) {
      // Measure the actual path length so the dasharray matches it exactly
      // (the CSS placeholder of 20 is overridden here).
      const len = Math.ceil(path.getTotalLength());
      path.style.strokeDasharray = String(len);
      path.style.strokeDashoffset = String(len);
    }
    // Flip to "in" on the next frame so the keyframes start from a clean state.
    const id = window.requestAnimationFrame(() => {
      wrap.setAttribute("data-state", "in");
    });
    return () => window.cancelAnimationFrame(id);
  }, []);

  return (
    <span
      ref={ref}
      className={["t-success-check", className].filter(Boolean).join(" ")}
      data-state="out"
      aria-hidden="true"
      style={{ width: size, height: size }}
    >
      <svg viewBox="0 0 52 52" width={size} height={size} fill="none">
        <circle cx="26" cy="26" r="25" fill="var(--brand-primary)" />
        <path
          data-check-stroke=""
          d="M16 27 l7 7 l13 -15"
          stroke="var(--brand-on-primary)"
          strokeWidth="4"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </span>
  );
}
