"use client";
import { useEffect, useRef } from "react";

/** Firma con dedo o mouse. Devuelve un data URI PNG al soltar. */
export function SignaturePad({ value, onChange }: { value?: string | null; onChange: (dataUrl: string | null) => void }) {
  const ref = useRef<HTMLCanvasElement>(null);
  const drawing = useRef(false);

  useEffect(() => {
    const c = ref.current!;
    const r = c.getBoundingClientRect();
    c.width = r.width;
    c.height = r.height;
    const g = c.getContext("2d")!;
    g.lineWidth = 2;
    g.lineCap = "round";
    g.strokeStyle = getComputedStyle(c).color;
    if (value) {
      const img = new Image();
      img.onload = () => g.drawImage(img, 0, 0, c.width, c.height);
      img.src = value;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const pt = (e: React.PointerEvent) => {
    const b = ref.current!.getBoundingClientRect();
    return [e.clientX - b.left, e.clientY - b.top] as const;
  };

  return (
    <>
      <canvas
        ref={ref}
        className="sigpad"
        aria-label="Firma del paciente"
        onPointerDown={(e) => { drawing.current = true; ref.current!.setPointerCapture(e.pointerId); const g = ref.current!.getContext("2d")!; g.beginPath(); g.moveTo(...pt(e)); }}
        onPointerMove={(e) => { if (!drawing.current) return; const g = ref.current!.getContext("2d")!; g.lineTo(...pt(e)); g.stroke(); }}
        onPointerUp={() => { drawing.current = false; onChange(ref.current!.toDataURL("image/png")); }}
      />
      <div className="spread">
        <small className="muted">Firma del paciente con el dedo o el mouse</small>
        <button type="button" className="btn sm" onClick={() => { const c = ref.current!; c.getContext("2d")!.clearRect(0, 0, c.width, c.height); onChange(null); }}>Borrar firma</button>
      </div>
    </>
  );
}
