/**
 * Minimal Alpine.js-compatible signature pad.
 * Exposes dataUrl for form submission after commit().
 */
function signaturePad() {
  return {
    ctx: null,
    canvas: null,
    drawing: false,
    dataUrl: '',

    init(canvas) {
      this.canvas = canvas;
      const rect = canvas.getBoundingClientRect();
      canvas.width  = rect.width * 2;
      canvas.height = rect.height * 2;
      canvas.style.width = rect.width + 'px';
      canvas.style.height = rect.height + 'px';
      this.ctx = canvas.getContext('2d');
      this.ctx.scale(2, 2);
      this.ctx.strokeStyle = '#0a0a0a';
      this.ctx.lineWidth = 2;
      this.ctx.lineCap = 'round';
      this.ctx.lineJoin = 'round';

      const getPos = (e) => {
        const r = canvas.getBoundingClientRect();
        const t = e.touches ? e.touches[0] : e;
        return { x: t.clientX - r.left, y: t.clientY - r.top };
      };
      const start = (e) => { e.preventDefault(); this.drawing = true; const p = getPos(e); this.ctx.beginPath(); this.ctx.moveTo(p.x, p.y); };
      const move  = (e) => { if (!this.drawing) return; e.preventDefault(); const p = getPos(e); this.ctx.lineTo(p.x, p.y); this.ctx.stroke(); };
      const end   = ()  => { this.drawing = false; };

      canvas.addEventListener('mousedown', start);
      canvas.addEventListener('mousemove', move);
      canvas.addEventListener('mouseup', end);
      canvas.addEventListener('mouseleave', end);
      canvas.addEventListener('touchstart', start, { passive: false });
      canvas.addEventListener('touchmove',  move,  { passive: false });
      canvas.addEventListener('touchend',   end);
    },

    clear() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.dataUrl = ''; },
    commit() { this.dataUrl = this.canvas.toDataURL('image/png'); },
  };
}
window.signaturePad = signaturePad;
