// Signature pad — small <canvas> drawable signature, persists as a data-URL.
const { useEffect, useRef, useState } = React;

function SignaturePad({ label, role, value, onChange, disabled }) {
  const canvasRef = useRef(null);
  const drawing = useRef(false);
  const last = useRef({ x: 0, y: 0 });
  const [empty, setEmpty] = useState(!value);

  // Set up canvas + redraw saved signature
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.strokeStyle = '#15110d';
    ctx.lineWidth = 1.8;

    if (value) {
      const img = new Image();
      img.onload = () => {
        ctx.clearRect(0, 0, rect.width, rect.height);
        ctx.drawImage(img, 0, 0, rect.width, rect.height);
        setEmpty(false);
      };
      img.src = value;
    } else {
      setEmpty(true);
    }
  }, [value]);

  const getPos = (e) => {
    const rect = canvasRef.current.getBoundingClientRect();
    const t = e.touches ? e.touches[0] : e;
    return { x: t.clientX - rect.left, y: t.clientY - rect.top };
  };

  const start = (e) => {
    if (disabled) return;
    e.preventDefault();
    drawing.current = true;
    last.current = getPos(e);
    setEmpty(false);
  };
  const move = (e) => {
    if (!drawing.current || disabled) return;
    e.preventDefault();
    const p = getPos(e);
    const ctx = canvasRef.current.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(last.current.x, last.current.y);
    ctx.lineTo(p.x, p.y);
    ctx.stroke();
    last.current = p;
  };
  const end = () => {
    if (!drawing.current) return;
    drawing.current = false;
    onChange(canvasRef.current.toDataURL('image/png'));
  };

  const clear = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const rect = canvas.getBoundingClientRect();
    ctx.clearRect(0, 0, rect.width, rect.height);
    setEmpty(true);
    onChange('');
  };

  return (
    <div className="sig-block">
      <div className={`sig-pad ${empty ? '' : 'signed'}`}>
        <canvas
          ref={canvasRef}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end}
        />
        {empty && <div className="ph">Sign here</div>}
      </div>
      <div className="sig-meta">
        <div>
          <b>{label}</b>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>{role}</div>
        </div>
        {!empty && (
          <button onClick={clear} disabled={disabled}>Clear</button>
        )}
      </div>
    </div>
  );
}

window.SignaturePad = SignaturePad;
