(function () {
    'use strict';

    function initWizard() {
    const wizard = document.getElementById('regWizard');
    if (!wizard) {
        return;
    }

    const i18n = window.KARVI_I18N || {};
    const token = wizard.dataset.token || '';
    let pdfViewed = wizard.dataset.pdfViewed || '';
    const ownerCount = parseInt(wizard.dataset.ownerCount || '1', 10);
    const ownerNames = JSON.parse(wizard.dataset.ownerNames || '[]');
    let currentStep = parseInt(wizard.dataset.initialStep || '1', 10);
    let currentOwnerIndex = parseInt(wizard.dataset.initialOwnerIndex || '0', 10);
    let signMode = null;

    const panels = wizard.querySelectorAll('[data-step-panel]');
    const stepIndicators = wizard.querySelectorAll('[data-step-indicator]');
    const backBtn = document.getElementById('regBackBtn');
    const nextBtn = document.getElementById('regNextBtn');
    const ownerIndexInput = document.getElementById('ownerIndex');
    const signerNameInput = document.getElementById('signerName');
    const signerDisplayName = document.getElementById('signerDisplayName');
    const signMethodButtons = document.getElementById('signMethodButtons');
    const uploadPanel = document.getElementById('uploadPanel');
    const drawPanel = document.getElementById('drawPanel');
    const uploadPreview = document.getElementById('uploadPreview');
    const btnOpenDraw = document.getElementById('btnOpenDraw');
    const btnOpenUpload = document.getElementById('btnOpenUpload');
    const registrationEmailInput = document.getElementById('registrationEmail');
    const registrationEmailUrl = wizard.dataset.registrationEmailUrl || (window.karviPath ? window.karviPath('/api/registration-email') : '/api/registration-email');
    const pdfViewedUrl = wizard.dataset.pdfViewedUrl || (window.karviPath ? window.karviPath('/api/pdf-viewed') : '/api/pdf-viewed');
    const signUrl = wizard.dataset.signUrl || (window.karviPath ? window.karviPath('/api/sign') : '/api/sign');

    function hasUploadPreview() {
        return uploadPreview && !uploadPreview.classList.contains('hidden') && uploadPreview.src;
    }

    function hasDrawSignature() {
        return window.KarviSignature && window.KarviSignature.hasSignature();
    }

    function showDrawMode() {
        signMode = 'draw';
        if (signMethodButtons) {
            signMethodButtons.classList.add('hidden');
        }
        if (uploadPanel) {
            uploadPanel.classList.add('hidden');
        }
        if (drawPanel) {
            drawPanel.classList.remove('hidden');
        }
        window.dispatchEvent(new CustomEvent('reg-draw-opened'));
        updateFooter();
    }

    function showUploadMode() {
        signMode = 'upload';
        if (signMethodButtons) {
            signMethodButtons.classList.add('hidden');
        }
        if (drawPanel) {
            drawPanel.classList.add('hidden');
        }
        if (uploadPanel) {
            uploadPanel.classList.remove('hidden');
        }
        updateFooter();
    }

    function resetChoiceScreen() {
        signMode = null;
        if (signMethodButtons) {
            signMethodButtons.classList.remove('hidden');
        }
        if (uploadPanel) {
            uploadPanel.classList.add('hidden');
        }
        if (drawPanel) {
            drawPanel.classList.add('hidden');
        }
    }

    function showPanel(step) {
        panels.forEach(function (panel) {
            const panelStep = panel.getAttribute('data-step-panel');
            panel.classList.toggle('hidden', panelStep !== String(step));
        });

        stepIndicators.forEach(function (item) {
            const indicatorStep = parseInt(item.getAttribute('data-step-indicator') || '0', 10);
            item.classList.remove('active', 'done');
            if (indicatorStep < step) {
                item.classList.add('done');
            } else if (indicatorStep === step) {
                item.classList.add('active');
            }
        });
    }

    function updateOwnerUi() {
        const defaultName = ownerNames[currentOwnerIndex] || '';

        if (ownerIndexInput) {
            ownerIndexInput.value = String(currentOwnerIndex);
        }
        if (signerNameInput) {
            signerNameInput.value = defaultName;
        }
        if (signerDisplayName) {
            signerDisplayName.textContent = defaultName || ('Owner ' + (currentOwnerIndex + 1));
        }

        const isLastOwner = currentOwnerIndex >= ownerCount - 1;
        nextBtn.textContent = isLastOwner
            ? (i18n.reg_submit || 'Submit')
            : (i18n.reg_next || 'Next');
    }

    function showFinalSuccessScreen() {
        showPanel('success');
        wizard.classList.remove('reg-shell-step3');
        document.body.classList.remove('reg-step-doc-active');
        backBtn.classList.add('hidden');
        nextBtn.classList.add('hidden');
        wizard.classList.add('reg-shell-complete');
        const regFooter = wizard.querySelector('.reg-footer');
        if (regFooter) {
            regFooter.classList.add('hidden');
        }
    }

    function updateFooter() {
        backBtn.classList.toggle('hidden', currentStep <= 1);

        if (currentStep === 1) {
            nextBtn.disabled = false;
            nextBtn.textContent = i18n.reg_next || 'Next';
            return;
        }

        if (currentStep === 2) {
            nextBtn.disabled = false;
            nextBtn.textContent = i18n.reg_next || 'Next';
            return;
        }

        if (currentStep === 3) {
            updateOwnerUi();
            if (signMode === 'upload') {
                nextBtn.disabled = !hasUploadPreview();
                return;
            }
            if (signMode === 'draw') {
                nextBtn.disabled = !hasDrawSignature();
                return;
            }
            nextBtn.disabled = true;
            nextBtn.textContent = i18n.reg_next || 'Next';
        }
    }

    function goToStep(step) {
        if (currentStep === 3 && step !== 3) {
            resetChoiceScreen();
            if (window.KarviSignature) {
                window.KarviSignature.reset();
            }
        }

        currentStep = step;
        showPanel(step);
        wizard.classList.toggle('reg-shell-step3', step === 3);
        wizard.classList.toggle('reg-shell-step2', step === 2);
        document.body.classList.toggle('reg-step-doc-active', step === 2);
        updateFooter();

        if (step === 3) {
            resetChoiceScreen();
            updateOwnerUi();
            if (window.KarviSignature) {
                window.KarviSignature.reset();
            }
        }
    }

    function getRegistrationEmail() {
        return registrationEmailInput ? registrationEmailInput.value.trim() : '';
    }

    function isValidOptionalEmail(value) {
        if (value === '') {
            return true;
        }

        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
    }

    async function saveRegistrationEmail() {
        const registrationEmail = getRegistrationEmail();

        if (!isValidOptionalEmail(registrationEmail)) {
            alert(i18n.reg_document_email_invalid || 'Please enter a valid email address or leave this field empty.');
            return false;
        }

        const formData = new FormData();
        formData.set('token', token);
        formData.set('registration_email', registrationEmail);

        try {
            const response = await fetch(registrationEmailUrl, { method: 'POST', body: formData });
            const result = await response.json();
            if (!result.success) {
                alert(result.message || i18n.js_alert_fail || 'Submission failed.');
                return false;
            }
        } catch (error) {
            /* optional field — continue even if save fails */
        }

        return true;
    }

    async function recordPdfViewed() {
        if (pdfViewed !== '') {
            return pdfViewed;
        }

        const formData = new FormData();
        formData.set('token', token);

        try {
            const response = await fetch(pdfViewedUrl, { method: 'POST', body: formData });
            const result = await response.json();
            if (result.success) {
                pdfViewed = result.pdf_viewed_at || new Date().toISOString();
            }
        } catch (error) {
            /* keep going even if tracking fails */
        }

        return pdfViewed;
    }

    async function submitOwnerSignature(forcedMethod) {
        const signerName = (signerNameInput ? signerNameInput.value.trim() : '') || ownerNames[currentOwnerIndex] || ('Owner ' + (currentOwnerIndex + 1));
        if (signerNameInput) {
            signerNameInput.value = signerName;
        }

        let signature = null;
        if (forcedMethod === 'upload' || signMode === 'upload') {
            if (!hasUploadPreview()) {
                alert(i18n.js_alert_upload || 'Please upload your signature image.');
                return;
            }
            signature = { data: uploadPreview.src, method: 'upload' };
        } else {
            if (!hasDrawSignature()) {
                alert(i18n.js_alert_draw || 'Please draw your signature on the screen.');
                return;
            }
            signature = { data: window.KarviSignature.toDataUrl(), method: 'draw' };
        }

        nextBtn.disabled = true;
        nextBtn.textContent = i18n.submitting || 'Submitting...';

        const formData = new FormData();
        formData.set('token', token);
        formData.set('owner_index', String(currentOwnerIndex));
        formData.set('signer_name', signerName);
        formData.set('signature_data', signature.data);
        formData.set('signature_method', signature.method);
        formData.set('agreed', '1');
        formData.set('user_agent', navigator.userAgent);
        formData.set('screen_resolution', screen.width + 'x' + screen.height);
        formData.set('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
        formData.set('registration_email', getRegistrationEmail());

        const isLastOwner = currentOwnerIndex >= ownerCount - 1;

        try {
            const response = await fetch(signUrl, { method: 'POST', body: formData });
            let result = null;

            try {
                result = await response.json();
            } catch (parseError) {
                result = {
                    success: false,
                    message: 'Invalid server response.',
                    parse_error: String(parseError),
                };
            }

            if (isLastOwner) {
                if (result.success && result.is_final) {
                    showFinalSuccessScreen();
                } else {
                    alert(result.message || i18n.js_alert_fail || 'Submission failed.');
                    nextBtn.disabled = false;
                    updateFooter();
                }
                return;
            }

            if (!result.success) {
                alert(result.message || i18n.js_alert_fail || 'Submission failed.');
                updateFooter();
                return;
            }

            currentOwnerIndex += 1;
            resetChoiceScreen();
            if (window.KarviSignature) {
                window.KarviSignature.reset();
            }
            updateOwnerUi();
            updateFooter();
        } catch (error) {
            alert(i18n.js_alert_network || 'Network error.');
            updateFooter();
        } finally {
            updateOwnerUi();
        }
    }

    backBtn.addEventListener('click', function () {
        if (currentStep === 3 && (signMode === 'upload' || signMode === 'draw')) {
            resetChoiceScreen();
            if (window.KarviSignature) {
                window.KarviSignature.reset();
            }
            updateFooter();
            return;
        }

        if (currentStep > 1) {
            goToStep(currentStep - 1);
        }
    });

    nextBtn.addEventListener('click', function () {
        if (currentStep === 1) {
            goToStep(2);
            return;
        }

        if (currentStep === 2) {
            if (!isValidOptionalEmail(getRegistrationEmail())) {
                alert(i18n.reg_document_email_invalid || 'Please enter a valid email address or leave this field empty.');
                return;
            }

            nextBtn.disabled = true;
            Promise.all([recordPdfViewed(), saveRegistrationEmail()]).then(function (results) {
                nextBtn.disabled = false;
                if (results[1] === false) {
                    return;
                }
                goToStep(3);
            });
            return;
        }

        if (currentStep === 3 && signMode === 'upload') {
            submitOwnerSignature('upload');
            return;
        }

        if (currentStep === 3 && signMode === 'draw') {
            submitOwnerSignature('draw');
        }
    });

    if (btnOpenDraw) {
        btnOpenDraw.addEventListener('click', showDrawMode);
    }

    if (btnOpenUpload) {
        btnOpenUpload.addEventListener('click', showUploadMode);
    }

    window.addEventListener('reg-upload-changed', function () {
        if (currentStep === 3) {
            updateFooter();
        }
    });

    window.addEventListener('reg-draw-changed', function () {
        if (currentStep === 3) {
            updateFooter();
        }
    });

    goToStep(currentStep);
    }

    if (document.body.classList.contains('reg-location-pending') && !document.body.classList.contains('reg-location-ready')) {
        document.addEventListener('karvi:location-ready', initWizard, { once: true });
    } else {
        initWizard();
    }
})();
