(function () {
    function initPad(host) {
        if (host.dataset.sigInit === '1') return;
        host.dataset.sigInit = '1';

        const canvas = host.querySelector('.sig-canvas');
        const nameInput = host.querySelector('.sig-name');
        const clearBtn = host.querySelector('.sig-clear');
        const saveBtn = host.querySelector('.sig-save');
        const status = host.querySelector('.sig-status');
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        ctx.lineWidth = 2;
        ctx.lineCap = 'round';
        ctx.strokeStyle = '#111';

        let drawing = false;
        let last = null;

        function pos(ev) {
            const r = canvas.getBoundingClientRect();
            const x = (ev.clientX - r.left) * (canvas.width / r.width);
            const y = (ev.clientY - r.top) * (canvas.height / r.height);
            return { x, y };
        }
        function start(ev) { ev.preventDefault(); drawing = true; last = pos(ev); }
        function move(ev) {
            if (!drawing) return;
            ev.preventDefault();
            const p = pos(ev);
            ctx.beginPath();
            ctx.moveTo(last.x, last.y);
            ctx.lineTo(p.x, p.y);
            ctx.stroke();
            last = p;
        }
        function end() { drawing = false; last = null; }

        canvas.addEventListener('pointerdown', start);
        canvas.addEventListener('pointermove', move);
        canvas.addEventListener('pointerup', end);
        canvas.addEventListener('pointerleave', end);

        clearBtn?.addEventListener('click', () => ctx.clearRect(0, 0, canvas.width, canvas.height));

        saveBtn?.addEventListener('click', async () => {
            const dataUrl = canvas.toDataURL('image/png');
            const fd = new FormData();
            const csrfName = document.querySelector('meta[name="csrf-token-name"]')?.content || 'csrf_test_name';
            const csrfHash = document.querySelector('meta[name="csrf-token"]')?.content || '';
            fd.append(csrfName, csrfHash);
            fd.append('signable_type', host.dataset.signableType);
            fd.append('signable_id', host.dataset.signableId);
            fd.append('role', host.dataset.role);
            fd.append('name', nameInput?.value || '');
            fd.append('image', dataUrl);
            status.textContent = 'Guardando firma…';
            try {
                const r = await fetch(host.dataset.uploadUrl, {
                    method: 'POST',
                    body: fd,
                    credentials: 'same-origin',
                    headers: { 'X-CSRF-TOKEN': csrfHash },
                });
                const j = await r.json();
                if (j && j.csrf_token) {
                    document.querySelector('meta[name="csrf-token"]')?.setAttribute('content', j.csrf_token);
                }
                if (j.ok) {
                    status.textContent = '✓ Firma guardada';
                    if (host.dataset.fieldKey) {
                        const hidden = document.querySelector('input[data-bind="' + host.dataset.fieldKey + '"]');
                        if (hidden) {
                            hidden.value = j.path;
                            hidden.dispatchEvent(new Event('change', { bubbles: true }));
                        }
                    }
                } else {
                    status.textContent = '✗ ' + (j.msg || 'Error');
                }
            } catch (e) {
                status.textContent = '✗ Sin conexión';
            }
        });
    }

    document.querySelectorAll('.signature-pad').forEach(initPad);
})();
