(function () {
    if (window.MainppDigitalSignature) return;

    let modal = null;
    let canvas = null;
    let ctx = null;
    let drawing = false;
    let hasInk = false;
    let currentOptions = null;

    function injectStyles() {
        if (document.getElementById('mainpp_digital_signature_styles')) return;
        const style = document.createElement('style');
        style.id = 'mainpp_digital_signature_styles';
        style.textContent = `
            .digital-signature-modal{position:fixed;inset:0;z-index:4000;display:none;align-items:center;justify-content:center;background:rgba(15,23,42,.46);padding:20px}
            .digital-signature-modal.active{display:flex}
            .digital-signature-dialog{width:min(620px,100%);background:#fff;border-radius:12px;box-shadow:0 24px 70px rgba(15,23,42,.24);padding:20px;color:#14324a}
            .digital-signature-dialog h4{margin:0 0 8px;color:#005f99;font-size:1.05rem}
            .digital-signature-dialog p{margin:0 0 14px;color:#52697c;font-size:.9rem;line-height:1.45}
            .digital-signature-choice,.digital-signature-actions{display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end;margin-top:14px}
            .digital-signature-canvas-wrap{border:1px solid #b9d8eb;border-radius:10px;background:#fff;padding:10px}
            .digital-signature-canvas{width:100%;height:210px;display:block;touch-action:none;background:#fff;border:1px dashed #9cc7dd;border-radius:8px}
            .digital-signature-draw{display:none}
            .digital-signature-modal.drawing-mode .digital-signature-choice{display:none}
            .digital-signature-modal.drawing-mode .digital-signature-draw{display:block}
        `;
        document.head.appendChild(style);
    }

    function createModal() {
        injectStyles();
        modal = document.createElement('div');
        modal.className = 'digital-signature-modal';
        modal.setAttribute('aria-hidden', 'true');
        modal.innerHTML = `
            <div class="digital-signature-dialog" role="dialog" aria-modal="true" aria-labelledby="digital_signature_title">
                <h4 id="digital_signature_title"><i class="fas fa-signature"></i> Tandatangan</h4>
                <p>Pilih tandatangan sedia ada atau lukis tandatangan digital khusus untuk dokumen ini.</p>
                <div class="digital-signature-choice">
                    <button type="button" class="btn btn-secondary" data-digital-signature-action="cancel"><i class="fas fa-xmark"></i> Batal</button>
                    <button type="button" class="btn btn-warning" data-digital-signature-action="profile"><i class="fas fa-id-card"></i> Tandatangan sedia ada</button>
                    <button type="button" class="btn btn-primary" data-digital-signature-action="draw"><i class="fas fa-pen"></i> Buat Tandatangan Digital</button>
                </div>
                <div class="digital-signature-draw">
                    <div class="digital-signature-canvas-wrap">
                        <canvas class="digital-signature-canvas" width="900" height="300"></canvas>
                    </div>
                    <div class="digital-signature-actions">
                        <button type="button" class="btn btn-secondary" data-digital-signature-action="back"><i class="fas fa-arrow-left"></i> Kembali</button>
                        <button type="button" class="btn btn-secondary" data-digital-signature-action="clear"><i class="fas fa-eraser"></i> Padam</button>
                        <button type="button" class="btn btn-primary" data-digital-signature-action="use"><i class="fas fa-check"></i> Gunakan Tandatangan</button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        canvas = modal.querySelector('canvas');
        ctx = canvas.getContext('2d');
        resetCanvas();

        modal.addEventListener('click', event => {
            if (event.target === modal) close();
            const button = event.target.closest('[data-digital-signature-action]');
            if (!button) return;
            const action = button.dataset.digitalSignatureAction;
            if (action === 'cancel') close();
            if (action === 'profile') useProfile();
            if (action === 'draw') showDraw();
            if (action === 'back') showChoice();
            if (action === 'clear') resetCanvas();
            if (action === 'use') useDrawn();
        });

        canvas.addEventListener('pointerdown', startDraw);
        canvas.addEventListener('pointermove', draw);
        canvas.addEventListener('pointerup', stopDraw);
        canvas.addEventListener('pointerleave', stopDraw);
        window.addEventListener('resize', resetCanvasIfBlank);
    }

    function point(event) {
        const rect = canvas.getBoundingClientRect();
        return {
            x: (event.clientX - rect.left) * (canvas.width / rect.width),
            y: (event.clientY - rect.top) * (canvas.height / rect.height)
        };
    }

    function resetCanvas() {
        if (!ctx) return;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.strokeStyle = '#111827';
        ctx.lineWidth = 4;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        hasInk = false;
    }

    function resetCanvasIfBlank() {
        if (!hasInk) resetCanvas();
    }

    function startDraw(event) {
        drawing = true;
        hasInk = true;
        canvas.setPointerCapture?.(event.pointerId);
        const p = point(event);
        ctx.beginPath();
        ctx.moveTo(p.x, p.y);
    }

    function draw(event) {
        if (!drawing) return;
        const p = point(event);
        ctx.lineTo(p.x, p.y);
        ctx.stroke();
    }

    function stopDraw(event) {
        if (!drawing) return;
        drawing = false;
        canvas.releasePointerCapture?.(event.pointerId);
    }

    function showDraw() {
        modal.classList.add('drawing-mode');
        resetCanvas();
    }

    function showChoice() {
        modal.classList.remove('drawing-mode');
    }

    function useProfile() {
        const path = (currentOptions?.profileSignaturePath || '').trim();
        if (!path) {
            alert('Tandatangan sedia ada belum didaftarkan dalam profil pengguna.');
            return;
        }
        currentOptions?.onUseSignature?.(path, 'profile');
        close();
    }

    function useDrawn() {
        if (!hasInk) {
            alert('Sila lukis tandatangan digital terlebih dahulu.');
            return;
        }
        currentOptions?.onUseSignature?.(canvas.toDataURL('image/png'), 'digital');
        close();
    }

    function close() {
        modal?.classList.remove('active', 'drawing-mode');
        modal?.setAttribute('aria-hidden', 'true');
        currentOptions = null;
        drawing = false;
    }

    window.MainppDigitalSignature = {
        open(options) {
            if (!modal) createModal();
            currentOptions = options || {};
            const profileButton = modal.querySelector('[data-digital-signature-action="profile"]');
            if (profileButton) {
                profileButton.style.display = currentOptions.profileSignaturePath ? '' : 'none';
            }
            showChoice();
            modal.classList.add('active');
            modal.setAttribute('aria-hidden', 'false');
        }
    };
})();
